blob: f6db1fc1f7306fd23e176f079f56557eecc33526 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "compiler_driver.h"
18
Anwar Ghuloum67f99412013-08-12 14:19:48 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <utils/Trace.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
Anwar Ghuloum67f99412013-08-12 14:19:48 -070022#include <vector>
Brian Carlstrom7940e442013-07-12 13:46:57 -070023#include <unistd.h>
24
Mathieu Chartier25fda922014-12-03 17:38:22 -080025#ifndef __APPLE__
26#include <malloc.h> // For mallinfo
27#endif
28
Brian Carlstrom7940e442013-07-12 13:46:57 -070029#include "base/stl_util.h"
30#include "base/timing_logger.h"
31#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070032#include "compiled_class.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000033#include "compiler.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000034#include "compiler_driver-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070035#include "dex_compilation_unit.h"
36#include "dex_file-inl.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000037#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000038#include "dex/verified_method.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000039#include "dex/quick/dex_file_method_inliner.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080040#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "jni_internal.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070042#include "object_lock.h"
Calin Juravlebb0b53f2014-05-23 17:33:29 +010043#include "profiler.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070044#include "runtime.h"
45#include "gc/accounting/card_table-inl.h"
46#include "gc/accounting/heap_bitmap.h"
47#include "gc/space/space.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070048#include "mirror/art_field-inl.h"
49#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "mirror/class_loader.h"
51#include "mirror/class-inl.h"
52#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070053#include "mirror/object-inl.h"
54#include "mirror/object_array-inl.h"
55#include "mirror/throwable.h"
56#include "scoped_thread_state_change.h"
57#include "ScopedLocalRef.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070058#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "thread.h"
60#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070061#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010062#include "transaction.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063#include "verifier/method_verifier.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000064#include "verifier/method_verifier-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065
Brian Carlstrom7940e442013-07-12 13:46:57 -070066namespace art {
67
Ian Rogers6dd35cc2014-08-27 21:46:57 +000068static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
Mathieu Chartierb68c6e52014-08-19 14:29:46 -070069
Brian Carlstrom7940e442013-07-12 13:46:57 -070070static double Percentage(size_t x, size_t y) {
71 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
72}
73
74static void DumpStat(size_t x, size_t y, const char* str) {
75 if (x == 0 && y == 0) {
76 return;
77 }
Ian Rogerse732ef12013-10-09 15:22:24 -070078 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -070079}
80
Vladimir Markof096aad2014-01-23 15:51:58 +000081class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -070082 public:
83 AOTCompilationStats()
84 : stats_lock_("AOT compilation statistics lock"),
85 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
86 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
87 resolved_types_(0), unresolved_types_(0),
88 resolved_instance_fields_(0), unresolved_instance_fields_(0),
89 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
90 type_based_devirtualization_(0),
91 safe_casts_(0), not_safe_casts_(0) {
92 for (size_t i = 0; i <= kMaxInvokeType; i++) {
93 resolved_methods_[i] = 0;
94 unresolved_methods_[i] = 0;
95 virtual_made_direct_[i] = 0;
96 direct_calls_to_boot_[i] = 0;
97 direct_methods_to_boot_[i] = 0;
98 }
99 }
100
101 void Dump() {
102 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
103 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
104 DumpStat(resolved_types_, unresolved_types_, "types resolved");
105 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
106 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
107 "static fields resolved");
108 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
109 "static fields local to a class");
110 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
111 // Note, the code below subtracts the stat value so that when added to the stat value we have
112 // 100% of samples. TODO: clean this up.
113 DumpStat(type_based_devirtualization_,
114 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
115 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
116 type_based_devirtualization_,
117 "virtual/interface calls made direct based on type information");
118
119 for (size_t i = 0; i <= kMaxInvokeType; i++) {
120 std::ostringstream oss;
121 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
122 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
123 if (virtual_made_direct_[i] > 0) {
124 std::ostringstream oss2;
125 oss2 << static_cast<InvokeType>(i) << " methods made direct";
126 DumpStat(virtual_made_direct_[i],
127 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
128 oss2.str().c_str());
129 }
130 if (direct_calls_to_boot_[i] > 0) {
131 std::ostringstream oss2;
132 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
133 DumpStat(direct_calls_to_boot_[i],
134 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
135 oss2.str().c_str());
136 }
137 if (direct_methods_to_boot_[i] > 0) {
138 std::ostringstream oss2;
139 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
140 DumpStat(direct_methods_to_boot_[i],
141 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
142 oss2.str().c_str());
143 }
144 }
145 }
146
147// Allow lossy statistics in non-debug builds.
148#ifndef NDEBUG
149#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
150#else
151#define STATS_LOCK()
152#endif
153
154 void TypeInDexCache() {
155 STATS_LOCK();
156 types_in_dex_cache_++;
157 }
158
159 void TypeNotInDexCache() {
160 STATS_LOCK();
161 types_not_in_dex_cache_++;
162 }
163
164 void StringInDexCache() {
165 STATS_LOCK();
166 strings_in_dex_cache_++;
167 }
168
169 void StringNotInDexCache() {
170 STATS_LOCK();
171 strings_not_in_dex_cache_++;
172 }
173
174 void TypeDoesntNeedAccessCheck() {
175 STATS_LOCK();
176 resolved_types_++;
177 }
178
179 void TypeNeedsAccessCheck() {
180 STATS_LOCK();
181 unresolved_types_++;
182 }
183
184 void ResolvedInstanceField() {
185 STATS_LOCK();
186 resolved_instance_fields_++;
187 }
188
189 void UnresolvedInstanceField() {
190 STATS_LOCK();
191 unresolved_instance_fields_++;
192 }
193
194 void ResolvedLocalStaticField() {
195 STATS_LOCK();
196 resolved_local_static_fields_++;
197 }
198
199 void ResolvedStaticField() {
200 STATS_LOCK();
201 resolved_static_fields_++;
202 }
203
204 void UnresolvedStaticField() {
205 STATS_LOCK();
206 unresolved_static_fields_++;
207 }
208
209 // Indicate that type information from the verifier led to devirtualization.
210 void PreciseTypeDevirtualization() {
211 STATS_LOCK();
212 type_based_devirtualization_++;
213 }
214
215 // Indicate that a method of the given type was resolved at compile time.
216 void ResolvedMethod(InvokeType type) {
217 DCHECK_LE(type, kMaxInvokeType);
218 STATS_LOCK();
219 resolved_methods_[type]++;
220 }
221
222 // Indicate that a method of the given type was unresolved at compile time as it was in an
223 // unknown dex file.
224 void UnresolvedMethod(InvokeType type) {
225 DCHECK_LE(type, kMaxInvokeType);
226 STATS_LOCK();
227 unresolved_methods_[type]++;
228 }
229
230 // Indicate that a type of virtual method dispatch has been converted into a direct method
231 // dispatch.
232 void VirtualMadeDirect(InvokeType type) {
233 DCHECK(type == kVirtual || type == kInterface || type == kSuper);
234 STATS_LOCK();
235 virtual_made_direct_[type]++;
236 }
237
238 // Indicate that a method of the given type was able to call directly into boot.
239 void DirectCallsToBoot(InvokeType type) {
240 DCHECK_LE(type, kMaxInvokeType);
241 STATS_LOCK();
242 direct_calls_to_boot_[type]++;
243 }
244
245 // Indicate that a method of the given type was able to be resolved directly from boot.
246 void DirectMethodsToBoot(InvokeType type) {
247 DCHECK_LE(type, kMaxInvokeType);
248 STATS_LOCK();
249 direct_methods_to_boot_[type]++;
250 }
251
Vladimir Markof096aad2014-01-23 15:51:58 +0000252 void ProcessedInvoke(InvokeType type, int flags) {
253 STATS_LOCK();
254 if (flags == 0) {
255 unresolved_methods_[type]++;
256 } else {
257 DCHECK_NE((flags & kFlagMethodResolved), 0);
258 resolved_methods_[type]++;
259 if ((flags & kFlagVirtualMadeDirect) != 0) {
260 virtual_made_direct_[type]++;
261 if ((flags & kFlagPreciseTypeDevirtualization) != 0) {
262 type_based_devirtualization_++;
263 }
264 } else {
265 DCHECK_EQ((flags & kFlagPreciseTypeDevirtualization), 0);
266 }
267 if ((flags & kFlagDirectCallToBoot) != 0) {
268 direct_calls_to_boot_[type]++;
269 }
270 if ((flags & kFlagDirectMethodToBoot) != 0) {
271 direct_methods_to_boot_[type]++;
272 }
273 }
274 }
275
Brian Carlstrom7940e442013-07-12 13:46:57 -0700276 // A check-cast could be eliminated due to verifier type analysis.
277 void SafeCast() {
278 STATS_LOCK();
279 safe_casts_++;
280 }
281
282 // A check-cast couldn't be eliminated due to verifier type analysis.
283 void NotASafeCast() {
284 STATS_LOCK();
285 not_safe_casts_++;
286 }
287
288 private:
289 Mutex stats_lock_;
290
291 size_t types_in_dex_cache_;
292 size_t types_not_in_dex_cache_;
293
294 size_t strings_in_dex_cache_;
295 size_t strings_not_in_dex_cache_;
296
297 size_t resolved_types_;
298 size_t unresolved_types_;
299
300 size_t resolved_instance_fields_;
301 size_t unresolved_instance_fields_;
302
303 size_t resolved_local_static_fields_;
304 size_t resolved_static_fields_;
305 size_t unresolved_static_fields_;
306 // Type based devirtualization for invoke interface and virtual.
307 size_t type_based_devirtualization_;
308
309 size_t resolved_methods_[kMaxInvokeType + 1];
310 size_t unresolved_methods_[kMaxInvokeType + 1];
311 size_t virtual_made_direct_[kMaxInvokeType + 1];
312 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
313 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
314
315 size_t safe_casts_;
316 size_t not_safe_casts_;
317
318 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
319};
320
Brian Carlstrom7940e442013-07-12 13:46:57 -0700321
322extern "C" art::CompiledMethod* ArtCompileDEX(art::CompilerDriver& compiler,
323 const art::DexFile::CodeItem* code_item,
324 uint32_t access_flags,
325 art::InvokeType invoke_type,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700326 uint16_t class_def_idx,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700327 uint32_t method_idx,
328 jobject class_loader,
329 const art::DexFile& dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700330
Brian Carlstrom6449c622014-02-10 23:48:36 -0800331CompilerDriver::CompilerDriver(const CompilerOptions* compiler_options,
332 VerificationResults* verification_results,
Vladimir Marko5816ed42013-11-27 17:04:20 +0000333 DexFileToMethodInlinerMap* method_inliner_map,
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000334 Compiler::Kind compiler_kind,
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000335 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700336 InstructionSetFeatures instruction_set_features,
Andreas Gampe26318f72014-11-11 13:28:29 -0800337 bool image, std::set<std::string>* image_classes,
338 std::set<std::string>* compiled_classes, size_t thread_count,
Dave Allison39c3bfb2014-01-28 18:33:52 -0800339 bool dump_stats, bool dump_passes, CumulativeLogger* timer,
340 std::string profile_file)
Calin Juravlec1b643c2014-05-30 23:44:11 +0100341 : profile_present_(false), compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800342 verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000343 method_inliner_map_(method_inliner_map),
Ian Rogers72d32622014-05-06 16:20:11 -0700344 compiler_(Compiler::Create(this, compiler_kind)),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700345 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700346 instruction_set_features_(instruction_set_features),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700347 freezing_constructor_lock_("freezing constructor lock"),
348 compiled_classes_lock_("compiled classes lock"),
349 compiled_methods_lock_("compiled method lock"),
350 image_(image),
351 image_classes_(image_classes),
Andreas Gampe26318f72014-11-11 13:28:29 -0800352 classes_to_compile_(compiled_classes),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700353 thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700354 start_ns_(0),
355 stats_(new AOTCompilationStats),
356 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000357 dump_passes_(dump_passes),
358 timings_logger_(timer),
Andreas Gampe35439ba2014-08-28 14:41:02 -0700359 compiler_library_(nullptr),
360 compiler_context_(nullptr),
361 compiler_enable_auto_elf_loading_(nullptr),
362 compiler_get_method_code_addr_(nullptr),
Mark Mendell55d0eac2014-02-06 11:02:52 -0800363 support_boot_image_fixup_(instruction_set != kMips),
Mark Mendellae9fd932014-02-10 16:14:35 -0800364 cfi_info_(nullptr),
Ian Rogersd133b972013-09-05 11:01:30 -0700365 dedupe_code_("dedupe code"),
366 dedupe_mapping_table_("dedupe mapping table"),
367 dedupe_vmap_table_("dedupe vmap table"),
Mark Mendellae9fd932014-02-10 16:14:35 -0800368 dedupe_gc_map_("dedupe gc map"),
369 dedupe_cfi_info_("dedupe cfi info") {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800370 DCHECK(compiler_options_ != nullptr);
371 DCHECK(verification_results_ != nullptr);
372 DCHECK(method_inliner_map_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700373
Andreas Gampe35439ba2014-08-28 14:41:02 -0700374 CHECK_PTHREAD_CALL(pthread_key_create, (&tls_key_, nullptr), "compiler tls key");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700375
Sebastien Hertz75021222013-07-16 18:34:50 +0200376 dex_to_dex_compiler_ = reinterpret_cast<DexToDexCompilerFn>(ArtCompileDEX);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700377
Ian Rogers72d32622014-05-06 16:20:11 -0700378 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700379
380 CHECK(!Runtime::Current()->IsStarted());
Kenny Rootd5185342014-05-13 14:47:05 -0700381 if (image_) {
382 CHECK(image_classes_.get() != nullptr);
383 } else {
384 CHECK(image_classes_.get() == nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700385 }
Mark Mendellae9fd932014-02-10 16:14:35 -0800386
387 // Are we generating CFI information?
388 if (compiler_options->GetGenerateGDBInformation()) {
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000389 cfi_info_.reset(compiler_->GetCallFrameInformationInitialization(*this));
Mark Mendellae9fd932014-02-10 16:14:35 -0800390 }
Calin Juravlec1b643c2014-05-30 23:44:11 +0100391
392 // Read the profile file if one is provided.
393 if (!profile_file.empty()) {
394 profile_present_ = profile_file_.LoadFile(profile_file);
395 if (profile_present_) {
396 LOG(INFO) << "Using profile data form file " << profile_file;
397 } else {
398 LOG(INFO) << "Failed to load profile file " << profile_file;
399 }
400 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700401}
402
Mathieu Chartier193bad92013-08-29 18:46:00 -0700403std::vector<uint8_t>* CompilerDriver::DeduplicateCode(const std::vector<uint8_t>& code) {
404 return dedupe_code_.Add(Thread::Current(), code);
405}
406
407std::vector<uint8_t>* CompilerDriver::DeduplicateMappingTable(const std::vector<uint8_t>& code) {
408 return dedupe_mapping_table_.Add(Thread::Current(), code);
409}
410
411std::vector<uint8_t>* CompilerDriver::DeduplicateVMapTable(const std::vector<uint8_t>& code) {
412 return dedupe_vmap_table_.Add(Thread::Current(), code);
413}
414
415std::vector<uint8_t>* CompilerDriver::DeduplicateGCMap(const std::vector<uint8_t>& code) {
416 return dedupe_gc_map_.Add(Thread::Current(), code);
417}
418
Mark Mendellae9fd932014-02-10 16:14:35 -0800419std::vector<uint8_t>* CompilerDriver::DeduplicateCFIInfo(const std::vector<uint8_t>* cfi_info) {
420 if (cfi_info == nullptr) {
421 return nullptr;
422 }
423 return dedupe_cfi_info_.Add(Thread::Current(), *cfi_info);
424}
425
Brian Carlstrom7940e442013-07-12 13:46:57 -0700426CompilerDriver::~CompilerDriver() {
427 Thread* self = Thread::Current();
428 {
429 MutexLock mu(self, compiled_classes_lock_);
430 STLDeleteValues(&compiled_classes_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700431 STLDeleteValues(&compiled_methods_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700432 STLDeleteElements(&code_to_patch_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700433 STLDeleteElements(&methods_to_patch_);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800434 STLDeleteElements(&classes_to_patch_);
Mathieu Chartier80714002014-11-20 15:04:10 -0800435 STLDeleteElements(&strings_to_patch_);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800436 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700437 CHECK_PTHREAD_CALL(pthread_key_delete, (tls_key_), "delete tls key");
Ian Rogers72d32622014-05-06 16:20:11 -0700438 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700439}
440
441CompilerTls* CompilerDriver::GetTls() {
442 // Lazily create thread-local storage
443 CompilerTls* res = static_cast<CompilerTls*>(pthread_getspecific(tls_key_));
Andreas Gampe35439ba2014-08-28 14:41:02 -0700444 if (res == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700445 res = new CompilerTls();
446 CHECK_PTHREAD_CALL(pthread_setspecific, (tls_key_, res), "compiler tls");
447 }
448 return res;
449}
450
Ian Rogersdd7624d2014-03-14 17:43:00 -0700451#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700452 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700453 return CreateTrampoline64(instruction_set_, abi, \
454 type ## _ENTRYPOINT_OFFSET(8, offset)); \
455 } else { \
456 return CreateTrampoline32(instruction_set_, abi, \
457 type ## _ENTRYPOINT_OFFSET(4, offset)); \
458 }
459
Ian Rogers848871b2013-08-05 10:56:33 -0700460const std::vector<uint8_t>* CompilerDriver::CreateInterpreterToInterpreterBridge() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700461 CREATE_TRAMPOLINE(INTERPRETER, kInterpreterAbi, pInterpreterToInterpreterBridge)
Ian Rogers848871b2013-08-05 10:56:33 -0700462}
463
464const std::vector<uint8_t>* CompilerDriver::CreateInterpreterToCompiledCodeBridge() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700465 CREATE_TRAMPOLINE(INTERPRETER, kInterpreterAbi, pInterpreterToCompiledCodeBridge)
Ian Rogers848871b2013-08-05 10:56:33 -0700466}
467
468const std::vector<uint8_t>* CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700469 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700470}
471
Jeff Hao88474b42013-10-23 16:24:40 -0700472const std::vector<uint8_t>* CompilerDriver::CreatePortableImtConflictTrampoline() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700473 CREATE_TRAMPOLINE(PORTABLE, kPortableAbi, pPortableImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700474}
475
Brian Carlstrom7940e442013-07-12 13:46:57 -0700476const std::vector<uint8_t>* CompilerDriver::CreatePortableResolutionTrampoline() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700477 CREATE_TRAMPOLINE(PORTABLE, kPortableAbi, pPortableResolutionTrampoline)
Ian Rogers848871b2013-08-05 10:56:33 -0700478}
479
480const std::vector<uint8_t>* CompilerDriver::CreatePortableToInterpreterBridge() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700481 CREATE_TRAMPOLINE(PORTABLE, kPortableAbi, pPortableToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700482}
483
Andreas Gampe2da88232014-02-27 12:26:20 -0800484const std::vector<uint8_t>* CompilerDriver::CreateQuickGenericJniTrampoline() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700485 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800486}
487
Jeff Hao88474b42013-10-23 16:24:40 -0700488const std::vector<uint8_t>* CompilerDriver::CreateQuickImtConflictTrampoline() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700489 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700490}
491
Brian Carlstrom7940e442013-07-12 13:46:57 -0700492const std::vector<uint8_t>* CompilerDriver::CreateQuickResolutionTrampoline() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700493 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700494}
495
Ian Rogers848871b2013-08-05 10:56:33 -0700496const std::vector<uint8_t>* CompilerDriver::CreateQuickToInterpreterBridge() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700497 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700498}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700499#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700500
501void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700502 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800503 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700504 DCHECK(!Runtime::Current()->IsStarted());
Ian Rogers700a4022014-05-19 16:49:03 -0700505 std::unique_ptr<ThreadPool> thread_pool(new ThreadPool("Compiler driver thread pool", thread_count_ - 1));
Mathieu Chartier25fda922014-12-03 17:38:22 -0800506 VLOG(compiler) << "Before precompile " << GetMemoryUsageString();
Ian Rogers3d504072014-03-01 09:16:49 -0800507 PreCompile(class_loader, dex_files, thread_pool.get(), timings);
508 Compile(class_loader, dex_files, thread_pool.get(), timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700509 if (dump_stats_) {
510 stats_->Dump();
511 }
512}
513
Mathieu Chartier590fee92013-09-13 13:46:47 -0700514static DexToDexCompilationLevel GetDexToDexCompilationlevel(
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700515 Thread* self, Handle<mirror::ClassLoader> class_loader, const DexFile& dex_file,
Mathieu Chartier590fee92013-09-13 13:46:47 -0700516 const DexFile::ClassDef& class_def) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700517 const char* descriptor = dex_file.GetClassDescriptor(class_def);
518 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800519 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe35439ba2014-08-28 14:41:02 -0700520 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700521 CHECK(self->IsExceptionPending());
522 self->ClearException();
Sebastien Hertz75021222013-07-16 18:34:50 +0200523 return kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700524 }
Andreas Gampe35439ba2014-08-28 14:41:02 -0700525 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
526 // references with actual offsets. We cannot re-verify such instructions.
527 //
528 // We store the verification information in the class status in the oat file, which the linker
529 // can validate (checksums) and use to skip load-time verification. It is thus safe to
530 // optimize when a class has been fully verified before.
531 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200532 // Class is verified so we can enable DEX-to-DEX compilation for performance.
533 return kOptimize;
534 } else if (klass->IsCompileTimeVerified()) {
535 // Class verification has soft-failed. Anyway, ensure at least correctness.
536 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
537 return kRequired;
538 } else {
539 // Class verification has failed: do not run DEX-to-DEX compilation.
540 return kDontDexToDexCompile;
541 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700542}
543
Ian Rogers3d504072014-03-01 09:16:49 -0800544void CompilerDriver::CompileOne(mirror::ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700545 DCHECK(!Runtime::Current()->IsStarted());
546 Thread* self = Thread::Current();
547 jobject jclass_loader;
548 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700549 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800550 uint32_t method_idx = method->GetDexMethodIndex();
551 uint32_t access_flags = method->GetAccessFlags();
552 InvokeType invoke_type = method->GetInvokeType();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700553 {
554 ScopedObjectAccessUnchecked soa(self);
555 ScopedLocalRef<jobject>
556 local_class_loader(soa.Env(),
557 soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
558 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
559 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700560 dex_file = method->GetDexFile();
561 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700562 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800563 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700564 self->TransitionFromRunnableToSuspended(kNative);
565
566 std::vector<const DexFile*> dex_files;
567 dex_files.push_back(dex_file);
568
Ian Rogers700a4022014-05-19 16:49:03 -0700569 std::unique_ptr<ThreadPool> thread_pool(new ThreadPool("Compiler driver thread pool", 0U));
Ian Rogers3d504072014-03-01 09:16:49 -0800570 PreCompile(jclass_loader, dex_files, thread_pool.get(), timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700571
Brian Carlstrom7940e442013-07-12 13:46:57 -0700572 // Can we run DEX-to-DEX compiler on this class ?
Sebastien Hertz75021222013-07-16 18:34:50 +0200573 DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700574 {
575 ScopedObjectAccess soa(Thread::Current());
576 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700577 StackHandleScope<1> hs(soa.Self());
578 Handle<mirror::ClassLoader> class_loader(
579 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
Ian Rogers98379392014-02-24 16:53:16 -0800580 dex_to_dex_compilation_level = GetDexToDexCompilationlevel(self, class_loader, *dex_file,
581 class_def);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700582 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800583 CompileMethod(code_item, access_flags, invoke_type, class_def_idx, method_idx, jclass_loader,
Andreas Gampe26318f72014-11-11 13:28:29 -0800584 *dex_file, dex_to_dex_compilation_level, true);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700585
586 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
587
588 self->TransitionFromSuspendedToRunnable();
589}
590
591void CompilerDriver::Resolve(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800592 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700593 for (size_t i = 0; i != dex_files.size(); ++i) {
594 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700595 CHECK(dex_file != nullptr);
Andreas Gampe01719872014-07-28 18:38:57 -0700596 ResolveDexFile(class_loader, *dex_file, dex_files, thread_pool, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700597 }
598}
599
600void CompilerDriver::PreCompile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800601 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700602 LoadImageClasses(timings);
Mathieu Chartier25fda922014-12-03 17:38:22 -0800603 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700604
Andreas Gampe35439ba2014-08-28 14:41:02 -0700605 Resolve(class_loader, dex_files, thread_pool, timings);
Mathieu Chartier25fda922014-12-03 17:38:22 -0800606 VLOG(compiler) << "Resolve: " << GetMemoryUsageString();
Andreas Gampe35439ba2014-08-28 14:41:02 -0700607
Jeff Hao4a200f52014-04-01 14:58:49 -0700608 if (!compiler_options_->IsVerificationEnabled()) {
Mathieu Chartier25fda922014-12-03 17:38:22 -0800609 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampe35439ba2014-08-28 14:41:02 -0700610 SetVerified(class_loader, dex_files, thread_pool, timings);
Jeff Hao4a200f52014-04-01 14:58:49 -0700611 return;
612 }
613
Brian Carlstrom7940e442013-07-12 13:46:57 -0700614 Verify(class_loader, dex_files, thread_pool, timings);
Mathieu Chartier25fda922014-12-03 17:38:22 -0800615 VLOG(compiler) << "Verify: " << GetMemoryUsageString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700616
617 InitializeClasses(class_loader, dex_files, thread_pool, timings);
Mathieu Chartier25fda922014-12-03 17:38:22 -0800618 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700619
620 UpdateImageClasses(timings);
Mathieu Chartier25fda922014-12-03 17:38:22 -0800621 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700622}
623
Ian Rogersdfb325e2013-10-30 01:00:44 -0700624bool CompilerDriver::IsImageClass(const char* descriptor) const {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700625 if (!IsImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700626 return true;
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700627 } else {
Ian Rogersdfb325e2013-10-30 01:00:44 -0700628 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700629 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700630}
631
Andreas Gampe26318f72014-11-11 13:28:29 -0800632bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
633 if (!IsImage()) {
634 return true;
635 } else {
636 if (classes_to_compile_ == nullptr) {
637 return true;
638 }
639 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
640 }
641}
642
Brian Carlstrom7940e442013-07-12 13:46:57 -0700643static void ResolveExceptionsForMethod(MethodHelper* mh,
Ian Rogers700a4022014-05-19 16:49:03 -0700644 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700645 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700646 const DexFile::CodeItem* code_item = mh->GetMethod()->GetCodeItem();
Andreas Gampe35439ba2014-08-28 14:41:02 -0700647 if (code_item == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700648 return; // native or abstract method
649 }
650 if (code_item->tries_size_ == 0) {
651 return; // nothing to process
652 }
653 const byte* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
654 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
655 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
656 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
657 bool has_catch_all = false;
658 if (encoded_catch_handler_size <= 0) {
659 encoded_catch_handler_size = -encoded_catch_handler_size;
660 has_catch_all = true;
661 }
662 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
663 uint16_t encoded_catch_handler_handlers_type_idx =
664 DecodeUnsignedLeb128(&encoded_catch_handler_list);
665 // Add to set of types to resolve if not already in the dex cache resolved types
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700666 if (!mh->GetMethod()->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700667 exceptions_to_resolve.insert(
668 std::pair<uint16_t, const DexFile*>(encoded_catch_handler_handlers_type_idx,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700669 mh->GetMethod()->GetDexFile()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700670 }
671 // ignore address associated with catch handler
672 DecodeUnsignedLeb128(&encoded_catch_handler_list);
673 }
674 if (has_catch_all) {
675 // ignore catch all address
676 DecodeUnsignedLeb128(&encoded_catch_handler_list);
677 }
678 }
679}
680
681static bool ResolveCatchBlockExceptionsClassVisitor(mirror::Class* c, void* arg)
682 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers700a4022014-05-19 16:49:03 -0700683 std::set<std::pair<uint16_t, const DexFile*>>* exceptions_to_resolve =
684 reinterpret_cast<std::set<std::pair<uint16_t, const DexFile*>>*>(arg);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700685 StackHandleScope<1> hs(Thread::Current());
686 MethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700687 for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700688 mh.ChangeMethod(c->GetVirtualMethod(i));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700689 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
690 }
691 for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700692 mh.ChangeMethod(c->GetDirectMethod(i));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700693 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
694 }
695 return true;
696}
697
698static bool RecordImageClassesVisitor(mirror::Class* klass, void* arg)
699 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700700 std::set<std::string>* image_classes = reinterpret_cast<std::set<std::string>*>(arg);
701 std::string temp;
702 image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700703 return true;
704}
705
706// Make a list of descriptors for classes to include in the image
Ian Rogers3d504072014-03-01 09:16:49 -0800707void CompilerDriver::LoadImageClasses(TimingLogger* timings)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700708 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Kenny Rootd5185342014-05-13 14:47:05 -0700709 CHECK(timings != nullptr);
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700710 if (!IsImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700711 return;
712 }
713
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700714 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700715 // Make a first class to load all classes explicitly listed in the file
716 Thread* self = Thread::Current();
717 ScopedObjectAccess soa(self);
718 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -0700719 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700720 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000721 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700722 StackHandleScope<1> hs(self);
723 Handle<mirror::Class> klass(
724 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampe35439ba2014-08-28 14:41:02 -0700725 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700726 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000727 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -0700728 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700729 } else {
730 ++it;
731 }
732 }
733
734 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
735 // exceptions are resolved by the verifier when there is a catch block in an interested method.
736 // Do this here so that exception classes appear to have been specified image classes.
Ian Rogers700a4022014-05-19 16:49:03 -0700737 std::set<std::pair<uint16_t, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700738 StackHandleScope<1> hs(self);
739 Handle<mirror::Class> java_lang_Throwable(
740 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700741 do {
742 unresolved_exception_types.clear();
743 class_linker->VisitClasses(ResolveCatchBlockExceptionsClassVisitor,
744 &unresolved_exception_types);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700745 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
746 uint16_t exception_type_idx = exception_type.first;
747 const DexFile* dex_file = exception_type.second;
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700748 StackHandleScope<2> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700749 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(*dex_file)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700750 Handle<mirror::Class> klass(hs.NewHandle(
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700751 class_linker->ResolveType(*dex_file, exception_type_idx, dex_cache,
752 NullHandle<mirror::ClassLoader>())));
Andreas Gampe35439ba2014-08-28 14:41:02 -0700753 if (klass.Get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700754 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
755 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
756 LOG(FATAL) << "Failed to resolve class " << descriptor;
757 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700758 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700759 }
760 // Resolving exceptions may load classes that reference more exceptions, iterate until no
761 // more are found
762 } while (!unresolved_exception_types.empty());
763
764 // We walk the roots looking for classes so that we'll pick up the
765 // above classes plus any classes them depend on such super
766 // classes, interfaces, and the required ClassLinker roots.
767 class_linker->VisitClasses(RecordImageClassesVisitor, image_classes_.get());
768
769 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700770}
771
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700772static void MaybeAddToImageClasses(Handle<mirror::Class> c, std::set<std::string>* image_classes)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700773 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700774 Thread* self = Thread::Current();
775 StackHandleScope<1> hs(self);
776 // Make a copy of the handle so that we don't clobber it doing Assign.
777 Handle<mirror::Class> klass(hs.NewHandle(c.Get()));
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700778 std::string temp;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700779 while (!klass->IsObjectClass()) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700780 const char* descriptor = klass->GetDescriptor(&temp);
781 std::pair<std::set<std::string>::iterator, bool> result = image_classes->insert(descriptor);
782 if (!result.second) { // Previously inserted.
783 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700784 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700785 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Mathieu Chartierf8322842014-05-16 10:59:25 -0700786 for (size_t i = 0; i < klass->NumDirectInterfaces(); ++i) {
787 StackHandleScope<1> hs(self);
788 MaybeAddToImageClasses(hs.NewHandle(mirror::Class::GetDirectInterface(self, klass, i)),
789 image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700790 }
791 if (klass->IsArrayClass()) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700792 StackHandleScope<1> hs(self);
793 MaybeAddToImageClasses(hs.NewHandle(klass->GetComponentType()), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700794 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700795 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700796 }
797}
798
799void CompilerDriver::FindClinitImageClassesCallback(mirror::Object* object, void* arg) {
Andreas Gampe35439ba2014-08-28 14:41:02 -0700800 DCHECK(object != nullptr);
801 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700802 CompilerDriver* compiler_driver = reinterpret_cast<CompilerDriver*>(arg);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700803 StackHandleScope<1> hs(Thread::Current());
804 MaybeAddToImageClasses(hs.NewHandle(object->GetClass()), compiler_driver->image_classes_.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700805}
806
Ian Rogers3d504072014-03-01 09:16:49 -0800807void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700808 if (IsImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700809 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700810 // Update image_classes_ with classes for objects created by <clinit> methods.
811 Thread* self = Thread::Current();
812 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
813 gc::Heap* heap = Runtime::Current()->GetHeap();
814 // TODO: Image spaces only?
Mathieu Chartier590fee92013-09-13 13:46:47 -0700815 ScopedObjectAccess soa(Thread::Current());
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700816 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700817 heap->VisitObjects(FindClinitImageClassesCallback, this);
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700818 self->EndAssertNoThreadSuspension(old_cause);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700819 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700820}
821
Mathieu Chartier590fee92013-09-13 13:46:47 -0700822bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(const DexFile& dex_file, uint32_t type_idx) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700823 if (IsImage() &&
Ian Rogersdfb325e2013-10-30 01:00:44 -0700824 IsImageClass(dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_))) {
Andreas Gampe4ef12f52014-07-31 16:23:49 -0700825 {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700826 ScopedObjectAccess soa(Thread::Current());
827 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
828 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe4ef12f52014-07-31 16:23:49 -0700829 if (resolved_class == nullptr) {
830 // Erroneous class.
831 stats_->TypeNotInDexCache();
832 return false;
833 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700834 }
835 stats_->TypeInDexCache();
836 return true;
837 } else {
838 stats_->TypeNotInDexCache();
839 return false;
840 }
841}
842
843bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
844 uint32_t string_idx) {
845 // See also Compiler::ResolveDexFile
846
847 bool result = false;
848 if (IsImage()) {
849 // We resolve all const-string strings when building for the image.
850 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700851 StackHandleScope<1> hs(soa.Self());
852 Handle<mirror::DexCache> dex_cache(
853 hs.NewHandle(Runtime::Current()->GetClassLinker()->FindDexCache(dex_file)));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700854 Runtime::Current()->GetClassLinker()->ResolveString(dex_file, string_idx, dex_cache);
855 result = true;
856 }
857 if (result) {
858 stats_->StringInDexCache();
859 } else {
860 stats_->StringNotInDexCache();
861 }
862 return result;
863}
864
865bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
866 uint32_t type_idx,
867 bool* type_known_final, bool* type_known_abstract,
868 bool* equals_referrers_class) {
Andreas Gampe35439ba2014-08-28 14:41:02 -0700869 if (type_known_final != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700870 *type_known_final = false;
871 }
Andreas Gampe35439ba2014-08-28 14:41:02 -0700872 if (type_known_abstract != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700873 *type_known_abstract = false;
874 }
Andreas Gampe35439ba2014-08-28 14:41:02 -0700875 if (equals_referrers_class != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700876 *equals_referrers_class = false;
877 }
878 ScopedObjectAccess soa(Thread::Current());
879 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
880 // Get type from dex cache assuming it was populated by the verifier
881 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe35439ba2014-08-28 14:41:02 -0700882 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700883 stats_->TypeNeedsAccessCheck();
884 return false; // Unknown class needs access checks.
885 }
886 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
Andreas Gampe35439ba2014-08-28 14:41:02 -0700887 if (equals_referrers_class != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700888 *equals_referrers_class = (method_id.class_idx_ == type_idx);
889 }
890 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
Andreas Gampe35439ba2014-08-28 14:41:02 -0700891 if (referrer_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700892 stats_->TypeNeedsAccessCheck();
893 return false; // Incomplete referrer knowledge needs access check.
894 }
895 // Perform access check, will return true if access is ok or false if we're going to have to
896 // check this at runtime (for example for class loaders).
897 bool result = referrer_class->CanAccess(resolved_class);
898 if (result) {
899 stats_->TypeDoesntNeedAccessCheck();
Andreas Gampe35439ba2014-08-28 14:41:02 -0700900 if (type_known_final != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700901 *type_known_final = resolved_class->IsFinal() && !resolved_class->IsArrayClass();
902 }
Andreas Gampe35439ba2014-08-28 14:41:02 -0700903 if (type_known_abstract != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700904 *type_known_abstract = resolved_class->IsAbstract() && !resolved_class->IsArrayClass();
905 }
906 } else {
907 stats_->TypeNeedsAccessCheck();
908 }
909 return result;
910}
911
912bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
913 const DexFile& dex_file,
914 uint32_t type_idx) {
915 ScopedObjectAccess soa(Thread::Current());
916 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
917 // Get type from dex cache assuming it was populated by the verifier.
918 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe35439ba2014-08-28 14:41:02 -0700919 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700920 stats_->TypeNeedsAccessCheck();
921 return false; // Unknown class needs access checks.
922 }
923 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
924 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
Andreas Gampe35439ba2014-08-28 14:41:02 -0700925 if (referrer_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700926 stats_->TypeNeedsAccessCheck();
927 return false; // Incomplete referrer knowledge needs access check.
928 }
929 // Perform access and instantiable checks, will return true if access is ok or false if we're
930 // going to have to check this at runtime (for example for class loaders).
931 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
932 if (result) {
933 stats_->TypeDoesntNeedAccessCheck();
934 } else {
935 stats_->TypeNeedsAccessCheck();
936 }
937 return result;
938}
939
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800940bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
941 bool* is_type_initialized, bool* use_direct_type_ptr,
Mathieu Chartier8668c3c2014-04-24 16:48:11 -0700942 uintptr_t* direct_type_ptr, bool* out_is_finalizable) {
Mathieu Chartier80714002014-11-20 15:04:10 -0800943 if (GetCompilerOptions().GetCompilePic()) {
944 // Do not allow a direct class pointer to be used when compiling for position-independent
945 return false;
946 }
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800947 ScopedObjectAccess soa(Thread::Current());
948 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
949 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
950 if (resolved_class == nullptr) {
951 return false;
952 }
Mathieu Chartier8668c3c2014-04-24 16:48:11 -0700953 *out_is_finalizable = resolved_class->IsFinalizable();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800954 const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
Alex Light345c4b12014-07-18 14:57:04 -0700955 const bool support_boot_image_fixup = GetSupportBootImageFixup();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800956 if (compiling_boot) {
957 // boot -> boot class pointers.
958 // True if the class is in the image at boot compiling time.
959 const bool is_image_class = IsImage() && IsImageClass(
960 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
961 // True if pc relative load works.
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800962 if (is_image_class && support_boot_image_fixup) {
963 *is_type_initialized = resolved_class->IsInitialized();
964 *use_direct_type_ptr = false;
965 *direct_type_ptr = 0;
966 return true;
967 } else {
968 return false;
969 }
970 } else {
971 // True if the class is in the image at app compiling time.
972 const bool class_in_image =
973 Runtime::Current()->GetHeap()->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
Alex Light345c4b12014-07-18 14:57:04 -0700974 if (class_in_image && support_boot_image_fixup) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800975 // boot -> app class pointers.
976 *is_type_initialized = resolved_class->IsInitialized();
Alex Lighta59dd802014-07-02 16:28:08 -0700977 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
978 *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800979 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
980 return true;
981 } else {
982 // app -> app class pointers.
983 // Give up because app does not have an image and class
984 // isn't created at compile time. TODO: implement this
985 // if/when each app gets an image.
986 return false;
987 }
988 }
989}
990
Mathieu Chartier80714002014-11-20 15:04:10 -0800991bool CompilerDriver::CanEmbedStringInCode(const DexFile& dex_file, uint32_t string_idx,
992 bool* use_direct_type_ptr, uintptr_t* direct_type_ptr) {
993 if (GetCompilerOptions().GetCompilePic()) {
994 // Do not allow a direct class pointer to be used when compiling for position-independent
995 return false;
996 }
997 ScopedObjectAccess soa(Thread::Current());
998 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
999 mirror::String* resolved_string = dex_cache->GetResolvedString(string_idx);
1000 if (resolved_string == nullptr) {
1001 return false;
1002 }
1003 const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
1004 const bool support_boot_image_fixup = GetSupportBootImageFixup();
1005 if (compiling_boot) {
1006 // boot -> boot class pointers.
1007 // True if the class is in the image at boot compiling time.
1008 const bool is_image_string = IsImage();
1009 // True if pc relative load works.
1010 if (is_image_string && support_boot_image_fixup) {
1011 *use_direct_type_ptr = false;
1012 *direct_type_ptr = 0;
1013 return true;
1014 }
1015 return false;
1016 } else {
1017 // True if the class is in the image at app compiling time.
1018 const bool obj_in_image =
1019 false && Runtime::Current()->GetHeap()->FindSpaceFromObject(resolved_string, false)->IsImageSpace();
1020 if (obj_in_image && support_boot_image_fixup) {
1021 // boot -> app class pointers.
1022 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1023 *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
1024 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_string);
1025 return true;
1026 }
1027
1028 // app -> app class pointers.
1029 // Give up because app does not have an image and class
1030 // isn't created at compile time. TODO: implement this
1031 // if/when each app gets an image.
1032 return false;
1033 }
1034}
1035
Vladimir Markobe0e5462014-02-26 11:24:15 +00001036void CompilerDriver::ProcessedInstanceField(bool resolved) {
1037 if (!resolved) {
1038 stats_->UnresolvedInstanceField();
1039 } else {
1040 stats_->ResolvedInstanceField();
1041 }
1042}
1043
1044void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1045 if (!resolved) {
1046 stats_->UnresolvedStaticField();
1047 } else if (local) {
1048 stats_->ResolvedLocalStaticField();
1049 } else {
1050 stats_->ResolvedStaticField();
1051 }
1052}
1053
Vladimir Markof096aad2014-01-23 15:51:58 +00001054void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
1055 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001056}
1057
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001058mirror::ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1059 const DexCompilationUnit* mUnit,
1060 bool is_put,
1061 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001062 // Try to resolve the field and compiling method's class.
1063 mirror::ArtField* resolved_field;
1064 mirror::Class* referrer_class;
1065 mirror::DexCache* dex_cache;
1066 {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001067 StackHandleScope<3> hs(soa.Self());
1068 Handle<mirror::DexCache> dex_cache_handle(
1069 hs.NewHandle(mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile())));
1070 Handle<mirror::ClassLoader> class_loader_handle(
1071 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
1072 Handle<mirror::ArtField> resolved_field_handle(hs.NewHandle(
1073 ResolveField(soa, dex_cache_handle, class_loader_handle, mUnit, field_idx, false)));
1074 referrer_class = (resolved_field_handle.Get() != nullptr)
1075 ? ResolveCompilingMethodsClass(soa, dex_cache_handle, class_loader_handle, mUnit) : nullptr;
1076 resolved_field = resolved_field_handle.Get();
1077 dex_cache = dex_cache_handle.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001078 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001079 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001080 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001081 std::pair<bool, bool> fast_path = IsFastInstanceField(
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001082 dex_cache, referrer_class, resolved_field, field_idx);
1083 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001084 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001085 ProcessedInstanceField(can_link);
1086 return can_link ? resolved_field : nullptr;
1087}
1088
1089bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1090 bool is_put, MemberOffset* field_offset,
1091 bool* is_volatile) {
1092 ScopedObjectAccess soa(Thread::Current());
1093 StackHandleScope<1> hs(soa.Self());
1094 Handle<mirror::ArtField> resolved_field =
1095 hs.NewHandle(ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa));
1096
1097 if (resolved_field.Get() == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001098 // Conservative defaults.
1099 *is_volatile = true;
1100 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001101 return false;
1102 } else {
1103 *is_volatile = resolved_field->IsVolatile();
1104 *field_offset = resolved_field->GetOffset();
1105 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001106 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001107}
1108
1109bool CompilerDriver::ComputeStaticFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
Vladimir Markobe0e5462014-02-26 11:24:15 +00001110 bool is_put, MemberOffset* field_offset,
1111 uint32_t* storage_index, bool* is_referrers_class,
1112 bool* is_volatile, bool* is_initialized) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001113 ScopedObjectAccess soa(Thread::Current());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001114 // Try to resolve the field and compiling method's class.
1115 mirror::ArtField* resolved_field;
1116 mirror::Class* referrer_class;
1117 mirror::DexCache* dex_cache;
1118 {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001119 StackHandleScope<3> hs(soa.Self());
1120 Handle<mirror::DexCache> dex_cache_handle(
1121 hs.NewHandle(mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile())));
1122 Handle<mirror::ClassLoader> class_loader_handle(
1123 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
1124 Handle<mirror::ArtField> resolved_field_handle(hs.NewHandle(
1125 ResolveField(soa, dex_cache_handle, class_loader_handle, mUnit, field_idx, true)));
1126 referrer_class = (resolved_field_handle.Get() != nullptr)
1127 ? ResolveCompilingMethodsClass(soa, dex_cache_handle, class_loader_handle, mUnit) : nullptr;
1128 resolved_field = resolved_field_handle.Get();
1129 dex_cache = dex_cache_handle.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001130 }
Vladimir Markobe0e5462014-02-26 11:24:15 +00001131 bool result = false;
1132 if (resolved_field != nullptr && referrer_class != nullptr) {
1133 *is_volatile = IsFieldVolatile(resolved_field);
1134 std::pair<bool, bool> fast_path = IsFastStaticField(
1135 dex_cache, referrer_class, resolved_field, field_idx, field_offset,
1136 storage_index, is_referrers_class, is_initialized);
1137 result = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001138 }
Vladimir Markobe0e5462014-02-26 11:24:15 +00001139 if (!result) {
1140 // Conservative defaults.
1141 *is_volatile = true;
1142 *field_offset = MemberOffset(static_cast<size_t>(-1));
1143 *storage_index = -1;
1144 *is_referrers_class = false;
1145 *is_initialized = false;
1146 }
1147 ProcessedStaticField(result, *is_referrers_class);
1148 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001149}
1150
Ian Rogers83883d72013-10-21 21:07:24 -07001151void CompilerDriver::GetCodeAndMethodForDirectCall(InvokeType* type, InvokeType sharp_type,
1152 bool no_guarantee_of_dex_cache_entry,
Igor Murashkin643b5df2014-10-16 18:36:16 -07001153 const mirror::Class* referrer_class,
Brian Carlstromea46f952013-07-30 01:26:50 -07001154 mirror::ArtMethod* method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001155 int* stats_flags,
Ian Rogers83883d72013-10-21 21:07:24 -07001156 MethodReference* target_method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001157 uintptr_t* direct_code,
1158 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001159 // For direct and static methods compute possible direct_code and direct_method values, ie
1160 // an address for the Method* being invoked and an address of the code for that Method*.
1161 // For interface calls compute a value for direct_method that is the interface method being
1162 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001163 *direct_code = 0;
1164 *direct_method = 0;
Igor Murashkin643b5df2014-10-16 18:36:16 -07001165 bool use_dex_cache = GetCompilerOptions().GetCompilePic(); // Off by default
Mathieu Chartier590fee92013-09-13 13:46:47 -07001166 const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
Alex Lighta59dd802014-07-02 16:28:08 -07001167 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1168 const bool force_relocations = (compiling_boot ||
1169 GetCompilerOptions().GetIncludePatchInformation());
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001170 if (compiler_->IsPortable()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001171 if (sharp_type != kStatic && sharp_type != kDirect) {
1172 return;
1173 }
Ian Rogers83883d72013-10-21 21:07:24 -07001174 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001175 } else {
Jeff Hao88474b42013-10-23 16:24:40 -07001176 if (sharp_type != kStatic && sharp_type != kDirect) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001177 return;
1178 }
Ian Rogers83883d72013-10-21 21:07:24 -07001179 // TODO: support patching on all architectures.
Igor Murashkin643b5df2014-10-16 18:36:16 -07001180 use_dex_cache = use_dex_cache || (force_relocations && !support_boot_image_fixup_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001181 }
Ian Rogers83883d72013-10-21 21:07:24 -07001182 bool method_code_in_boot = (method->GetDeclaringClass()->GetClassLoader() == nullptr);
1183 if (!use_dex_cache) {
1184 if (!method_code_in_boot) {
1185 use_dex_cache = true;
1186 } else {
1187 bool has_clinit_trampoline =
1188 method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
1189 if (has_clinit_trampoline && (method->GetDeclaringClass() != referrer_class)) {
1190 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1191 // class.
1192 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001193 }
1194 }
Ian Rogers83883d72013-10-21 21:07:24 -07001195 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001196 if (method_code_in_boot) {
1197 *stats_flags |= kFlagDirectCallToBoot | kFlagDirectMethodToBoot;
Ian Rogers83883d72013-10-21 21:07:24 -07001198 }
Alex Lighta59dd802014-07-02 16:28:08 -07001199 if (!use_dex_cache && force_relocations) {
1200 if (!IsImage() || !IsImageClass(method->GetDeclaringClassDescriptor())) {
Ian Rogers83883d72013-10-21 21:07:24 -07001201 // We can only branch directly to Methods that are resolved in the DexCache.
1202 // Otherwise we won't invoke the resolution trampoline.
1203 use_dex_cache = true;
1204 }
1205 }
1206 // The method is defined not within this dex file. We need a dex cache slot within the current
1207 // dex file or direct pointers.
1208 bool must_use_direct_pointers = false;
1209 if (target_method->dex_file == method->GetDeclaringClass()->GetDexCache()->GetDexFile()) {
1210 target_method->dex_method_index = method->GetDexMethodIndex();
1211 } else {
Ian Rogers83883d72013-10-21 21:07:24 -07001212 if (no_guarantee_of_dex_cache_entry) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001213 StackHandleScope<1> hs(Thread::Current());
1214 MethodHelper mh(hs.NewHandle(method));
Ian Rogers83883d72013-10-21 21:07:24 -07001215 // See if the method is also declared in this dex cache.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001216 uint32_t dex_method_idx = mh.FindDexMethodIndexInOtherDexFile(
Vladimir Markobbcc0c02014-02-03 14:08:42 +00001217 *target_method->dex_file, target_method->dex_method_index);
Ian Rogers83883d72013-10-21 21:07:24 -07001218 if (dex_method_idx != DexFile::kDexNoIndex) {
1219 target_method->dex_method_index = dex_method_idx;
1220 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001221 if (force_relocations && !use_dex_cache) {
Jeff Hao49161ce2014-03-12 11:05:25 -07001222 target_method->dex_method_index = method->GetDexMethodIndex();
1223 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1224 }
Ian Rogers83883d72013-10-21 21:07:24 -07001225 must_use_direct_pointers = true;
1226 }
1227 }
1228 }
1229 if (use_dex_cache) {
1230 if (must_use_direct_pointers) {
1231 // Fail. Test above showed the only safe dispatch was via the dex cache, however, the direct
1232 // pointers are required as the dex cache lacks an appropriate entry.
1233 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1234 } else {
1235 *type = sharp_type;
1236 }
1237 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001238 bool method_in_image =
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001239 Runtime::Current()->GetHeap()->FindSpaceFromObject(method, false)->IsImageSpace();
Alex Lighta59dd802014-07-02 16:28:08 -07001240 if (method_in_image || compiling_boot) {
1241 // We know we must be able to get to the method in the image, so use that pointer.
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001242 CHECK(!method->IsAbstract());
Ian Rogers83883d72013-10-21 21:07:24 -07001243 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001244 *direct_method = force_relocations ? -1 : reinterpret_cast<uintptr_t>(method);
1245 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001246 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1247 target_method->dex_method_index = method->GetDexMethodIndex();
1248 } else if (!must_use_direct_pointers) {
1249 // Set the code and rely on the dex cache for the method.
1250 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001251 if (force_relocations) {
1252 *direct_code = -1;
1253 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1254 target_method->dex_method_index = method->GetDexMethodIndex();
1255 } else {
1256 *direct_code = compiler_->GetEntryPointOf(method);
1257 }
Ian Rogers83883d72013-10-21 21:07:24 -07001258 } else {
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001259 // Direct pointers were required but none were available.
1260 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001261 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001262 }
1263}
1264
1265bool CompilerDriver::ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001266 bool update_stats, bool enable_devirtualization,
1267 InvokeType* invoke_type, MethodReference* target_method,
1268 int* vtable_idx, uintptr_t* direct_code,
1269 uintptr_t* direct_method) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001270 InvokeType orig_invoke_type = *invoke_type;
1271 int stats_flags = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001272 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof096aad2014-01-23 15:51:58 +00001273 // Try to resolve the method and compiling method's class.
1274 mirror::ArtMethod* resolved_method;
1275 mirror::Class* referrer_class;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001276 StackHandleScope<3> hs(soa.Self());
1277 Handle<mirror::DexCache> dex_cache(
1278 hs.NewHandle(mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile())));
1279 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1280 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Vladimir Markof096aad2014-01-23 15:51:58 +00001281 {
1282 uint32_t method_idx = target_method->dex_method_index;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001283 Handle<mirror::ArtMethod> resolved_method_handle(hs.NewHandle(
1284 ResolveMethod(soa, dex_cache, class_loader, mUnit, method_idx, orig_invoke_type)));
1285 referrer_class = (resolved_method_handle.Get() != nullptr)
Vladimir Markof096aad2014-01-23 15:51:58 +00001286 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001287 resolved_method = resolved_method_handle.Get();
Vladimir Markof096aad2014-01-23 15:51:58 +00001288 }
1289 bool result = false;
1290 if (resolved_method != nullptr) {
1291 *vtable_idx = GetResolvedMethodVTableIndex(resolved_method, orig_invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001292
Vladimir Markof096aad2014-01-23 15:51:58 +00001293 if (enable_devirtualization) {
1294 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1295 const MethodReference* devirt_target = mUnit->GetVerifiedMethod()->GetDevirtTarget(dex_pc);
1296
1297 stats_flags = IsFastInvoke(
1298 soa, dex_cache, class_loader, mUnit, referrer_class, resolved_method,
1299 invoke_type, target_method, devirt_target, direct_code, direct_method);
1300 result = stats_flags != 0;
1301 } else {
1302 // Devirtualization not enabled. Inline IsFastInvoke(), dropping the devirtualization parts.
1303 if (UNLIKELY(referrer_class == nullptr) ||
1304 UNLIKELY(!referrer_class->CanAccessResolvedMethod(resolved_method->GetDeclaringClass(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001305 resolved_method, dex_cache.Get(),
Vladimir Markof096aad2014-01-23 15:51:58 +00001306 target_method->dex_method_index)) ||
1307 *invoke_type == kSuper) {
1308 // Slow path. (Without devirtualization, all super calls go slow path as well.)
1309 } else {
1310 // Sharpening failed so generate a regular resolved method dispatch.
1311 stats_flags = kFlagMethodResolved;
1312 GetCodeAndMethodForDirectCall(invoke_type, *invoke_type, false, referrer_class, resolved_method,
1313 &stats_flags, target_method, direct_code, direct_method);
1314 result = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001315 }
1316 }
1317 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001318 if (!result) {
1319 // Conservative defaults.
1320 *vtable_idx = -1;
1321 *direct_code = 0u;
1322 *direct_method = 0u;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001323 }
1324 if (update_stats) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001325 ProcessedInvoke(orig_invoke_type, stats_flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001326 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001327 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001328}
1329
Vladimir Marko2730db02014-01-27 11:15:17 +00001330const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1331 uint32_t method_idx) const {
1332 MethodReference ref(dex_file, method_idx);
1333 return verification_results_->GetVerifiedMethod(ref);
1334}
1335
1336bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07001337 if (!compiler_options_->IsVerificationEnabled()) {
1338 // If we didn't verify, every cast has to be treated as non-safe.
1339 return false;
1340 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001341 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1342 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001343 if (result) {
1344 stats_->SafeCast();
1345 } else {
1346 stats_->NotASafeCast();
1347 }
1348 return result;
1349}
1350
Brian Carlstrom7940e442013-07-12 13:46:57 -07001351void CompilerDriver::AddCodePatch(const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001352 uint16_t referrer_class_def_idx,
1353 uint32_t referrer_method_idx,
1354 InvokeType referrer_invoke_type,
1355 uint32_t target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001356 const DexFile* target_dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001357 InvokeType target_invoke_type,
1358 size_t literal_offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001359 MutexLock mu(Thread::Current(), compiled_methods_lock_);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001360 code_to_patch_.push_back(new CallPatchInformation(dex_file,
1361 referrer_class_def_idx,
1362 referrer_method_idx,
1363 referrer_invoke_type,
1364 target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001365 target_dex_file,
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001366 target_invoke_type,
1367 literal_offset));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001368}
Mark Mendell55d0eac2014-02-06 11:02:52 -08001369void CompilerDriver::AddRelativeCodePatch(const DexFile* dex_file,
1370 uint16_t referrer_class_def_idx,
1371 uint32_t referrer_method_idx,
1372 InvokeType referrer_invoke_type,
1373 uint32_t target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001374 const DexFile* target_dex_file,
Mark Mendell55d0eac2014-02-06 11:02:52 -08001375 InvokeType target_invoke_type,
1376 size_t literal_offset,
1377 int32_t pc_relative_offset) {
1378 MutexLock mu(Thread::Current(), compiled_methods_lock_);
1379 code_to_patch_.push_back(new RelativeCallPatchInformation(dex_file,
1380 referrer_class_def_idx,
1381 referrer_method_idx,
1382 referrer_invoke_type,
1383 target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001384 target_dex_file,
Mark Mendell55d0eac2014-02-06 11:02:52 -08001385 target_invoke_type,
1386 literal_offset,
1387 pc_relative_offset));
1388}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001389void CompilerDriver::AddMethodPatch(const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001390 uint16_t referrer_class_def_idx,
1391 uint32_t referrer_method_idx,
1392 InvokeType referrer_invoke_type,
1393 uint32_t target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001394 const DexFile* target_dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001395 InvokeType target_invoke_type,
1396 size_t literal_offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001397 MutexLock mu(Thread::Current(), compiled_methods_lock_);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001398 methods_to_patch_.push_back(new CallPatchInformation(dex_file,
1399 referrer_class_def_idx,
1400 referrer_method_idx,
1401 referrer_invoke_type,
1402 target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001403 target_dex_file,
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001404 target_invoke_type,
1405 literal_offset));
1406}
1407void CompilerDriver::AddClassPatch(const DexFile* dex_file,
1408 uint16_t referrer_class_def_idx,
1409 uint32_t referrer_method_idx,
1410 uint32_t target_type_idx,
1411 size_t literal_offset) {
1412 MutexLock mu(Thread::Current(), compiled_methods_lock_);
1413 classes_to_patch_.push_back(new TypePatchInformation(dex_file,
1414 referrer_class_def_idx,
1415 referrer_method_idx,
1416 target_type_idx,
1417 literal_offset));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001418}
Mathieu Chartier80714002014-11-20 15:04:10 -08001419void CompilerDriver::AddStringPatch(const DexFile* dex_file,
1420 uint16_t referrer_class_def_idx,
1421 uint32_t referrer_method_idx,
1422 uint32_t string_idx,
1423 size_t literal_offset) {
1424 MutexLock mu(Thread::Current(), compiled_methods_lock_);
1425 strings_to_patch_.push_back(new StringPatchInformation(dex_file,
1426 referrer_class_def_idx,
1427 referrer_method_idx,
1428 string_idx,
1429 literal_offset));
1430}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001431
1432class ParallelCompilationManager {
1433 public:
1434 typedef void Callback(const ParallelCompilationManager* manager, size_t index);
1435
1436 ParallelCompilationManager(ClassLinker* class_linker,
1437 jobject class_loader,
1438 CompilerDriver* compiler,
1439 const DexFile* dex_file,
Andreas Gampe01719872014-07-28 18:38:57 -07001440 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001441 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001442 : index_(0),
1443 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001444 class_loader_(class_loader),
1445 compiler_(compiler),
1446 dex_file_(dex_file),
Andreas Gampe01719872014-07-28 18:38:57 -07001447 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001448 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001449
1450 ClassLinker* GetClassLinker() const {
Andreas Gampe35439ba2014-08-28 14:41:02 -07001451 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001452 return class_linker_;
1453 }
1454
1455 jobject GetClassLoader() const {
1456 return class_loader_;
1457 }
1458
1459 CompilerDriver* GetCompiler() const {
Andreas Gampe35439ba2014-08-28 14:41:02 -07001460 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001461 return compiler_;
1462 }
1463
1464 const DexFile* GetDexFile() const {
Andreas Gampe35439ba2014-08-28 14:41:02 -07001465 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001466 return dex_file_;
1467 }
1468
Andreas Gampe01719872014-07-28 18:38:57 -07001469 const std::vector<const DexFile*>& GetDexFiles() const {
1470 return dex_files_;
1471 }
1472
Brian Carlstrom7940e442013-07-12 13:46:57 -07001473 void ForAll(size_t begin, size_t end, Callback callback, size_t work_units) {
1474 Thread* self = Thread::Current();
1475 self->AssertNoPendingException();
1476 CHECK_GT(work_units, 0U);
1477
Ian Rogers3e5cf302014-05-20 16:40:37 -07001478 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001479 for (size_t i = 0; i < work_units; ++i) {
Sebastien Hertz501baec2013-12-13 12:02:36 +01001480 thread_pool_->AddTask(self, new ForAllClosure(this, end, callback));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001481 }
1482 thread_pool_->StartWorkers(self);
1483
1484 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1485 // thread destructor's called below perform join).
1486 CHECK_NE(self->GetState(), kRunnable);
1487
1488 // Wait for all the worker threads to finish.
1489 thread_pool_->Wait(self, true, false);
1490 }
1491
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001492 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001493 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001494 }
1495
Brian Carlstrom7940e442013-07-12 13:46:57 -07001496 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001497 class ForAllClosure : public Task {
1498 public:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001499 ForAllClosure(ParallelCompilationManager* manager, size_t end, Callback* callback)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001500 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001501 end_(end),
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001502 callback_(callback) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001503
1504 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001505 while (true) {
1506 const size_t index = manager_->NextIndex();
1507 if (UNLIKELY(index >= end_)) {
1508 break;
1509 }
1510 callback_(manager_, index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001511 self->AssertNoPendingException();
1512 }
1513 }
1514
1515 virtual void Finalize() {
1516 delete this;
1517 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001518
Brian Carlstrom7940e442013-07-12 13:46:57 -07001519 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001520 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001521 const size_t end_;
Bernhard Rosenkränzer46053622013-12-12 02:15:52 +01001522 Callback* const callback_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001523 };
1524
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001525 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001526 ClassLinker* const class_linker_;
1527 const jobject class_loader_;
1528 CompilerDriver* const compiler_;
1529 const DexFile* const dex_file_;
Andreas Gampe01719872014-07-28 18:38:57 -07001530 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001531 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001532
1533 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001534};
1535
Jeff Hao0e49b422013-11-08 12:16:56 -08001536// A fast version of SkipClass above if the class pointer is available
1537// that avoids the expensive FindInClassPath search.
1538static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
1539 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07001540 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001541 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1542 if (&dex_file != &original_dex_file) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07001543 if (class_loader == nullptr) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001544 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1545 << dex_file.GetLocation() << " previously found in "
1546 << original_dex_file.GetLocation();
1547 }
1548 return true;
1549 }
1550 return false;
1551}
1552
Mathieu Chartier70b63482014-06-27 17:19:04 -07001553static void CheckAndClearResolveException(Thread* self)
1554 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1555 CHECK(self->IsExceptionPending());
1556 mirror::Throwable* exception = self->GetException(nullptr);
Ian Rogerscb6b0f32014-08-12 02:30:58 -07001557 std::string temp;
1558 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1559 const char* expected_exceptions[] = {
1560 "Ljava/lang/IllegalAccessError;",
1561 "Ljava/lang/IncompatibleClassChangeError;",
1562 "Ljava/lang/InstantiationError;",
Brian Carlstrom118785c2014-08-25 23:07:30 -07001563 "Ljava/lang/LinkageError;",
Ian Rogerscb6b0f32014-08-12 02:30:58 -07001564 "Ljava/lang/NoClassDefFoundError;",
1565 "Ljava/lang/NoSuchFieldError;",
1566 "Ljava/lang/NoSuchMethodError;"
1567 };
1568 bool found = false;
1569 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1570 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1571 found = true;
1572 }
1573 }
1574 if (!found) {
Brian Carlstrom118785c2014-08-25 23:07:30 -07001575 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07001576 }
1577 self->ClearException();
1578}
1579
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001580static void ResolveClassFieldsAndMethods(const ParallelCompilationManager* manager,
1581 size_t class_def_index)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001582 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001583 ATRACE_CALL();
Ian Rogersbe7149f2013-08-20 09:29:39 -07001584 Thread* self = Thread::Current();
1585 jobject jclass_loader = manager->GetClassLoader();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001586 const DexFile& dex_file = *manager->GetDexFile();
Ian Rogersbe7149f2013-08-20 09:29:39 -07001587 ClassLinker* class_linker = manager->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001588
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001589 // If an instance field is final then we need to have a barrier on the return, static final
1590 // fields are assigned within the lock held for class initialization. Conservatively assume
1591 // constructor barriers are always required.
1592 bool requires_constructor_barrier = true;
1593
Brian Carlstrom7940e442013-07-12 13:46:57 -07001594 // Method and Field are the worst. We can't resolve without either
1595 // context from the code use (to disambiguate virtual vs direct
1596 // method and instance vs static field) or from class
1597 // definitions. While the compiler will resolve what it can as it
1598 // needs it, here we try to resolve fields and methods used in class
1599 // definitions, since many of them many never be referenced by
1600 // generated code.
1601 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogerscc2f2392014-08-29 20:19:11 -07001602 ScopedObjectAccess soa(self);
1603 StackHandleScope<2> hs(soa.Self());
1604 Handle<mirror::ClassLoader> class_loader(
1605 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
1606 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(dex_file)));
1607 // Resolve the class.
1608 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
1609 class_loader);
1610 bool resolve_fields_and_methods;
1611 if (klass == nullptr) {
1612 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
1613 // attempt to resolve methods and fields when there is no declaring class.
1614 CheckAndClearResolveException(soa.Self());
1615 resolve_fields_and_methods = false;
1616 } else {
1617 // We successfully resolved a class, should we skip it?
1618 if (SkipClass(jclass_loader, dex_file, klass)) {
1619 return;
Brian Carlstromcb5f5e52013-09-23 17:48:16 -07001620 }
Ian Rogerscc2f2392014-08-29 20:19:11 -07001621 // We want to resolve the methods and fields eagerly.
1622 resolve_fields_and_methods = true;
1623 }
1624 // Note the class_data pointer advances through the headers,
1625 // static fields, instance fields, direct methods, and virtual
1626 // methods.
1627 const byte* class_data = dex_file.GetClassData(class_def);
Andreas Gampe35439ba2014-08-28 14:41:02 -07001628 if (class_data == nullptr) {
Ian Rogerscc2f2392014-08-29 20:19:11 -07001629 // Empty class such as a marker interface.
1630 requires_constructor_barrier = false;
1631 } else {
1632 ClassDataItemIterator it(dex_file, class_data);
1633 while (it.HasNextStaticField()) {
1634 if (resolve_fields_and_methods) {
1635 mirror::ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1636 dex_cache, class_loader, true);
Andreas Gampe35439ba2014-08-28 14:41:02 -07001637 if (field == nullptr) {
Ian Rogerscc2f2392014-08-29 20:19:11 -07001638 CheckAndClearResolveException(soa.Self());
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001639 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001640 }
Ian Rogerscc2f2392014-08-29 20:19:11 -07001641 it.Next();
1642 }
1643 // We require a constructor barrier if there are final instance fields.
1644 requires_constructor_barrier = false;
1645 while (it.HasNextInstanceField()) {
Andreas Gampe7fc8f902014-08-25 15:05:04 -07001646 if (it.MemberIsFinal()) {
Ian Rogerscc2f2392014-08-29 20:19:11 -07001647 requires_constructor_barrier = true;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001648 }
1649 if (resolve_fields_and_methods) {
Ian Rogerscc2f2392014-08-29 20:19:11 -07001650 mirror::ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1651 dex_cache, class_loader, false);
Andreas Gampe35439ba2014-08-28 14:41:02 -07001652 if (field == nullptr) {
Ian Rogerscc2f2392014-08-29 20:19:11 -07001653 CheckAndClearResolveException(soa.Self());
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001654 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001655 }
Ian Rogerscc2f2392014-08-29 20:19:11 -07001656 it.Next();
1657 }
1658 if (resolve_fields_and_methods) {
1659 while (it.HasNextDirectMethod()) {
1660 mirror::ArtMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1661 dex_cache, class_loader,
1662 NullHandle<mirror::ArtMethod>(),
1663 it.GetMethodInvokeType(class_def));
Andreas Gampe35439ba2014-08-28 14:41:02 -07001664 if (method == nullptr) {
Ian Rogerscc2f2392014-08-29 20:19:11 -07001665 CheckAndClearResolveException(soa.Self());
1666 }
1667 it.Next();
1668 }
1669 while (it.HasNextVirtualMethod()) {
1670 mirror::ArtMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1671 dex_cache, class_loader,
1672 NullHandle<mirror::ArtMethod>(),
1673 it.GetMethodInvokeType(class_def));
Andreas Gampe35439ba2014-08-28 14:41:02 -07001674 if (method == nullptr) {
Ian Rogerscc2f2392014-08-29 20:19:11 -07001675 CheckAndClearResolveException(soa.Self());
1676 }
1677 it.Next();
1678 }
1679 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001680 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001681 }
1682 if (requires_constructor_barrier) {
Ian Rogersbe7149f2013-08-20 09:29:39 -07001683 manager->GetCompiler()->AddRequiresConstructorBarrier(self, &dex_file, class_def_index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001684 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001685}
1686
1687static void ResolveType(const ParallelCompilationManager* manager, size_t type_idx)
1688 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1689 // Class derived values are more complicated, they require the linker and loader.
1690 ScopedObjectAccess soa(Thread::Current());
1691 ClassLinker* class_linker = manager->GetClassLinker();
1692 const DexFile& dex_file = *manager->GetDexFile();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001693 StackHandleScope<2> hs(soa.Self());
1694 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(dex_file)));
1695 Handle<mirror::ClassLoader> class_loader(
1696 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(manager->GetClassLoader())));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001697 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
1698
Andreas Gampe35439ba2014-08-28 14:41:02 -07001699 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001700 CHECK(soa.Self()->IsExceptionPending());
Andreas Gampe35439ba2014-08-28 14:41:02 -07001701 mirror::Throwable* exception = soa.Self()->GetException(nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07001702 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
Mathieu Chartierf8322842014-05-16 10:59:25 -07001703 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001704 // There's little point continuing compilation if the heap is exhausted.
1705 LOG(FATAL) << "Out of memory during type resolution for compilation";
1706 }
1707 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001708 }
1709}
1710
1711void CompilerDriver::ResolveDexFile(jobject class_loader, const DexFile& dex_file,
Andreas Gampe01719872014-07-28 18:38:57 -07001712 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001713 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001714 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1715
1716 // TODO: we could resolve strings here, although the string table is largely filled with class
1717 // and method names.
1718
Andreas Gampe01719872014-07-28 18:38:57 -07001719 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
1720 thread_pool);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001721 if (IsImage()) {
1722 // For images we resolve all types, such as array, whereas for applications just those with
1723 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001724 TimingLogger::ScopedTiming t("Resolve Types", timings);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001725 context.ForAll(0, dex_file.NumTypeIds(), ResolveType, thread_count_);
1726 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001727
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001728 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001729 context.ForAll(0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001730}
1731
Andreas Gampe35439ba2014-08-28 14:41:02 -07001732void CompilerDriver::SetVerified(jobject class_loader, const std::vector<const DexFile*>& dex_files,
1733 ThreadPool* thread_pool, TimingLogger* timings) {
1734 for (size_t i = 0; i != dex_files.size(); ++i) {
1735 const DexFile* dex_file = dex_files[i];
1736 CHECK(dex_file != nullptr);
1737 SetVerifiedDexFile(class_loader, *dex_file, dex_files, thread_pool, timings);
1738 }
1739}
1740
Brian Carlstrom7940e442013-07-12 13:46:57 -07001741void CompilerDriver::Verify(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001742 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001743 for (size_t i = 0; i != dex_files.size(); ++i) {
1744 const DexFile* dex_file = dex_files[i];
Andreas Gampe35439ba2014-08-28 14:41:02 -07001745 CHECK(dex_file != nullptr);
Andreas Gampe01719872014-07-28 18:38:57 -07001746 VerifyDexFile(class_loader, *dex_file, dex_files, thread_pool, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001747 }
1748}
1749
1750static void VerifyClass(const ParallelCompilationManager* manager, size_t class_def_index)
1751 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001752 ATRACE_CALL();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001753 ScopedObjectAccess soa(Thread::Current());
Jeff Hao0e49b422013-11-08 12:16:56 -08001754 const DexFile& dex_file = *manager->GetDexFile();
1755 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1756 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1757 ClassLinker* class_linker = manager->GetClassLinker();
1758 jobject jclass_loader = manager->GetClassLoader();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001759 StackHandleScope<3> hs(soa.Self());
1760 Handle<mirror::ClassLoader> class_loader(
1761 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
1762 Handle<mirror::Class> klass(
1763 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
1764 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001765 CHECK(soa.Self()->IsExceptionPending());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001766 soa.Self()->ClearException();
1767
1768 /*
1769 * At compile time, we can still structurally verify the class even if FindClass fails.
1770 * This is to ensure the class is structurally sound for compilation. An unsound class
1771 * will be rejected by the verifier and later skipped during compilation in the compiler.
1772 */
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001773 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(dex_file)));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001774 std::string error_msg;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001775 if (verifier::MethodVerifier::VerifyClass(&dex_file, dex_cache, class_loader, &class_def, true,
1776 &error_msg) ==
Brian Carlstrom7940e442013-07-12 13:46:57 -07001777 verifier::MethodVerifier::kHardFailure) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001778 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001779 << " because: " << error_msg;
1780 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001781 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
1782 CHECK(klass->IsResolved()) << PrettyClass(klass.Get());
Jeff Hao0e49b422013-11-08 12:16:56 -08001783 class_linker->VerifyClass(klass);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001784
1785 if (klass->IsErroneous()) {
1786 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1787 CHECK(soa.Self()->IsExceptionPending());
1788 soa.Self()->ClearException();
1789 }
1790
1791 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001792 << PrettyDescriptor(klass.Get()) << ": state=" << klass->GetStatus();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001793 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001794 soa.Self()->AssertNoPendingException();
1795}
1796
1797void CompilerDriver::VerifyDexFile(jobject class_loader, const DexFile& dex_file,
Andreas Gampe01719872014-07-28 18:38:57 -07001798 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001799 ThreadPool* thread_pool, TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001800 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001801 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampe01719872014-07-28 18:38:57 -07001802 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
1803 thread_pool);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001804 context.ForAll(0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001805}
1806
Andreas Gampe35439ba2014-08-28 14:41:02 -07001807static void SetVerifiedClass(const ParallelCompilationManager* manager, size_t class_def_index)
1808 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1809 ATRACE_CALL();
1810 ScopedObjectAccess soa(Thread::Current());
1811 const DexFile& dex_file = *manager->GetDexFile();
1812 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1813 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1814 ClassLinker* class_linker = manager->GetClassLinker();
1815 jobject jclass_loader = manager->GetClassLoader();
1816 StackHandleScope<3> hs(soa.Self());
1817 Handle<mirror::ClassLoader> class_loader(
1818 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
1819 Handle<mirror::Class> klass(
1820 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
1821 // Class might have failed resolution. Then don't set it to verified.
1822 if (klass.Get() != nullptr) {
1823 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
1824 // very wrong.
1825 if (klass->IsResolved()) {
1826 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
1827 ObjectLock<mirror::Class> lock(soa.Self(), klass);
1828 klass->SetStatus(mirror::Class::kStatusVerified, soa.Self());
1829 }
1830 // Record the final class status if necessary.
1831 ClassReference ref(manager->GetDexFile(), class_def_index);
1832 manager->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
1833 }
Andreas Gampeba354a92014-09-16 11:23:23 -07001834 } else {
1835 Thread* self = soa.Self();
1836 DCHECK(self->IsExceptionPending());
1837 self->ClearException();
Andreas Gampe35439ba2014-08-28 14:41:02 -07001838 }
Andreas Gampe35439ba2014-08-28 14:41:02 -07001839}
1840
1841void CompilerDriver::SetVerifiedDexFile(jobject class_loader, const DexFile& dex_file,
1842 const std::vector<const DexFile*>& dex_files,
1843 ThreadPool* thread_pool, TimingLogger* timings) {
1844 TimingLogger::ScopedTiming t("Verify Dex File", timings);
1845 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1846 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
1847 thread_pool);
1848 context.ForAll(0, dex_file.NumClassDefs(), SetVerifiedClass, thread_count_);
1849}
1850
Brian Carlstrom7940e442013-07-12 13:46:57 -07001851static void InitializeClass(const ParallelCompilationManager* manager, size_t class_def_index)
1852 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001853 ATRACE_CALL();
Jeff Hao0e49b422013-11-08 12:16:56 -08001854 jobject jclass_loader = manager->GetClassLoader();
1855 const DexFile& dex_file = *manager->GetDexFile();
1856 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Jeff Haobcdbbfe2013-11-08 18:03:22 -08001857 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
1858 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001859
Brian Carlstrom7940e442013-07-12 13:46:57 -07001860 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001861 StackHandleScope<3> hs(soa.Self());
1862 Handle<mirror::ClassLoader> class_loader(
1863 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
1864 Handle<mirror::Class> klass(
1865 hs.NewHandle(manager->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
Jeff Hao0e49b422013-11-08 12:16:56 -08001866
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001867 if (klass.Get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001868 // Only try to initialize classes that were successfully verified.
1869 if (klass->IsVerified()) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001870 // Attempt to initialize the class but bail if we either need to initialize the super-class
1871 // or static fields.
1872 manager->GetClassLinker()->EnsureInitialized(klass, false, false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001873 if (!klass->IsInitialized()) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001874 // We don't want non-trivial class initialization occurring on multiple threads due to
1875 // deadlock problems. For example, a parent class is initialized (holding its lock) that
1876 // refers to a sub-class in its static/class initializer causing it to try to acquire the
1877 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
1878 // after first initializing its parents, whose locks are acquired. This leads to a
1879 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
1880 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
1881 // than use a special Object for the purpose we use the Class of java.lang.Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001882 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001883 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001884 // Attempt to initialize allowing initialization of parent classes but still not static
1885 // fields.
1886 manager->GetClassLinker()->EnsureInitialized(klass, false, true);
1887 if (!klass->IsInitialized()) {
1888 // We need to initialize static fields, we only do this for image classes that aren't
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001889 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001890 bool can_init_static_fields = manager->GetCompiler()->IsImage() &&
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001891 manager->GetCompiler()->IsImageClass(descriptor) &&
1892 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001893 if (can_init_static_fields) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001894 VLOG(compiler) << "Initializing: " << descriptor;
Ian Rogersc45b8b52014-05-03 01:39:59 -07001895 // TODO multithreading support. We should ensure the current compilation thread has
1896 // exclusive access to the runtime and the transaction. To achieve this, we could use
1897 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
1898 // checks in Thread::AssertThreadSuspensionIsAllowable.
1899 Runtime* const runtime = Runtime::Current();
1900 Transaction transaction;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001901
Ian Rogersc45b8b52014-05-03 01:39:59 -07001902 // Run the class initializer in transaction mode.
1903 runtime->EnterTransactionMode(&transaction);
1904 const mirror::Class::Status old_status = klass->GetStatus();
1905 bool success = manager->GetClassLinker()->EnsureInitialized(klass, true, true);
1906 // TODO we detach transaction from runtime to indicate we quit the transactional
1907 // mode which prevents the GC from visiting objects modified during the transaction.
1908 // Ensure GC is not run so don't access freed objects when aborting transaction.
1909 const char* old_casue = soa.Self()->StartAssertNoThreadSuspension("Transaction end");
1910 runtime->ExitTransactionMode();
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001911
Ian Rogersc45b8b52014-05-03 01:39:59 -07001912 if (!success) {
1913 CHECK(soa.Self()->IsExceptionPending());
1914 ThrowLocation throw_location;
1915 mirror::Throwable* exception = soa.Self()->GetException(&throw_location);
1916 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
1917 << exception->Dump();
1918 soa.Self()->ClearException();
1919 transaction.Abort();
1920 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Brian Carlstrom7940e442013-07-12 13:46:57 -07001921 }
Ian Rogersc45b8b52014-05-03 01:39:59 -07001922 soa.Self()->EndAssertNoThreadSuspension(old_casue);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001923 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001924 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001925 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001926 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001927 }
1928 // Record the final class status if necessary.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001929 ClassReference ref(manager->GetDexFile(), class_def_index);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001930 manager->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001931 }
1932 // Clear any class not found or verification exceptions.
1933 soa.Self()->ClearException();
1934}
1935
1936void CompilerDriver::InitializeClasses(jobject jni_class_loader, const DexFile& dex_file,
Andreas Gampe01719872014-07-28 18:38:57 -07001937 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001938 ThreadPool* thread_pool, TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001939 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001940 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampe01719872014-07-28 18:38:57 -07001941 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
1942 thread_pool);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001943 size_t thread_count;
1944 if (IsImage()) {
1945 // TODO: remove this when transactional mode supports multithreading.
1946 thread_count = 1U;
1947 } else {
1948 thread_count = thread_count_;
1949 }
1950 context.ForAll(0, dex_file.NumClassDefs(), InitializeClass, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001951}
1952
1953void CompilerDriver::InitializeClasses(jobject class_loader,
1954 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001955 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001956 for (size_t i = 0; i != dex_files.size(); ++i) {
1957 const DexFile* dex_file = dex_files[i];
Andreas Gampe35439ba2014-08-28 14:41:02 -07001958 CHECK(dex_file != nullptr);
Andreas Gampe01719872014-07-28 18:38:57 -07001959 InitializeClasses(class_loader, *dex_file, dex_files, thread_pool, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001960 }
Mathieu Chartiera73a8b52014-08-11 13:52:12 -07001961 if (IsImage()) {
1962 // Prune garbage objects created during aborted transactions.
1963 Runtime::Current()->GetHeap()->CollectGarbage(true);
1964 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001965}
1966
1967void CompilerDriver::Compile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001968 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001969 for (size_t i = 0; i != dex_files.size(); ++i) {
1970 const DexFile* dex_file = dex_files[i];
Andreas Gampe35439ba2014-08-28 14:41:02 -07001971 CHECK(dex_file != nullptr);
Andreas Gampe01719872014-07-28 18:38:57 -07001972 CompileDexFile(class_loader, *dex_file, dex_files, thread_pool, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001973 }
Mathieu Chartier25fda922014-12-03 17:38:22 -08001974 VLOG(compiler) << "Compile: " << GetMemoryUsageString();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001975}
1976
1977void CompilerDriver::CompileClass(const ParallelCompilationManager* manager, size_t class_def_index) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001978 ATRACE_CALL();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001979 const DexFile& dex_file = *manager->GetDexFile();
1980 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogersbe7149f2013-08-20 09:29:39 -07001981 ClassLinker* class_linker = manager->GetClassLinker();
Ian Rogerscb6b0f32014-08-12 02:30:58 -07001982 jobject jclass_loader = manager->GetClassLoader();
1983 {
1984 // Use a scoped object access to perform to the quick SkipClass check.
1985 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1986 ScopedObjectAccess soa(Thread::Current());
1987 StackHandleScope<3> hs(soa.Self());
1988 Handle<mirror::ClassLoader> class_loader(
1989 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
1990 Handle<mirror::Class> klass(
1991 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
1992 if (klass.Get() == nullptr) {
1993 CHECK(soa.Self()->IsExceptionPending());
1994 soa.Self()->ClearException();
1995 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
1996 return;
1997 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001998 }
1999 ClassReference ref(&dex_file, class_def_index);
2000 // Skip compiling classes with generic verifier failures since they will still fail at runtime
Vladimir Markoc7f83202014-01-24 17:55:18 +00002001 if (manager->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002002 return;
2003 }
2004 const byte* class_data = dex_file.GetClassData(class_def);
Andreas Gampe35439ba2014-08-28 14:41:02 -07002005 if (class_data == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002006 // empty class, probably a marker interface
2007 return;
2008 }
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002009
Brian Carlstrom7940e442013-07-12 13:46:57 -07002010 // Can we run DEX-to-DEX compiler on this class ?
Sebastien Hertz75021222013-07-16 18:34:50 +02002011 DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002012 {
2013 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002014 StackHandleScope<1> hs(soa.Self());
2015 Handle<mirror::ClassLoader> class_loader(
2016 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
Ian Rogers98379392014-02-24 16:53:16 -08002017 dex_to_dex_compilation_level = GetDexToDexCompilationlevel(soa.Self(), class_loader, dex_file,
2018 class_def);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002019 }
2020 ClassDataItemIterator it(dex_file, class_data);
2021 // Skip fields
2022 while (it.HasNextStaticField()) {
2023 it.Next();
2024 }
2025 while (it.HasNextInstanceField()) {
2026 it.Next();
2027 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002028 CompilerDriver* driver = manager->GetCompiler();
Andreas Gampe26318f72014-11-11 13:28:29 -08002029
2030 bool compilation_enabled = driver->IsClassToCompile(
2031 dex_file.StringByTypeIdx(class_def.class_idx_));
2032
Brian Carlstrom7940e442013-07-12 13:46:57 -07002033 // Compile direct methods
2034 int64_t previous_direct_method_idx = -1;
2035 while (it.HasNextDirectMethod()) {
2036 uint32_t method_idx = it.GetMemberIndex();
2037 if (method_idx == previous_direct_method_idx) {
2038 // smali can create dex files with two encoded_methods sharing the same method_idx
2039 // http://code.google.com/p/smali/issues/detail?id=119
2040 it.Next();
2041 continue;
2042 }
2043 previous_direct_method_idx = method_idx;
Andreas Gampe7fc8f902014-08-25 15:05:04 -07002044 driver->CompileMethod(it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Ian Rogersbe7149f2013-08-20 09:29:39 -07002045 it.GetMethodInvokeType(class_def), class_def_index,
Andreas Gampe26318f72014-11-11 13:28:29 -08002046 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
2047 compilation_enabled);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002048 it.Next();
2049 }
2050 // Compile virtual methods
2051 int64_t previous_virtual_method_idx = -1;
2052 while (it.HasNextVirtualMethod()) {
2053 uint32_t method_idx = it.GetMemberIndex();
2054 if (method_idx == previous_virtual_method_idx) {
2055 // smali can create dex files with two encoded_methods sharing the same method_idx
2056 // http://code.google.com/p/smali/issues/detail?id=119
2057 it.Next();
2058 continue;
2059 }
2060 previous_virtual_method_idx = method_idx;
Andreas Gampe7fc8f902014-08-25 15:05:04 -07002061 driver->CompileMethod(it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Ian Rogersbe7149f2013-08-20 09:29:39 -07002062 it.GetMethodInvokeType(class_def), class_def_index,
Andreas Gampe26318f72014-11-11 13:28:29 -08002063 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
2064 compilation_enabled);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002065 it.Next();
2066 }
2067 DCHECK(!it.HasNext());
2068}
2069
2070void CompilerDriver::CompileDexFile(jobject class_loader, const DexFile& dex_file,
Andreas Gampe01719872014-07-28 18:38:57 -07002071 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08002072 ThreadPool* thread_pool, TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002073 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002074 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampe01719872014-07-28 18:38:57 -07002075 &dex_file, dex_files, thread_pool);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002076 context.ForAll(0, dex_file.NumClassDefs(), CompilerDriver::CompileClass, thread_count_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002077}
2078
2079void CompilerDriver::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002080 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom7940e442013-07-12 13:46:57 -07002081 uint32_t method_idx, jobject class_loader,
2082 const DexFile& dex_file,
Andreas Gampe26318f72014-11-11 13:28:29 -08002083 DexToDexCompilationLevel dex_to_dex_compilation_level,
2084 bool compilation_enabled) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07002085 CompiledMethod* compiled_method = nullptr;
Mathieu Chartierb68c6e52014-08-19 14:29:46 -07002086 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
Mathieu Chartier25fda922014-12-03 17:38:22 -08002087 MethodReference method_ref(&dex_file, method_idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002088
2089 if ((access_flags & kAccNative) != 0) {
Ian Rogers0188ab72014-03-17 16:51:53 -07002090 // Are we interpreting only and have support for generic JNI down calls?
Jeff Hao4a200f52014-04-01 14:58:49 -07002091 if (!compiler_options_->IsCompilationEnabled() &&
Stuart Monteithb95a5342014-03-12 13:32:32 +00002092 (instruction_set_ == kX86_64 || instruction_set_ == kArm64)) {
Ian Rogers5b271492014-03-14 13:20:26 -07002093 // Leaving this empty will trigger the generic JNI version
2094 } else {
Ian Rogers72d32622014-05-06 16:20:11 -07002095 compiled_method = compiler_->JniCompile(access_flags, method_idx, dex_file);
Andreas Gampe35439ba2014-08-28 14:41:02 -07002096 CHECK(compiled_method != nullptr);
Ian Rogers5b271492014-03-14 13:20:26 -07002097 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002098 } else if ((access_flags & kAccAbstract) != 0) {
2099 } else {
Andreas Gampef535c692014-12-17 14:35:46 -08002100 bool has_verified_method = verification_results_->GetVerifiedMethod(method_ref) != nullptr;
Andreas Gampe26318f72014-11-11 13:28:29 -08002101 bool compile = compilation_enabled &&
Andreas Gampef535c692014-12-17 14:35:46 -08002102 // Basic checks, e.g., not <clinit>.
2103 verification_results_->IsCandidateForCompilation(method_ref, access_flags) &&
2104 // Did not fail to create VerifiedMethod metadata.
2105 has_verified_method;
Sebastien Hertz4d4adb12013-07-24 16:14:19 +02002106 if (compile) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07002107 // NOTE: if compiler declines to compile this method, it will return nullptr.
Ian Rogers72d32622014-05-06 16:20:11 -07002108 compiled_method = compiler_->Compile(code_item, access_flags, invoke_type, class_def_idx,
2109 method_idx, class_loader, dex_file);
Sebastien Hertz17965ed2014-04-04 15:59:53 +02002110 }
2111 if (compiled_method == nullptr && dex_to_dex_compilation_level != kDontDexToDexCompile) {
2112 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Andreas Gampef535c692014-12-17 14:35:46 -08002113 // Do not optimize if a VerifiedMethod is missing. SafeCast elision, for example, relies on
2114 // it.
Sebastien Hertz75021222013-07-16 18:34:50 +02002115 (*dex_to_dex_compiler_)(*this, code_item, access_flags,
2116 invoke_type, class_def_idx,
2117 method_idx, class_loader, dex_file,
Andreas Gampef535c692014-12-17 14:35:46 -08002118 has_verified_method ? dex_to_dex_compilation_level : kRequired);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002119 }
2120 }
Mathieu Chartierb68c6e52014-08-19 14:29:46 -07002121 if (kTimeCompileMethod) {
2122 uint64_t duration_ns = NanoTime() - start_ns;
2123 if (duration_ns > MsToNs(compiler_->GetMaximumCompilationTimeBeforeWarning())) {
2124 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
2125 << " took " << PrettyDuration(duration_ns);
2126 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002127 }
2128
2129 Thread* self = Thread::Current();
Andreas Gampe35439ba2014-08-28 14:41:02 -07002130 if (compiled_method != nullptr) {
Mathieu Chartier25fda922014-12-03 17:38:22 -08002131 DCHECK(GetCompiledMethod(method_ref) == nullptr) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002132 {
2133 MutexLock mu(self, compiled_methods_lock_);
Mathieu Chartier25fda922014-12-03 17:38:22 -08002134 compiled_methods_.Put(method_ref, compiled_method);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002135 }
Mathieu Chartier25fda922014-12-03 17:38:22 -08002136 DCHECK(GetCompiledMethod(method_ref) != nullptr) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002137 }
2138
Mathieu Chartier25fda922014-12-03 17:38:22 -08002139 // Done compiling, delete the verified method to reduce native memory usage.
2140 verification_results_->RemoveVerifiedMethod(method_ref);
2141
Brian Carlstrom7940e442013-07-12 13:46:57 -07002142 if (self->IsExceptionPending()) {
2143 ScopedObjectAccess soa(self);
2144 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
Andreas Gampe35439ba2014-08-28 14:41:02 -07002145 << self->GetException(nullptr)->Dump();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002146 }
2147}
2148
2149CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
2150 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2151 ClassTable::const_iterator it = compiled_classes_.find(ref);
2152 if (it == compiled_classes_.end()) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07002153 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002154 }
Andreas Gampe35439ba2014-08-28 14:41:02 -07002155 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002156 return it->second;
2157}
2158
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002159void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2160 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2161 auto it = compiled_classes_.find(ref);
2162 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2163 // An entry doesn't exist or the status is lower than the new status.
2164 if (it != compiled_classes_.end()) {
2165 CHECK_GT(status, it->second->GetStatus());
2166 delete it->second;
2167 }
2168 switch (status) {
2169 case mirror::Class::kStatusNotReady:
2170 case mirror::Class::kStatusError:
2171 case mirror::Class::kStatusRetryVerificationAtRuntime:
2172 case mirror::Class::kStatusVerified:
2173 case mirror::Class::kStatusInitialized:
2174 break; // Expected states.
2175 default:
2176 LOG(FATAL) << "Unexpected class status for class "
2177 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2178 << " of " << status;
2179 }
2180 CompiledClass* compiled_class = new CompiledClass(status);
2181 compiled_classes_.Overwrite(ref, compiled_class);
2182 }
2183}
2184
Brian Carlstrom7940e442013-07-12 13:46:57 -07002185CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2186 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2187 MethodTable::const_iterator it = compiled_methods_.find(ref);
2188 if (it == compiled_methods_.end()) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07002189 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002190 }
Andreas Gampe35439ba2014-08-28 14:41:02 -07002191 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002192 return it->second;
2193}
2194
Brian Carlstrom7940e442013-07-12 13:46:57 -07002195void CompilerDriver::AddRequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002196 uint16_t class_def_index) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002197 WriterMutexLock mu(self, freezing_constructor_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002198 freezing_constructor_classes_.insert(ClassReference(dex_file, class_def_index));
2199}
2200
2201bool CompilerDriver::RequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002202 uint16_t class_def_index) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002203 ReaderMutexLock mu(self, freezing_constructor_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002204 return freezing_constructor_classes_.count(ClassReference(dex_file, class_def_index)) != 0;
2205}
2206
2207bool CompilerDriver::WriteElf(const std::string& android_root,
2208 bool is_host,
2209 const std::vector<const art::DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08002210 OatWriter* oat_writer,
Brian Carlstrom7940e442013-07-12 13:46:57 -07002211 art::File* file)
2212 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers72d32622014-05-06 16:20:11 -07002213 return compiler_->WriteElf(file, oat_writer, dex_files, android_root, is_host);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002214}
2215void CompilerDriver::InstructionSetToLLVMTarget(InstructionSet instruction_set,
Ian Rogers3d504072014-03-01 09:16:49 -08002216 std::string* target_triple,
2217 std::string* target_cpu,
2218 std::string* target_attr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002219 switch (instruction_set) {
2220 case kThumb2:
Ian Rogers3d504072014-03-01 09:16:49 -08002221 *target_triple = "thumb-none-linux-gnueabi";
2222 *target_cpu = "cortex-a9";
2223 *target_attr = "+thumb2,+neon,+neonfp,+vfp3,+db";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002224 break;
2225
2226 case kArm:
Ian Rogers3d504072014-03-01 09:16:49 -08002227 *target_triple = "armv7-none-linux-gnueabi";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002228 // TODO: Fix for Nexus S.
Ian Rogers3d504072014-03-01 09:16:49 -08002229 *target_cpu = "cortex-a9";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002230 // TODO: Fix for Xoom.
Ian Rogers3d504072014-03-01 09:16:49 -08002231 *target_attr = "+v7,+neon,+neonfp,+vfp3,+db";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002232 break;
2233
2234 case kX86:
Ian Rogers3d504072014-03-01 09:16:49 -08002235 *target_triple = "i386-pc-linux-gnu";
2236 *target_attr = "";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002237 break;
2238
Dmitry Petrochenko6a58cb12014-04-02 17:27:59 +07002239 case kX86_64:
2240 *target_triple = "x86_64-pc-linux-gnu";
2241 *target_attr = "";
2242 break;
2243
Brian Carlstrom7940e442013-07-12 13:46:57 -07002244 case kMips:
Ian Rogers3d504072014-03-01 09:16:49 -08002245 *target_triple = "mipsel-unknown-linux";
2246 *target_attr = "mips32r2";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002247 break;
2248
2249 default:
2250 LOG(FATAL) << "Unknown instruction set: " << instruction_set;
2251 }
2252 }
Dave Allison39c3bfb2014-01-28 18:33:52 -08002253
Dave Allison39c3bfb2014-01-28 18:33:52 -08002254bool CompilerDriver::SkipCompilation(const std::string& method_name) {
Calin Juravlec1b643c2014-05-30 23:44:11 +01002255 if (!profile_present_) {
Dave Allison644789f2014-04-10 13:06:10 -07002256 return false;
Dave Allison39c3bfb2014-01-28 18:33:52 -08002257 }
Calin Juravlebb0b53f2014-05-23 17:33:29 +01002258 // First find the method in the profile file.
2259 ProfileFile::ProfileData data;
2260 if (!profile_file_.GetProfileData(&data, method_name)) {
Dave Allison39c3bfb2014-01-28 18:33:52 -08002261 // Not in profile, no information can be determined.
Calin Juravle08f7a2d2014-06-23 15:22:29 +01002262 if (kIsDebugBuild) {
2263 VLOG(compiler) << "not compiling " << method_name << " because it's not in the profile";
2264 }
Dave Allison39c3bfb2014-01-28 18:33:52 -08002265 return true;
2266 }
Calin Juravlebb0b53f2014-05-23 17:33:29 +01002267
2268 // Methods that comprise top_k_threshold % of the total samples will be compiled.
Calin Juravlef6a4cee2014-04-02 17:03:08 +01002269 // Compare against the start of the topK percentage bucket just in case the threshold
Calin Juravle04ff2262014-04-02 19:08:47 +01002270 // falls inside a bucket.
Calin Juravlec1b643c2014-05-30 23:44:11 +01002271 bool compile = data.GetTopKUsedPercentage() - data.GetUsedPercent()
2272 <= compiler_options_->GetTopKProfileThreshold();
Calin Juravle08f7a2d2014-06-23 15:22:29 +01002273 if (kIsDebugBuild) {
2274 if (compile) {
2275 LOG(INFO) << "compiling method " << method_name << " because its usage is part of top "
2276 << data.GetTopKUsedPercentage() << "% with a percent of " << data.GetUsedPercent() << "%"
2277 << " (topKThreshold=" << compiler_options_->GetTopKProfileThreshold() << ")";
2278 } else {
2279 VLOG(compiler) << "not compiling method " << method_name
2280 << " because it's not part of leading " << compiler_options_->GetTopKProfileThreshold()
2281 << "% samples)";
2282 }
Dave Allison39c3bfb2014-01-28 18:33:52 -08002283 }
2284 return !compile;
2285}
Mathieu Chartier25fda922014-12-03 17:38:22 -08002286
2287std::string CompilerDriver::GetMemoryUsageString() const {
2288 std::ostringstream oss;
2289 const ArenaPool* arena_pool = GetArenaPool();
2290 gc::Heap* heap = Runtime::Current()->GetHeap();
2291 oss << "arena alloc=" << PrettySize(arena_pool->GetBytesAllocated());
2292 oss << " java alloc=" << PrettySize(heap->GetBytesAllocated());
2293#ifdef HAVE_MALLOC_H
2294 struct mallinfo info = mallinfo();
2295 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2296 const size_t free_space = static_cast<size_t>(info.fordblks);
2297 oss << " native alloc=" << PrettySize(allocated_space) << " free="
2298 << PrettySize(free_space);
2299#endif
2300 return oss.str();
2301}
2302
Brian Carlstrom7940e442013-07-12 13:46:57 -07002303} // namespace art