blob: 8bf3b0486a46d7c66f85b98314801b58a5d3fc0a [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
Calin Juravlef6a4cee2014-04-02 17:03:08 +010022#include <fstream>
Anwar Ghuloum67f99412013-08-12 14:19:48 -070023#include <vector>
Brian Carlstrom7940e442013-07-12 13:46:57 -070024#include <unistd.h>
Calin Juravlef6a4cee2014-04-02 17:03:08 +010025#include <utility>
Brian Carlstrom7940e442013-07-12 13:46:57 -070026
Dave Allison754ddad2014-02-19 14:05:39 -080027#include "arch/arm/final_relocations_arm.h"
28#include "base/hex_dump.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070029#include "base/stl_util.h"
30#include "base/timing_logger.h"
31#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000032#include "compiler.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000033#include "compiler_driver-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070034#include "dex_compilation_unit.h"
35#include "dex_file-inl.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000036#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000037#include "dex/verified_method.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000038#include "dex/quick/dex_file_method_inliner.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080039#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070040#include "jni_internal.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "object_utils.h"
42#include "runtime.h"
43#include "gc/accounting/card_table-inl.h"
44#include "gc/accounting/heap_bitmap.h"
45#include "gc/space/space.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070046#include "mirror/art_field-inl.h"
47#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070048#include "mirror/class_loader.h"
49#include "mirror/class-inl.h"
50#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "mirror/object-inl.h"
52#include "mirror/object_array-inl.h"
53#include "mirror/throwable.h"
54#include "scoped_thread_state_change.h"
55#include "ScopedLocalRef.h"
Mathieu Chartierc645f1d2014-03-06 18:11:53 -080056#include "sirt_ref-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070057#include "thread.h"
58#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070059#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010060#include "transaction.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "verifier/method_verifier.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000062#include "verifier/method_verifier-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063
Calin Juravle04ff2262014-04-02 19:08:47 +010064#ifdef HAVE_ANDROID_OS
65#include "cutils/properties.h"
66#endif
67
Brian Carlstrom7940e442013-07-12 13:46:57 -070068namespace art {
69
70static 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,
buzbeea024a062013-07-31 10:47:37 -0700337 bool image, DescriptorSet* image_classes, size_t thread_count,
Dave Allison39c3bfb2014-01-28 18:33:52 -0800338 bool dump_stats, bool dump_passes, CumulativeLogger* timer,
339 std::string profile_file)
340 : profile_ok_(false), compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800341 verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000342 method_inliner_map_(method_inliner_map),
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000343 compiler_(Compiler::Create(compiler_kind)),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700344 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700345 instruction_set_features_(instruction_set_features),
Ian Rogersdd7624d2014-03-14 17:43:00 -0700346 instruction_set_is_64_bit_(instruction_set == kX86_64 || instruction_set == kArm64),
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),
352 thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700353 start_ns_(0),
354 stats_(new AOTCompilationStats),
355 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000356 dump_passes_(dump_passes),
357 timings_logger_(timer),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700358 compiler_library_(NULL),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700359 compiler_context_(NULL),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700360 compiler_enable_auto_elf_loading_(NULL),
361 compiler_get_method_code_addr_(NULL),
Mark Mendell55d0eac2014-02-06 11:02:52 -0800362 support_boot_image_fixup_(instruction_set != kMips),
Mark Mendellae9fd932014-02-10 16:14:35 -0800363 cfi_info_(nullptr),
Ian Rogersd133b972013-09-05 11:01:30 -0700364 dedupe_code_("dedupe code"),
365 dedupe_mapping_table_("dedupe mapping table"),
366 dedupe_vmap_table_("dedupe vmap table"),
Mark Mendellae9fd932014-02-10 16:14:35 -0800367 dedupe_gc_map_("dedupe gc map"),
368 dedupe_cfi_info_("dedupe cfi info") {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800369 DCHECK(compiler_options_ != nullptr);
370 DCHECK(verification_results_ != nullptr);
371 DCHECK(method_inliner_map_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700372
Brian Carlstrom7940e442013-07-12 13:46:57 -0700373 CHECK_PTHREAD_CALL(pthread_key_create, (&tls_key_, NULL), "compiler tls key");
374
Dave Allison39c3bfb2014-01-28 18:33:52 -0800375 // Read the profile file if one is provided.
376 if (profile_file != "") {
377 profile_ok_ = ReadProfile(profile_file);
378 }
379
Sebastien Hertz75021222013-07-16 18:34:50 +0200380 dex_to_dex_compiler_ = reinterpret_cast<DexToDexCompilerFn>(ArtCompileDEX);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700381
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000382 compiler_->Init(*this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700383
384 CHECK(!Runtime::Current()->IsStarted());
385 if (!image_) {
386 CHECK(image_classes_.get() == NULL);
387 }
Mark Mendellae9fd932014-02-10 16:14:35 -0800388
389 // Are we generating CFI information?
390 if (compiler_options->GetGenerateGDBInformation()) {
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000391 cfi_info_.reset(compiler_->GetCallFrameInformationInitialization(*this));
Mark Mendellae9fd932014-02-10 16:14:35 -0800392 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700393}
394
Mathieu Chartier193bad92013-08-29 18:46:00 -0700395std::vector<uint8_t>* CompilerDriver::DeduplicateCode(const std::vector<uint8_t>& code) {
396 return dedupe_code_.Add(Thread::Current(), code);
397}
398
399std::vector<uint8_t>* CompilerDriver::DeduplicateMappingTable(const std::vector<uint8_t>& code) {
400 return dedupe_mapping_table_.Add(Thread::Current(), code);
401}
402
403std::vector<uint8_t>* CompilerDriver::DeduplicateVMapTable(const std::vector<uint8_t>& code) {
404 return dedupe_vmap_table_.Add(Thread::Current(), code);
405}
406
407std::vector<uint8_t>* CompilerDriver::DeduplicateGCMap(const std::vector<uint8_t>& code) {
408 return dedupe_gc_map_.Add(Thread::Current(), code);
409}
410
Mark Mendellae9fd932014-02-10 16:14:35 -0800411std::vector<uint8_t>* CompilerDriver::DeduplicateCFIInfo(const std::vector<uint8_t>* cfi_info) {
412 if (cfi_info == nullptr) {
413 return nullptr;
414 }
415 return dedupe_cfi_info_.Add(Thread::Current(), *cfi_info);
416}
417
Brian Carlstrom7940e442013-07-12 13:46:57 -0700418CompilerDriver::~CompilerDriver() {
419 Thread* self = Thread::Current();
420 {
421 MutexLock mu(self, compiled_classes_lock_);
422 STLDeleteValues(&compiled_classes_);
423 }
424 {
425 MutexLock mu(self, compiled_methods_lock_);
426 STLDeleteValues(&compiled_methods_);
427 }
428 {
429 MutexLock mu(self, compiled_methods_lock_);
430 STLDeleteElements(&code_to_patch_);
431 }
432 {
433 MutexLock mu(self, compiled_methods_lock_);
434 STLDeleteElements(&methods_to_patch_);
435 }
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800436 {
437 MutexLock mu(self, compiled_methods_lock_);
438 STLDeleteElements(&classes_to_patch_);
439 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700440 CHECK_PTHREAD_CALL(pthread_key_delete, (tls_key_), "delete tls key");
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000441 compiler_->UnInit(*this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700442}
443
444CompilerTls* CompilerDriver::GetTls() {
445 // Lazily create thread-local storage
446 CompilerTls* res = static_cast<CompilerTls*>(pthread_getspecific(tls_key_));
447 if (res == NULL) {
448 res = new CompilerTls();
449 CHECK_PTHREAD_CALL(pthread_setspecific, (tls_key_, res), "compiler tls");
450 }
451 return res;
452}
453
Ian Rogersdd7624d2014-03-14 17:43:00 -0700454#define CREATE_TRAMPOLINE(type, abi, offset) \
455 if (instruction_set_is_64_bit_) { \
456 return CreateTrampoline64(instruction_set_, abi, \
457 type ## _ENTRYPOINT_OFFSET(8, offset)); \
458 } else { \
459 return CreateTrampoline32(instruction_set_, abi, \
460 type ## _ENTRYPOINT_OFFSET(4, offset)); \
461 }
462
Ian Rogers848871b2013-08-05 10:56:33 -0700463const std::vector<uint8_t>* CompilerDriver::CreateInterpreterToInterpreterBridge() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700464 CREATE_TRAMPOLINE(INTERPRETER, kInterpreterAbi, pInterpreterToInterpreterBridge)
Ian Rogers848871b2013-08-05 10:56:33 -0700465}
466
467const std::vector<uint8_t>* CompilerDriver::CreateInterpreterToCompiledCodeBridge() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700468 CREATE_TRAMPOLINE(INTERPRETER, kInterpreterAbi, pInterpreterToCompiledCodeBridge)
Ian Rogers848871b2013-08-05 10:56:33 -0700469}
470
471const std::vector<uint8_t>* CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700472 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700473}
474
Jeff Hao88474b42013-10-23 16:24:40 -0700475const std::vector<uint8_t>* CompilerDriver::CreatePortableImtConflictTrampoline() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700476 CREATE_TRAMPOLINE(PORTABLE, kPortableAbi, pPortableImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700477}
478
Brian Carlstrom7940e442013-07-12 13:46:57 -0700479const std::vector<uint8_t>* CompilerDriver::CreatePortableResolutionTrampoline() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700480 CREATE_TRAMPOLINE(PORTABLE, kPortableAbi, pPortableResolutionTrampoline)
Ian Rogers848871b2013-08-05 10:56:33 -0700481}
482
483const std::vector<uint8_t>* CompilerDriver::CreatePortableToInterpreterBridge() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700484 CREATE_TRAMPOLINE(PORTABLE, kPortableAbi, pPortableToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700485}
486
Andreas Gampe2da88232014-02-27 12:26:20 -0800487const std::vector<uint8_t>* CompilerDriver::CreateQuickGenericJniTrampoline() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700488 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800489}
490
Jeff Hao88474b42013-10-23 16:24:40 -0700491const std::vector<uint8_t>* CompilerDriver::CreateQuickImtConflictTrampoline() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700492 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700493}
494
Brian Carlstrom7940e442013-07-12 13:46:57 -0700495const std::vector<uint8_t>* CompilerDriver::CreateQuickResolutionTrampoline() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700496 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700497}
498
Ian Rogers848871b2013-08-05 10:56:33 -0700499const std::vector<uint8_t>* CompilerDriver::CreateQuickToInterpreterBridge() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700500 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700501}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700502#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700503
504void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700505 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800506 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700507 DCHECK(!Runtime::Current()->IsStarted());
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800508 UniquePtr<ThreadPool> thread_pool(new ThreadPool("Compiler driver thread pool", thread_count_ - 1));
Ian Rogers3d504072014-03-01 09:16:49 -0800509 PreCompile(class_loader, dex_files, thread_pool.get(), timings);
510 Compile(class_loader, dex_files, thread_pool.get(), timings);
Dave Allison754ddad2014-02-19 14:05:39 -0800511 PostCompile();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700512 if (dump_stats_) {
513 stats_->Dump();
514 }
515}
516
Mathieu Chartier590fee92013-09-13 13:46:47 -0700517static DexToDexCompilationLevel GetDexToDexCompilationlevel(
Ian Rogers98379392014-02-24 16:53:16 -0800518 Thread* self, SirtRef<mirror::ClassLoader>& class_loader, const DexFile& dex_file,
Mathieu Chartier590fee92013-09-13 13:46:47 -0700519 const DexFile::ClassDef& class_def) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700520 const char* descriptor = dex_file.GetClassDescriptor(class_def);
521 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800522 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700523 if (klass == NULL) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700524 CHECK(self->IsExceptionPending());
525 self->ClearException();
Sebastien Hertz75021222013-07-16 18:34:50 +0200526 return kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700527 }
Sebastien Hertz75021222013-07-16 18:34:50 +0200528 // The verifier can only run on "quick" instructions at runtime (see usage of
529 // FindAccessedFieldAtDexPc and FindInvokedMethodAtDexPc in ThrowNullPointerExceptionFromDexPC
530 // function). Since image classes can be verified again while compiling an application,
531 // we must prevent the DEX-to-DEX compiler from introducing them.
532 // TODO: find a way to enable "quick" instructions for image classes and remove this check.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700533 bool compiling_image_classes = class_loader.get() == nullptr;
Sebastien Hertz75021222013-07-16 18:34:50 +0200534 if (compiling_image_classes) {
535 return kRequired;
536 } else if (klass->IsVerified()) {
537 // Class is verified so we can enable DEX-to-DEX compilation for performance.
538 return kOptimize;
539 } else if (klass->IsCompileTimeVerified()) {
540 // Class verification has soft-failed. Anyway, ensure at least correctness.
541 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
542 return kRequired;
543 } else {
544 // Class verification has failed: do not run DEX-to-DEX compilation.
545 return kDontDexToDexCompile;
546 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700547}
548
Ian Rogers3d504072014-03-01 09:16:49 -0800549void CompilerDriver::CompileOne(mirror::ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700550 DCHECK(!Runtime::Current()->IsStarted());
551 Thread* self = Thread::Current();
552 jobject jclass_loader;
553 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700554 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800555 uint32_t method_idx = method->GetDexMethodIndex();
556 uint32_t access_flags = method->GetAccessFlags();
557 InvokeType invoke_type = method->GetInvokeType();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700558 {
559 ScopedObjectAccessUnchecked soa(self);
560 ScopedLocalRef<jobject>
561 local_class_loader(soa.Env(),
562 soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
563 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
564 // Find the dex_file
565 MethodHelper mh(method);
566 dex_file = &mh.GetDexFile();
567 class_def_idx = mh.GetClassDefIndex();
568 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800569 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700570 self->TransitionFromRunnableToSuspended(kNative);
571
572 std::vector<const DexFile*> dex_files;
573 dex_files.push_back(dex_file);
574
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800575 UniquePtr<ThreadPool> thread_pool(new ThreadPool("Compiler driver thread pool", 0U));
Ian Rogers3d504072014-03-01 09:16:49 -0800576 PreCompile(jclass_loader, dex_files, thread_pool.get(), timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700577
Brian Carlstrom7940e442013-07-12 13:46:57 -0700578 // Can we run DEX-to-DEX compiler on this class ?
Sebastien Hertz75021222013-07-16 18:34:50 +0200579 DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700580 {
581 ScopedObjectAccess soa(Thread::Current());
582 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700583 SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
584 soa.Decode<mirror::ClassLoader*>(jclass_loader));
Ian Rogers98379392014-02-24 16:53:16 -0800585 dex_to_dex_compilation_level = GetDexToDexCompilationlevel(self, class_loader, *dex_file,
586 class_def);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700587 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800588 CompileMethod(code_item, access_flags, invoke_type, class_def_idx, method_idx, jclass_loader,
589 *dex_file, dex_to_dex_compilation_level);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700590
591 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
592
593 self->TransitionFromSuspendedToRunnable();
594}
595
596void CompilerDriver::Resolve(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800597 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700598 for (size_t i = 0; i != dex_files.size(); ++i) {
599 const DexFile* dex_file = dex_files[i];
600 CHECK(dex_file != NULL);
601 ResolveDexFile(class_loader, *dex_file, thread_pool, timings);
602 }
603}
604
605void CompilerDriver::PreCompile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800606 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700607 LoadImageClasses(timings);
608
Jeff Hao4a200f52014-04-01 14:58:49 -0700609 if (!compiler_options_->IsVerificationEnabled()) {
610 VLOG(compiler) << "Verify none mode specified, skipping pre-compilation";
611 return;
612 }
613
Brian Carlstrom7940e442013-07-12 13:46:57 -0700614 Resolve(class_loader, dex_files, thread_pool, timings);
615
616 Verify(class_loader, dex_files, thread_pool, timings);
617
618 InitializeClasses(class_loader, dex_files, thread_pool, timings);
619
620 UpdateImageClasses(timings);
621}
622
Dave Allison754ddad2014-02-19 14:05:39 -0800623void CompilerDriver::PostCompile() {
624 BuildEntrypointTrampolineCode();
625}
626
Ian Rogersdfb325e2013-10-30 01:00:44 -0700627bool CompilerDriver::IsImageClass(const char* descriptor) const {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700628 if (!IsImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700629 return true;
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700630 } else {
Ian Rogersdfb325e2013-10-30 01:00:44 -0700631 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700632 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700633}
634
635static void ResolveExceptionsForMethod(MethodHelper* mh,
636 std::set<std::pair<uint16_t, const DexFile*> >& exceptions_to_resolve)
637 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
638 const DexFile::CodeItem* code_item = mh->GetCodeItem();
639 if (code_item == NULL) {
640 return; // native or abstract method
641 }
642 if (code_item->tries_size_ == 0) {
643 return; // nothing to process
644 }
645 const byte* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
646 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
647 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
648 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
649 bool has_catch_all = false;
650 if (encoded_catch_handler_size <= 0) {
651 encoded_catch_handler_size = -encoded_catch_handler_size;
652 has_catch_all = true;
653 }
654 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
655 uint16_t encoded_catch_handler_handlers_type_idx =
656 DecodeUnsignedLeb128(&encoded_catch_handler_list);
657 // Add to set of types to resolve if not already in the dex cache resolved types
658 if (!mh->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
659 exceptions_to_resolve.insert(
660 std::pair<uint16_t, const DexFile*>(encoded_catch_handler_handlers_type_idx,
661 &mh->GetDexFile()));
662 }
663 // ignore address associated with catch handler
664 DecodeUnsignedLeb128(&encoded_catch_handler_list);
665 }
666 if (has_catch_all) {
667 // ignore catch all address
668 DecodeUnsignedLeb128(&encoded_catch_handler_list);
669 }
670 }
671}
672
673static bool ResolveCatchBlockExceptionsClassVisitor(mirror::Class* c, void* arg)
674 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
675 std::set<std::pair<uint16_t, const DexFile*> >* exceptions_to_resolve =
676 reinterpret_cast<std::set<std::pair<uint16_t, const DexFile*> >*>(arg);
677 MethodHelper mh;
678 for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700679 mirror::ArtMethod* m = c->GetVirtualMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700680 mh.ChangeMethod(m);
681 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
682 }
683 for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700684 mirror::ArtMethod* m = c->GetDirectMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700685 mh.ChangeMethod(m);
686 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
687 }
688 return true;
689}
690
691static bool RecordImageClassesVisitor(mirror::Class* klass, void* arg)
692 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
693 CompilerDriver::DescriptorSet* image_classes =
694 reinterpret_cast<CompilerDriver::DescriptorSet*>(arg);
695 image_classes->insert(ClassHelper(klass).GetDescriptor());
696 return true;
697}
698
699// Make a list of descriptors for classes to include in the image
Ian Rogers3d504072014-03-01 09:16:49 -0800700void CompilerDriver::LoadImageClasses(TimingLogger* timings)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700701 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700702 if (!IsImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700703 return;
704 }
705
Ian Rogers3d504072014-03-01 09:16:49 -0800706 timings->NewSplit("LoadImageClasses");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700707 // Make a first class to load all classes explicitly listed in the file
708 Thread* self = Thread::Current();
709 ScopedObjectAccess soa(self);
710 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700711 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000712 const std::string& descriptor(*it);
Ian Rogers98379392014-02-24 16:53:16 -0800713 SirtRef<mirror::Class> klass(self, class_linker->FindSystemClass(self, descriptor.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700714 if (klass.get() == NULL) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700715 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000716 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -0700717 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700718 } else {
719 ++it;
720 }
721 }
722
723 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
724 // exceptions are resolved by the verifier when there is a catch block in an interested method.
725 // Do this here so that exception classes appear to have been specified image classes.
726 std::set<std::pair<uint16_t, const DexFile*> > unresolved_exception_types;
727 SirtRef<mirror::Class> java_lang_Throwable(self,
Ian Rogers98379392014-02-24 16:53:16 -0800728 class_linker->FindSystemClass(self, "Ljava/lang/Throwable;"));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700729 do {
730 unresolved_exception_types.clear();
731 class_linker->VisitClasses(ResolveCatchBlockExceptionsClassVisitor,
732 &unresolved_exception_types);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700733 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
734 uint16_t exception_type_idx = exception_type.first;
735 const DexFile* dex_file = exception_type.second;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700736 SirtRef<mirror::DexCache> dex_cache(self, class_linker->FindDexCache(*dex_file));
737 SirtRef<mirror::ClassLoader> class_loader(self, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700738 SirtRef<mirror::Class> klass(self, class_linker->ResolveType(*dex_file, exception_type_idx,
739 dex_cache, class_loader));
740 if (klass.get() == NULL) {
741 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
742 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
743 LOG(FATAL) << "Failed to resolve class " << descriptor;
744 }
745 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.get()));
746 }
747 // Resolving exceptions may load classes that reference more exceptions, iterate until no
748 // more are found
749 } while (!unresolved_exception_types.empty());
750
751 // We walk the roots looking for classes so that we'll pick up the
752 // above classes plus any classes them depend on such super
753 // classes, interfaces, and the required ClassLinker roots.
754 class_linker->VisitClasses(RecordImageClassesVisitor, image_classes_.get());
755
756 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700757}
758
759static void MaybeAddToImageClasses(mirror::Class* klass, CompilerDriver::DescriptorSet* image_classes)
760 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
761 while (!klass->IsObjectClass()) {
762 ClassHelper kh(klass);
763 const char* descriptor = kh.GetDescriptor();
764 std::pair<CompilerDriver::DescriptorSet::iterator, bool> result =
765 image_classes->insert(descriptor);
766 if (result.second) {
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700767 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700768 } else {
769 return;
770 }
771 for (size_t i = 0; i < kh.NumDirectInterfaces(); ++i) {
772 MaybeAddToImageClasses(kh.GetDirectInterface(i), image_classes);
773 }
774 if (klass->IsArrayClass()) {
775 MaybeAddToImageClasses(klass->GetComponentType(), image_classes);
776 }
777 klass = klass->GetSuperClass();
778 }
779}
780
781void CompilerDriver::FindClinitImageClassesCallback(mirror::Object* object, void* arg) {
782 DCHECK(object != NULL);
783 DCHECK(arg != NULL);
784 CompilerDriver* compiler_driver = reinterpret_cast<CompilerDriver*>(arg);
785 MaybeAddToImageClasses(object->GetClass(), compiler_driver->image_classes_.get());
786}
787
Ian Rogers3d504072014-03-01 09:16:49 -0800788void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700789 if (IsImage()) {
Ian Rogers3d504072014-03-01 09:16:49 -0800790 timings->NewSplit("UpdateImageClasses");
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700791
792 // Update image_classes_ with classes for objects created by <clinit> methods.
793 Thread* self = Thread::Current();
794 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
795 gc::Heap* heap = Runtime::Current()->GetHeap();
796 // TODO: Image spaces only?
Mathieu Chartier590fee92013-09-13 13:46:47 -0700797 ScopedObjectAccess soa(Thread::Current());
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700798 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700799 heap->VisitObjects(FindClinitImageClassesCallback, this);
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700800 self->EndAssertNoThreadSuspension(old_cause);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700801 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700802}
803
Mathieu Chartier590fee92013-09-13 13:46:47 -0700804bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(const DexFile& dex_file, uint32_t type_idx) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700805 if (IsImage() &&
Ian Rogersdfb325e2013-10-30 01:00:44 -0700806 IsImageClass(dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_))) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700807 if (kIsDebugBuild) {
808 ScopedObjectAccess soa(Thread::Current());
809 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
810 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
811 CHECK(resolved_class != NULL);
812 }
813 stats_->TypeInDexCache();
814 return true;
815 } else {
816 stats_->TypeNotInDexCache();
817 return false;
818 }
819}
820
821bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
822 uint32_t string_idx) {
823 // See also Compiler::ResolveDexFile
824
825 bool result = false;
826 if (IsImage()) {
827 // We resolve all const-string strings when building for the image.
828 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700829 SirtRef<mirror::DexCache> dex_cache(soa.Self(), Runtime::Current()->GetClassLinker()->FindDexCache(dex_file));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700830 Runtime::Current()->GetClassLinker()->ResolveString(dex_file, string_idx, dex_cache);
831 result = true;
832 }
833 if (result) {
834 stats_->StringInDexCache();
835 } else {
836 stats_->StringNotInDexCache();
837 }
838 return result;
839}
840
841bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
842 uint32_t type_idx,
843 bool* type_known_final, bool* type_known_abstract,
844 bool* equals_referrers_class) {
845 if (type_known_final != NULL) {
846 *type_known_final = false;
847 }
848 if (type_known_abstract != NULL) {
849 *type_known_abstract = false;
850 }
851 if (equals_referrers_class != NULL) {
852 *equals_referrers_class = false;
853 }
854 ScopedObjectAccess soa(Thread::Current());
855 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
856 // Get type from dex cache assuming it was populated by the verifier
857 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
858 if (resolved_class == NULL) {
859 stats_->TypeNeedsAccessCheck();
860 return false; // Unknown class needs access checks.
861 }
862 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
863 if (equals_referrers_class != NULL) {
864 *equals_referrers_class = (method_id.class_idx_ == type_idx);
865 }
866 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
867 if (referrer_class == NULL) {
868 stats_->TypeNeedsAccessCheck();
869 return false; // Incomplete referrer knowledge needs access check.
870 }
871 // Perform access check, will return true if access is ok or false if we're going to have to
872 // check this at runtime (for example for class loaders).
873 bool result = referrer_class->CanAccess(resolved_class);
874 if (result) {
875 stats_->TypeDoesntNeedAccessCheck();
876 if (type_known_final != NULL) {
877 *type_known_final = resolved_class->IsFinal() && !resolved_class->IsArrayClass();
878 }
879 if (type_known_abstract != NULL) {
880 *type_known_abstract = resolved_class->IsAbstract() && !resolved_class->IsArrayClass();
881 }
882 } else {
883 stats_->TypeNeedsAccessCheck();
884 }
885 return result;
886}
887
888bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
889 const DexFile& dex_file,
890 uint32_t type_idx) {
891 ScopedObjectAccess soa(Thread::Current());
892 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
893 // Get type from dex cache assuming it was populated by the verifier.
894 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
895 if (resolved_class == NULL) {
896 stats_->TypeNeedsAccessCheck();
897 return false; // Unknown class needs access checks.
898 }
899 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
900 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
901 if (referrer_class == NULL) {
902 stats_->TypeNeedsAccessCheck();
903 return false; // Incomplete referrer knowledge needs access check.
904 }
905 // Perform access and instantiable checks, will return true if access is ok or false if we're
906 // going to have to check this at runtime (for example for class loaders).
907 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
908 if (result) {
909 stats_->TypeDoesntNeedAccessCheck();
910 } else {
911 stats_->TypeNeedsAccessCheck();
912 }
913 return result;
914}
915
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800916bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
917 bool* is_type_initialized, bool* use_direct_type_ptr,
918 uintptr_t* direct_type_ptr) {
919 ScopedObjectAccess soa(Thread::Current());
920 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
921 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
922 if (resolved_class == nullptr) {
923 return false;
924 }
925 const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
926 if (compiling_boot) {
927 // boot -> boot class pointers.
928 // True if the class is in the image at boot compiling time.
929 const bool is_image_class = IsImage() && IsImageClass(
930 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
931 // True if pc relative load works.
932 const bool support_boot_image_fixup = GetSupportBootImageFixup();
933 if (is_image_class && support_boot_image_fixup) {
934 *is_type_initialized = resolved_class->IsInitialized();
935 *use_direct_type_ptr = false;
936 *direct_type_ptr = 0;
937 return true;
938 } else {
939 return false;
940 }
941 } else {
942 // True if the class is in the image at app compiling time.
943 const bool class_in_image =
944 Runtime::Current()->GetHeap()->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
945 if (class_in_image) {
946 // boot -> app class pointers.
947 *is_type_initialized = resolved_class->IsInitialized();
948 *use_direct_type_ptr = true;
949 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
950 return true;
951 } else {
952 // app -> app class pointers.
953 // Give up because app does not have an image and class
954 // isn't created at compile time. TODO: implement this
955 // if/when each app gets an image.
956 return false;
957 }
958 }
959}
960
Vladimir Markobe0e5462014-02-26 11:24:15 +0000961void CompilerDriver::ProcessedInstanceField(bool resolved) {
962 if (!resolved) {
963 stats_->UnresolvedInstanceField();
964 } else {
965 stats_->ResolvedInstanceField();
966 }
967}
968
969void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
970 if (!resolved) {
971 stats_->UnresolvedStaticField();
972 } else if (local) {
973 stats_->ResolvedLocalStaticField();
974 } else {
975 stats_->ResolvedStaticField();
976 }
977}
978
Vladimir Markof096aad2014-01-23 15:51:58 +0000979void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
980 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700981}
982
983bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
Vladimir Markobe0e5462014-02-26 11:24:15 +0000984 bool is_put, MemberOffset* field_offset,
985 bool* is_volatile) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700986 ScopedObjectAccess soa(Thread::Current());
Vladimir Markobe0e5462014-02-26 11:24:15 +0000987 // Try to resolve the field and compiling method's class.
988 mirror::ArtField* resolved_field;
989 mirror::Class* referrer_class;
990 mirror::DexCache* dex_cache;
991 {
992 SirtRef<mirror::DexCache> dex_cache_sirt(soa.Self(),
993 mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
994 SirtRef<mirror::ClassLoader> class_loader_sirt(soa.Self(),
995 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
996 SirtRef<mirror::ArtField> resolved_field_sirt(soa.Self(),
997 ResolveField(soa, dex_cache_sirt, class_loader_sirt, mUnit, field_idx, false));
998 referrer_class = (resolved_field_sirt.get() != nullptr)
999 ? ResolveCompilingMethodsClass(soa, dex_cache_sirt, class_loader_sirt, mUnit) : nullptr;
1000 resolved_field = resolved_field_sirt.get();
1001 dex_cache = dex_cache_sirt.get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001002 }
Vladimir Markobe0e5462014-02-26 11:24:15 +00001003 bool result = false;
1004 if (resolved_field != nullptr && referrer_class != nullptr) {
1005 *is_volatile = IsFieldVolatile(resolved_field);
1006 std::pair<bool, bool> fast_path = IsFastInstanceField(
1007 dex_cache, referrer_class, resolved_field, field_idx, field_offset);
1008 result = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001009 }
Vladimir Markobe0e5462014-02-26 11:24:15 +00001010 if (!result) {
1011 // Conservative defaults.
1012 *is_volatile = true;
1013 *field_offset = MemberOffset(static_cast<size_t>(-1));
1014 }
1015 ProcessedInstanceField(result);
1016 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001017}
1018
1019bool CompilerDriver::ComputeStaticFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
Vladimir Markobe0e5462014-02-26 11:24:15 +00001020 bool is_put, MemberOffset* field_offset,
1021 uint32_t* storage_index, bool* is_referrers_class,
1022 bool* is_volatile, bool* is_initialized) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001023 ScopedObjectAccess soa(Thread::Current());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001024 // Try to resolve the field and compiling method's class.
1025 mirror::ArtField* resolved_field;
1026 mirror::Class* referrer_class;
1027 mirror::DexCache* dex_cache;
1028 {
1029 SirtRef<mirror::DexCache> dex_cache_sirt(soa.Self(),
1030 mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
1031 SirtRef<mirror::ClassLoader> class_loader_sirt(soa.Self(),
1032 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
1033 SirtRef<mirror::ArtField> resolved_field_sirt(soa.Self(),
1034 ResolveField(soa, dex_cache_sirt, class_loader_sirt, mUnit, field_idx, true));
1035 referrer_class = (resolved_field_sirt.get() != nullptr)
1036 ? ResolveCompilingMethodsClass(soa, dex_cache_sirt, class_loader_sirt, mUnit) : nullptr;
1037 resolved_field = resolved_field_sirt.get();
1038 dex_cache = dex_cache_sirt.get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001039 }
Vladimir Markobe0e5462014-02-26 11:24:15 +00001040 bool result = false;
1041 if (resolved_field != nullptr && referrer_class != nullptr) {
1042 *is_volatile = IsFieldVolatile(resolved_field);
1043 std::pair<bool, bool> fast_path = IsFastStaticField(
1044 dex_cache, referrer_class, resolved_field, field_idx, field_offset,
1045 storage_index, is_referrers_class, is_initialized);
1046 result = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001047 }
Vladimir Markobe0e5462014-02-26 11:24:15 +00001048 if (!result) {
1049 // Conservative defaults.
1050 *is_volatile = true;
1051 *field_offset = MemberOffset(static_cast<size_t>(-1));
1052 *storage_index = -1;
1053 *is_referrers_class = false;
1054 *is_initialized = false;
1055 }
1056 ProcessedStaticField(result, *is_referrers_class);
1057 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001058}
1059
Ian Rogers83883d72013-10-21 21:07:24 -07001060void CompilerDriver::GetCodeAndMethodForDirectCall(InvokeType* type, InvokeType sharp_type,
1061 bool no_guarantee_of_dex_cache_entry,
Brian Carlstrom7940e442013-07-12 13:46:57 -07001062 mirror::Class* referrer_class,
Brian Carlstromea46f952013-07-30 01:26:50 -07001063 mirror::ArtMethod* method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001064 int* stats_flags,
Ian Rogers83883d72013-10-21 21:07:24 -07001065 MethodReference* target_method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001066 uintptr_t* direct_code,
1067 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001068 // For direct and static methods compute possible direct_code and direct_method values, ie
1069 // an address for the Method* being invoked and an address of the code for that Method*.
1070 // For interface calls compute a value for direct_method that is the interface method being
1071 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001072 *direct_code = 0;
1073 *direct_method = 0;
Ian Rogers83883d72013-10-21 21:07:24 -07001074 bool use_dex_cache = false;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001075 const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001076 if (compiler_->IsPortable()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001077 if (sharp_type != kStatic && sharp_type != kDirect) {
1078 return;
1079 }
Ian Rogers83883d72013-10-21 21:07:24 -07001080 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001081 } else {
Jeff Hao88474b42013-10-23 16:24:40 -07001082 if (sharp_type != kStatic && sharp_type != kDirect) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001083 return;
1084 }
Ian Rogers83883d72013-10-21 21:07:24 -07001085 // TODO: support patching on all architectures.
1086 use_dex_cache = compiling_boot && !support_boot_image_fixup_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001087 }
Ian Rogers83883d72013-10-21 21:07:24 -07001088 bool method_code_in_boot = (method->GetDeclaringClass()->GetClassLoader() == nullptr);
1089 if (!use_dex_cache) {
1090 if (!method_code_in_boot) {
1091 use_dex_cache = true;
1092 } else {
1093 bool has_clinit_trampoline =
1094 method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
1095 if (has_clinit_trampoline && (method->GetDeclaringClass() != referrer_class)) {
1096 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1097 // class.
1098 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001099 }
1100 }
Ian Rogers83883d72013-10-21 21:07:24 -07001101 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001102 if (method_code_in_boot) {
1103 *stats_flags |= kFlagDirectCallToBoot | kFlagDirectMethodToBoot;
Ian Rogers83883d72013-10-21 21:07:24 -07001104 }
1105 if (!use_dex_cache && compiling_boot) {
1106 MethodHelper mh(method);
Ian Rogersdfb325e2013-10-30 01:00:44 -07001107 if (!IsImageClass(mh.GetDeclaringClassDescriptor())) {
Ian Rogers83883d72013-10-21 21:07:24 -07001108 // We can only branch directly to Methods that are resolved in the DexCache.
1109 // Otherwise we won't invoke the resolution trampoline.
1110 use_dex_cache = true;
1111 }
1112 }
1113 // The method is defined not within this dex file. We need a dex cache slot within the current
1114 // dex file or direct pointers.
1115 bool must_use_direct_pointers = false;
1116 if (target_method->dex_file == method->GetDeclaringClass()->GetDexCache()->GetDexFile()) {
1117 target_method->dex_method_index = method->GetDexMethodIndex();
1118 } else {
Ian Rogers83883d72013-10-21 21:07:24 -07001119 if (no_guarantee_of_dex_cache_entry) {
1120 // See if the method is also declared in this dex cache.
1121 uint32_t dex_method_idx = MethodHelper(method).FindDexMethodIndexInOtherDexFile(
Vladimir Markobbcc0c02014-02-03 14:08:42 +00001122 *target_method->dex_file, target_method->dex_method_index);
Ian Rogers83883d72013-10-21 21:07:24 -07001123 if (dex_method_idx != DexFile::kDexNoIndex) {
1124 target_method->dex_method_index = dex_method_idx;
1125 } else {
Jeff Hao49161ce2014-03-12 11:05:25 -07001126 if (compiling_boot) {
1127 target_method->dex_method_index = method->GetDexMethodIndex();
1128 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1129 }
Ian Rogers83883d72013-10-21 21:07:24 -07001130 must_use_direct_pointers = true;
1131 }
1132 }
1133 }
1134 if (use_dex_cache) {
1135 if (must_use_direct_pointers) {
1136 // Fail. Test above showed the only safe dispatch was via the dex cache, however, the direct
1137 // pointers are required as the dex cache lacks an appropriate entry.
1138 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1139 } else {
1140 *type = sharp_type;
1141 }
1142 } else {
1143 if (compiling_boot) {
1144 *type = sharp_type;
1145 *direct_method = -1;
Jeff Hao88474b42013-10-23 16:24:40 -07001146 *direct_code = -1;
Ian Rogers83883d72013-10-21 21:07:24 -07001147 } else {
1148 bool method_in_image =
1149 Runtime::Current()->GetHeap()->FindSpaceFromObject(method, false)->IsImageSpace();
1150 if (method_in_image) {
Jeff Hao88474b42013-10-23 16:24:40 -07001151 CHECK(!method->IsAbstract());
Ian Rogers83883d72013-10-21 21:07:24 -07001152 *type = sharp_type;
1153 *direct_method = reinterpret_cast<uintptr_t>(method);
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001154 *direct_code = compiler_->GetEntryPointOf(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001155 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1156 target_method->dex_method_index = method->GetDexMethodIndex();
1157 } else if (!must_use_direct_pointers) {
1158 // Set the code and rely on the dex cache for the method.
1159 *type = sharp_type;
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001160 *direct_code = compiler_->GetEntryPointOf(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001161 } else {
1162 // Direct pointers were required but none were available.
1163 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1164 }
1165 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001166 }
1167}
1168
1169bool CompilerDriver::ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001170 bool update_stats, bool enable_devirtualization,
1171 InvokeType* invoke_type, MethodReference* target_method,
1172 int* vtable_idx, uintptr_t* direct_code,
1173 uintptr_t* direct_method) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001174 InvokeType orig_invoke_type = *invoke_type;
1175 int stats_flags = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001176 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof096aad2014-01-23 15:51:58 +00001177 // Try to resolve the method and compiling method's class.
1178 mirror::ArtMethod* resolved_method;
1179 mirror::Class* referrer_class;
1180 SirtRef<mirror::DexCache> dex_cache(soa.Self(),
1181 mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
1182 SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
1183 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
1184 {
1185 uint32_t method_idx = target_method->dex_method_index;
1186 SirtRef<mirror::ArtMethod> resolved_method_sirt(soa.Self(),
1187 ResolveMethod(soa, dex_cache, class_loader, mUnit, method_idx, orig_invoke_type));
1188 referrer_class = (resolved_method_sirt.get() != nullptr)
1189 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr;
1190 resolved_method = resolved_method_sirt.get();
1191 }
1192 bool result = false;
1193 if (resolved_method != nullptr) {
1194 *vtable_idx = GetResolvedMethodVTableIndex(resolved_method, orig_invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001195
Vladimir Markof096aad2014-01-23 15:51:58 +00001196 if (enable_devirtualization) {
1197 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1198 const MethodReference* devirt_target = mUnit->GetVerifiedMethod()->GetDevirtTarget(dex_pc);
1199
1200 stats_flags = IsFastInvoke(
1201 soa, dex_cache, class_loader, mUnit, referrer_class, resolved_method,
1202 invoke_type, target_method, devirt_target, direct_code, direct_method);
1203 result = stats_flags != 0;
1204 } else {
1205 // Devirtualization not enabled. Inline IsFastInvoke(), dropping the devirtualization parts.
1206 if (UNLIKELY(referrer_class == nullptr) ||
1207 UNLIKELY(!referrer_class->CanAccessResolvedMethod(resolved_method->GetDeclaringClass(),
1208 resolved_method, dex_cache.get(),
1209 target_method->dex_method_index)) ||
1210 *invoke_type == kSuper) {
1211 // Slow path. (Without devirtualization, all super calls go slow path as well.)
1212 } else {
1213 // Sharpening failed so generate a regular resolved method dispatch.
1214 stats_flags = kFlagMethodResolved;
1215 GetCodeAndMethodForDirectCall(invoke_type, *invoke_type, false, referrer_class, resolved_method,
1216 &stats_flags, target_method, direct_code, direct_method);
1217 result = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001218 }
1219 }
1220 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001221 if (!result) {
1222 // Conservative defaults.
1223 *vtable_idx = -1;
1224 *direct_code = 0u;
1225 *direct_method = 0u;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001226 }
1227 if (update_stats) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001228 ProcessedInvoke(orig_invoke_type, stats_flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001229 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001230 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001231}
1232
Vladimir Marko2730db02014-01-27 11:15:17 +00001233const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1234 uint32_t method_idx) const {
1235 MethodReference ref(dex_file, method_idx);
1236 return verification_results_->GetVerifiedMethod(ref);
1237}
1238
1239bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
1240 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1241 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001242 if (result) {
1243 stats_->SafeCast();
1244 } else {
1245 stats_->NotASafeCast();
1246 }
1247 return result;
1248}
1249
Dave Allison754ddad2014-02-19 14:05:39 -08001250uint32_t CompilerDriver::AddEntrypointTrampoline(uint32_t entrypoint) {
1251 return entrypoint_trampolines_.AddEntrypoint(Thread::Current(), entrypoint);
1252}
1253
1254
1255void CompilerDriver::BuildEntrypointTrampolineCode() {
1256 const auto& table = entrypoint_trampolines_.GetTrampolineTable();
1257 for (uint32_t offset : table) {
1258 switch (instruction_set_) {
1259 case kThumb2:
1260 BuildArmEntrypointTrampolineCall(ThreadOffset<4>(offset));
1261 break;
1262 default:
1263 UNIMPLEMENTED(FATAL) << "No entrypoint trampolines for this architecture";
1264 }
1265 }
1266}
1267
1268
Brian Carlstrom7940e442013-07-12 13:46:57 -07001269void CompilerDriver::AddCodePatch(const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001270 uint16_t referrer_class_def_idx,
1271 uint32_t referrer_method_idx,
1272 InvokeType referrer_invoke_type,
1273 uint32_t target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001274 const DexFile* target_dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001275 InvokeType target_invoke_type,
1276 size_t literal_offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001277 MutexLock mu(Thread::Current(), compiled_methods_lock_);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001278 code_to_patch_.push_back(new CallPatchInformation(dex_file,
1279 referrer_class_def_idx,
1280 referrer_method_idx,
1281 referrer_invoke_type,
1282 target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001283 target_dex_file,
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001284 target_invoke_type,
1285 literal_offset));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001286}
Mark Mendell55d0eac2014-02-06 11:02:52 -08001287void CompilerDriver::AddRelativeCodePatch(const DexFile* dex_file,
1288 uint16_t referrer_class_def_idx,
1289 uint32_t referrer_method_idx,
1290 InvokeType referrer_invoke_type,
1291 uint32_t target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001292 const DexFile* target_dex_file,
Mark Mendell55d0eac2014-02-06 11:02:52 -08001293 InvokeType target_invoke_type,
1294 size_t literal_offset,
1295 int32_t pc_relative_offset) {
1296 MutexLock mu(Thread::Current(), compiled_methods_lock_);
1297 code_to_patch_.push_back(new RelativeCallPatchInformation(dex_file,
1298 referrer_class_def_idx,
1299 referrer_method_idx,
1300 referrer_invoke_type,
1301 target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001302 target_dex_file,
Mark Mendell55d0eac2014-02-06 11:02:52 -08001303 target_invoke_type,
1304 literal_offset,
1305 pc_relative_offset));
1306}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001307void CompilerDriver::AddMethodPatch(const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001308 uint16_t referrer_class_def_idx,
1309 uint32_t referrer_method_idx,
1310 InvokeType referrer_invoke_type,
1311 uint32_t target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001312 const DexFile* target_dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001313 InvokeType target_invoke_type,
1314 size_t literal_offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001315 MutexLock mu(Thread::Current(), compiled_methods_lock_);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001316 methods_to_patch_.push_back(new CallPatchInformation(dex_file,
1317 referrer_class_def_idx,
1318 referrer_method_idx,
1319 referrer_invoke_type,
1320 target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001321 target_dex_file,
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001322 target_invoke_type,
1323 literal_offset));
1324}
1325void CompilerDriver::AddClassPatch(const DexFile* dex_file,
1326 uint16_t referrer_class_def_idx,
1327 uint32_t referrer_method_idx,
1328 uint32_t target_type_idx,
1329 size_t literal_offset) {
1330 MutexLock mu(Thread::Current(), compiled_methods_lock_);
1331 classes_to_patch_.push_back(new TypePatchInformation(dex_file,
1332 referrer_class_def_idx,
1333 referrer_method_idx,
1334 target_type_idx,
1335 literal_offset));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001336}
1337
1338class ParallelCompilationManager {
1339 public:
1340 typedef void Callback(const ParallelCompilationManager* manager, size_t index);
1341
1342 ParallelCompilationManager(ClassLinker* class_linker,
1343 jobject class_loader,
1344 CompilerDriver* compiler,
1345 const DexFile* dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001346 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001347 : index_(0),
1348 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001349 class_loader_(class_loader),
1350 compiler_(compiler),
1351 dex_file_(dex_file),
Ian Rogers3d504072014-03-01 09:16:49 -08001352 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001353
1354 ClassLinker* GetClassLinker() const {
1355 CHECK(class_linker_ != NULL);
1356 return class_linker_;
1357 }
1358
1359 jobject GetClassLoader() const {
1360 return class_loader_;
1361 }
1362
1363 CompilerDriver* GetCompiler() const {
1364 CHECK(compiler_ != NULL);
1365 return compiler_;
1366 }
1367
1368 const DexFile* GetDexFile() const {
1369 CHECK(dex_file_ != NULL);
1370 return dex_file_;
1371 }
1372
1373 void ForAll(size_t begin, size_t end, Callback callback, size_t work_units) {
1374 Thread* self = Thread::Current();
1375 self->AssertNoPendingException();
1376 CHECK_GT(work_units, 0U);
1377
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001378 index_ = begin;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001379 for (size_t i = 0; i < work_units; ++i) {
Sebastien Hertz501baec2013-12-13 12:02:36 +01001380 thread_pool_->AddTask(self, new ForAllClosure(this, end, callback));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001381 }
1382 thread_pool_->StartWorkers(self);
1383
1384 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1385 // thread destructor's called below perform join).
1386 CHECK_NE(self->GetState(), kRunnable);
1387
1388 // Wait for all the worker threads to finish.
1389 thread_pool_->Wait(self, true, false);
1390 }
1391
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001392 size_t NextIndex() {
Ian Rogersb122a4b2013-11-19 18:00:50 -08001393 return index_.FetchAndAdd(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001394 }
1395
Brian Carlstrom7940e442013-07-12 13:46:57 -07001396 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001397 class ForAllClosure : public Task {
1398 public:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001399 ForAllClosure(ParallelCompilationManager* manager, size_t end, Callback* callback)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001400 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001401 end_(end),
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001402 callback_(callback) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001403
1404 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001405 while (true) {
1406 const size_t index = manager_->NextIndex();
1407 if (UNLIKELY(index >= end_)) {
1408 break;
1409 }
1410 callback_(manager_, index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001411 self->AssertNoPendingException();
1412 }
1413 }
1414
1415 virtual void Finalize() {
1416 delete this;
1417 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001418
Brian Carlstrom7940e442013-07-12 13:46:57 -07001419 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001420 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001421 const size_t end_;
Bernhard Rosenkränzer46053622013-12-12 02:15:52 +01001422 Callback* const callback_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001423 };
1424
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001425 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001426 ClassLinker* const class_linker_;
1427 const jobject class_loader_;
1428 CompilerDriver* const compiler_;
1429 const DexFile* const dex_file_;
1430 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001431
1432 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001433};
1434
Jeff Hao0e49b422013-11-08 12:16:56 -08001435// Return true if the class should be skipped during compilation.
1436//
1437// The first case where we skip is for redundant class definitions in
1438// the boot classpath. We skip all but the first definition in that case.
1439//
1440// The second case where we skip is when an app bundles classes found
1441// in the boot classpath. Since at runtime we will select the class from
1442// the boot classpath, we ignore the one from the app.
Ian Rogersbe7149f2013-08-20 09:29:39 -07001443static bool SkipClass(ClassLinker* class_linker, jobject class_loader, const DexFile& dex_file,
1444 const DexFile::ClassDef& class_def) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001445 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001446 if (class_loader == NULL) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001447 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_linker->GetBootClassPath());
1448 CHECK(pair.second != NULL);
1449 if (pair.first != &dex_file) {
1450 LOG(WARNING) << "Skipping class " << descriptor << " from " << dex_file.GetLocation()
1451 << " previously found in " << pair.first->GetLocation();
1452 return true;
1453 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001454 return false;
1455 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07001456 return class_linker->IsInBootClassPath(descriptor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001457}
1458
Jeff Hao0e49b422013-11-08 12:16:56 -08001459// A fast version of SkipClass above if the class pointer is available
1460// that avoids the expensive FindInClassPath search.
1461static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
1462 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1463 DCHECK(klass != NULL);
1464 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1465 if (&dex_file != &original_dex_file) {
1466 if (class_loader == NULL) {
1467 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1468 << dex_file.GetLocation() << " previously found in "
1469 << original_dex_file.GetLocation();
1470 }
1471 return true;
1472 }
1473 return false;
1474}
1475
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001476static void ResolveClassFieldsAndMethods(const ParallelCompilationManager* manager,
1477 size_t class_def_index)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001478 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001479 ATRACE_CALL();
Ian Rogersbe7149f2013-08-20 09:29:39 -07001480 Thread* self = Thread::Current();
1481 jobject jclass_loader = manager->GetClassLoader();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001482 const DexFile& dex_file = *manager->GetDexFile();
Ian Rogersbe7149f2013-08-20 09:29:39 -07001483 ClassLinker* class_linker = manager->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001484
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001485 // If an instance field is final then we need to have a barrier on the return, static final
1486 // fields are assigned within the lock held for class initialization. Conservatively assume
1487 // constructor barriers are always required.
1488 bool requires_constructor_barrier = true;
1489
Brian Carlstrom7940e442013-07-12 13:46:57 -07001490 // Method and Field are the worst. We can't resolve without either
1491 // context from the code use (to disambiguate virtual vs direct
1492 // method and instance vs static field) or from class
1493 // definitions. While the compiler will resolve what it can as it
1494 // needs it, here we try to resolve fields and methods used in class
1495 // definitions, since many of them many never be referenced by
1496 // generated code.
1497 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogersbe7149f2013-08-20 09:29:39 -07001498 if (!SkipClass(class_linker, jclass_loader, dex_file, class_def)) {
Brian Carlstromcb5f5e52013-09-23 17:48:16 -07001499 ScopedObjectAccess soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001500 SirtRef<mirror::ClassLoader> class_loader(soa.Self(), soa.Decode<mirror::ClassLoader*>(jclass_loader));
1501 SirtRef<mirror::DexCache> dex_cache(soa.Self(), class_linker->FindDexCache(dex_file));
Brian Carlstromcb5f5e52013-09-23 17:48:16 -07001502 // Resolve the class.
1503 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
1504 class_loader);
Brian Carlstromcb5f5e52013-09-23 17:48:16 -07001505 bool resolve_fields_and_methods;
1506 if (klass == NULL) {
1507 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
1508 // attempt to resolve methods and fields when there is no declaring class.
1509 CHECK(soa.Self()->IsExceptionPending());
1510 soa.Self()->ClearException();
1511 resolve_fields_and_methods = false;
1512 } else {
1513 resolve_fields_and_methods = manager->GetCompiler()->IsImage();
1514 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001515 // Note the class_data pointer advances through the headers,
1516 // static fields, instance fields, direct methods, and virtual
1517 // methods.
1518 const byte* class_data = dex_file.GetClassData(class_def);
1519 if (class_data == NULL) {
1520 // Empty class such as a marker interface.
1521 requires_constructor_barrier = false;
1522 } else {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001523 ClassDataItemIterator it(dex_file, class_data);
1524 while (it.HasNextStaticField()) {
1525 if (resolve_fields_and_methods) {
1526 mirror::ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1527 dex_cache, class_loader, true);
1528 if (field == NULL) {
1529 CHECK(soa.Self()->IsExceptionPending());
1530 soa.Self()->ClearException();
1531 }
1532 }
1533 it.Next();
1534 }
1535 // We require a constructor barrier if there are final instance fields.
1536 requires_constructor_barrier = false;
1537 while (it.HasNextInstanceField()) {
1538 if ((it.GetMemberAccessFlags() & kAccFinal) != 0) {
1539 requires_constructor_barrier = true;
1540 }
1541 if (resolve_fields_and_methods) {
1542 mirror::ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1543 dex_cache, class_loader, false);
1544 if (field == NULL) {
1545 CHECK(soa.Self()->IsExceptionPending());
1546 soa.Self()->ClearException();
1547 }
1548 }
1549 it.Next();
1550 }
1551 if (resolve_fields_and_methods) {
1552 while (it.HasNextDirectMethod()) {
1553 mirror::ArtMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1554 dex_cache, class_loader, NULL,
1555 it.GetMethodInvokeType(class_def));
1556 if (method == NULL) {
1557 CHECK(soa.Self()->IsExceptionPending());
1558 soa.Self()->ClearException();
1559 }
1560 it.Next();
1561 }
1562 while (it.HasNextVirtualMethod()) {
1563 mirror::ArtMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1564 dex_cache, class_loader, NULL,
1565 it.GetMethodInvokeType(class_def));
1566 if (method == NULL) {
1567 CHECK(soa.Self()->IsExceptionPending());
1568 soa.Self()->ClearException();
1569 }
1570 it.Next();
1571 }
1572 DCHECK(!it.HasNext());
1573 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001574 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001575 }
1576 if (requires_constructor_barrier) {
Ian Rogersbe7149f2013-08-20 09:29:39 -07001577 manager->GetCompiler()->AddRequiresConstructorBarrier(self, &dex_file, class_def_index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001578 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001579}
1580
1581static void ResolveType(const ParallelCompilationManager* manager, size_t type_idx)
1582 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1583 // Class derived values are more complicated, they require the linker and loader.
1584 ScopedObjectAccess soa(Thread::Current());
1585 ClassLinker* class_linker = manager->GetClassLinker();
1586 const DexFile& dex_file = *manager->GetDexFile();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001587 SirtRef<mirror::DexCache> dex_cache(soa.Self(), class_linker->FindDexCache(dex_file));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001588 SirtRef<mirror::ClassLoader> class_loader(
1589 soa.Self(), soa.Decode<mirror::ClassLoader*>(manager->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001590 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
1591
1592 if (klass == NULL) {
1593 CHECK(soa.Self()->IsExceptionPending());
Ian Rogersa436fde2013-08-27 23:34:06 -07001594 mirror::Throwable* exception = soa.Self()->GetException(NULL);
1595 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
Ian Rogersdfb325e2013-10-30 01:00:44 -07001596 if (strcmp("Ljava/lang/OutOfMemoryError;",
1597 ClassHelper(exception->GetClass()).GetDescriptor()) == 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001598 // There's little point continuing compilation if the heap is exhausted.
1599 LOG(FATAL) << "Out of memory during type resolution for compilation";
1600 }
1601 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001602 }
1603}
1604
1605void CompilerDriver::ResolveDexFile(jobject class_loader, const DexFile& dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001606 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001607 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1608
1609 // TODO: we could resolve strings here, although the string table is largely filled with class
1610 // and method names.
1611
1612 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001613 if (IsImage()) {
1614 // For images we resolve all types, such as array, whereas for applications just those with
1615 // classdefs are resolved by ResolveClassFieldsAndMethods.
Ian Rogers3d504072014-03-01 09:16:49 -08001616 timings->NewSplit("Resolve Types");
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001617 context.ForAll(0, dex_file.NumTypeIds(), ResolveType, thread_count_);
1618 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001619
Ian Rogers3d504072014-03-01 09:16:49 -08001620 timings->NewSplit("Resolve MethodsAndFields");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001621 context.ForAll(0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001622}
1623
1624void CompilerDriver::Verify(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001625 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001626 for (size_t i = 0; i != dex_files.size(); ++i) {
1627 const DexFile* dex_file = dex_files[i];
1628 CHECK(dex_file != NULL);
1629 VerifyDexFile(class_loader, *dex_file, thread_pool, timings);
1630 }
1631}
1632
1633static void VerifyClass(const ParallelCompilationManager* manager, size_t class_def_index)
1634 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001635 ATRACE_CALL();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001636 ScopedObjectAccess soa(Thread::Current());
Jeff Hao0e49b422013-11-08 12:16:56 -08001637 const DexFile& dex_file = *manager->GetDexFile();
1638 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1639 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1640 ClassLinker* class_linker = manager->GetClassLinker();
1641 jobject jclass_loader = manager->GetClassLoader();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001642 SirtRef<mirror::ClassLoader> class_loader(
1643 soa.Self(), soa.Decode<mirror::ClassLoader*>(jclass_loader));
Ian Rogers98379392014-02-24 16:53:16 -08001644 SirtRef<mirror::Class> klass(soa.Self(), class_linker->FindClass(soa.Self(), descriptor,
1645 class_loader));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001646 if (klass.get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001647 CHECK(soa.Self()->IsExceptionPending());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001648 soa.Self()->ClearException();
1649
1650 /*
1651 * At compile time, we can still structurally verify the class even if FindClass fails.
1652 * This is to ensure the class is structurally sound for compilation. An unsound class
1653 * will be rejected by the verifier and later skipped during compilation in the compiler.
1654 */
Mathieu Chartier590fee92013-09-13 13:46:47 -07001655 SirtRef<mirror::DexCache> dex_cache(soa.Self(), class_linker->FindDexCache(dex_file));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001656 std::string error_msg;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001657 if (verifier::MethodVerifier::VerifyClass(&dex_file, dex_cache, class_loader, &class_def, true,
1658 &error_msg) ==
Brian Carlstrom7940e442013-07-12 13:46:57 -07001659 verifier::MethodVerifier::kHardFailure) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001660 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001661 << " because: " << error_msg;
1662 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001663 } else if (!SkipClass(jclass_loader, dex_file, klass.get())) {
1664 CHECK(klass->IsResolved()) << PrettyClass(klass.get());
Jeff Hao0e49b422013-11-08 12:16:56 -08001665 class_linker->VerifyClass(klass);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001666
1667 if (klass->IsErroneous()) {
1668 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1669 CHECK(soa.Self()->IsExceptionPending());
1670 soa.Self()->ClearException();
1671 }
1672
1673 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001674 << PrettyDescriptor(klass.get()) << ": state=" << klass->GetStatus();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001675 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001676 soa.Self()->AssertNoPendingException();
1677}
1678
1679void CompilerDriver::VerifyDexFile(jobject class_loader, const DexFile& dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001680 ThreadPool* thread_pool, TimingLogger* timings) {
1681 timings->NewSplit("Verify Dex File");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001682 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1683 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
1684 context.ForAll(0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001685}
1686
Brian Carlstrom7940e442013-07-12 13:46:57 -07001687static void InitializeClass(const ParallelCompilationManager* manager, size_t class_def_index)
1688 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001689 ATRACE_CALL();
Jeff Hao0e49b422013-11-08 12:16:56 -08001690 jobject jclass_loader = manager->GetClassLoader();
1691 const DexFile& dex_file = *manager->GetDexFile();
1692 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Jeff Haobcdbbfe2013-11-08 18:03:22 -08001693 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
1694 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001695
Brian Carlstrom7940e442013-07-12 13:46:57 -07001696 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001697 SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
1698 soa.Decode<mirror::ClassLoader*>(jclass_loader));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001699 SirtRef<mirror::Class> klass(soa.Self(),
Ian Rogers98379392014-02-24 16:53:16 -08001700 manager->GetClassLinker()->FindClass(soa.Self(), descriptor,
1701 class_loader));
Jeff Hao0e49b422013-11-08 12:16:56 -08001702
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001703 if (klass.get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.get())) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001704 // Only try to initialize classes that were successfully verified.
1705 if (klass->IsVerified()) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001706 // Attempt to initialize the class but bail if we either need to initialize the super-class
1707 // or static fields.
1708 manager->GetClassLinker()->EnsureInitialized(klass, false, false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001709 if (!klass->IsInitialized()) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001710 // We don't want non-trivial class initialization occurring on multiple threads due to
1711 // deadlock problems. For example, a parent class is initialized (holding its lock) that
1712 // refers to a sub-class in its static/class initializer causing it to try to acquire the
1713 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
1714 // after first initializing its parents, whose locks are acquired. This leads to a
1715 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
1716 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
1717 // than use a special Object for the purpose we use the Class of java.lang.Class.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001718 SirtRef<mirror::Class> sirt_klass(soa.Self(), klass->GetClass());
1719 ObjectLock<mirror::Class> lock(soa.Self(), &sirt_klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001720 // Attempt to initialize allowing initialization of parent classes but still not static
1721 // fields.
1722 manager->GetClassLinker()->EnsureInitialized(klass, false, true);
1723 if (!klass->IsInitialized()) {
1724 // We need to initialize static fields, we only do this for image classes that aren't
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001725 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001726 bool can_init_static_fields = manager->GetCompiler()->IsImage() &&
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001727 manager->GetCompiler()->IsImageClass(descriptor) &&
1728 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001729 if (can_init_static_fields) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001730 VLOG(compiler) << "Initializing: " << descriptor;
1731 if (strcmp("Ljava/lang/Void;", descriptor) == 0) {
1732 // Hand initialize j.l.Void to avoid Dex file operations in un-started runtime.
1733 ObjectLock<mirror::Class> lock(soa.Self(), &klass);
1734 mirror::ObjectArray<mirror::ArtField>* fields = klass->GetSFields();
1735 CHECK_EQ(fields->GetLength(), 1);
1736 fields->Get(0)->SetObj<false>(klass.get(),
1737 manager->GetClassLinker()->FindPrimitiveClass('V'));
1738 klass->SetStatus(mirror::Class::kStatusInitialized, soa.Self());
1739 } else {
1740 // TODO multithreading support. We should ensure the current compilation thread has
1741 // exclusive access to the runtime and the transaction. To achieve this, we could use
1742 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
1743 // checks in Thread::AssertThreadSuspensionIsAllowable.
1744 Runtime* const runtime = Runtime::Current();
1745 Transaction transaction;
1746
1747 // Run the class initializer in transaction mode.
1748 runtime->EnterTransactionMode(&transaction);
1749 const mirror::Class::Status old_status = klass->GetStatus();
1750 bool success = manager->GetClassLinker()->EnsureInitialized(klass, true, true);
1751 // TODO we detach transaction from runtime to indicate we quit the transactional
1752 // mode which prevents the GC from visiting objects modified during the transaction.
1753 // Ensure GC is not run so don't access freed objects when aborting transaction.
1754 const char* old_casue = soa.Self()->StartAssertNoThreadSuspension("Transaction end");
1755 runtime->ExitTransactionMode();
1756
1757 if (!success) {
1758 CHECK(soa.Self()->IsExceptionPending());
1759 ThrowLocation throw_location;
1760 mirror::Throwable* exception = soa.Self()->GetException(&throw_location);
1761 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
1762 << exception->Dump();
1763 soa.Self()->ClearException();
1764 transaction.Abort();
1765 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001766 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001767 soa.Self()->EndAssertNoThreadSuspension(old_casue);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001768 }
1769 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001770 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001771 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001772 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001773 }
1774 // Record the final class status if necessary.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001775 ClassReference ref(manager->GetDexFile(), class_def_index);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001776 manager->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001777 }
1778 // Clear any class not found or verification exceptions.
1779 soa.Self()->ClearException();
1780}
1781
1782void CompilerDriver::InitializeClasses(jobject jni_class_loader, const DexFile& dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001783 ThreadPool* thread_pool, TimingLogger* timings) {
1784 timings->NewSplit("InitializeNoClinit");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001785 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1786 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, thread_pool);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001787 size_t thread_count;
1788 if (IsImage()) {
1789 // TODO: remove this when transactional mode supports multithreading.
1790 thread_count = 1U;
1791 } else {
1792 thread_count = thread_count_;
1793 }
1794 context.ForAll(0, dex_file.NumClassDefs(), InitializeClass, thread_count);
1795 if (IsImage()) {
1796 // Prune garbage objects created during aborted transactions.
1797 Runtime::Current()->GetHeap()->CollectGarbage(true);
1798 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001799}
1800
1801void CompilerDriver::InitializeClasses(jobject class_loader,
1802 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001803 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001804 for (size_t i = 0; i != dex_files.size(); ++i) {
1805 const DexFile* dex_file = dex_files[i];
1806 CHECK(dex_file != NULL);
1807 InitializeClasses(class_loader, *dex_file, thread_pool, timings);
1808 }
1809}
1810
1811void CompilerDriver::Compile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001812 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001813 for (size_t i = 0; i != dex_files.size(); ++i) {
1814 const DexFile* dex_file = dex_files[i];
1815 CHECK(dex_file != NULL);
1816 CompileDexFile(class_loader, *dex_file, thread_pool, timings);
1817 }
1818}
1819
1820void CompilerDriver::CompileClass(const ParallelCompilationManager* manager, size_t class_def_index) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001821 ATRACE_CALL();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001822 jobject jclass_loader = manager->GetClassLoader();
1823 const DexFile& dex_file = *manager->GetDexFile();
1824 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogersbe7149f2013-08-20 09:29:39 -07001825 ClassLinker* class_linker = manager->GetClassLinker();
1826 if (SkipClass(class_linker, jclass_loader, dex_file, class_def)) {
1827 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001828 }
1829 ClassReference ref(&dex_file, class_def_index);
1830 // Skip compiling classes with generic verifier failures since they will still fail at runtime
Vladimir Markoc7f83202014-01-24 17:55:18 +00001831 if (manager->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001832 return;
1833 }
1834 const byte* class_data = dex_file.GetClassData(class_def);
1835 if (class_data == NULL) {
1836 // empty class, probably a marker interface
1837 return;
1838 }
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001839
Brian Carlstrom7940e442013-07-12 13:46:57 -07001840 // Can we run DEX-to-DEX compiler on this class ?
Sebastien Hertz75021222013-07-16 18:34:50 +02001841 DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001842 {
1843 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001844 SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
1845 soa.Decode<mirror::ClassLoader*>(jclass_loader));
Ian Rogers98379392014-02-24 16:53:16 -08001846 dex_to_dex_compilation_level = GetDexToDexCompilationlevel(soa.Self(), class_loader, dex_file,
1847 class_def);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001848 }
1849 ClassDataItemIterator it(dex_file, class_data);
1850 // Skip fields
1851 while (it.HasNextStaticField()) {
1852 it.Next();
1853 }
1854 while (it.HasNextInstanceField()) {
1855 it.Next();
1856 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07001857 CompilerDriver* driver = manager->GetCompiler();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001858 // Compile direct methods
1859 int64_t previous_direct_method_idx = -1;
1860 while (it.HasNextDirectMethod()) {
1861 uint32_t method_idx = it.GetMemberIndex();
1862 if (method_idx == previous_direct_method_idx) {
1863 // smali can create dex files with two encoded_methods sharing the same method_idx
1864 // http://code.google.com/p/smali/issues/detail?id=119
1865 it.Next();
1866 continue;
1867 }
1868 previous_direct_method_idx = method_idx;
Ian Rogersbe7149f2013-08-20 09:29:39 -07001869 driver->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1870 it.GetMethodInvokeType(class_def), class_def_index,
1871 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001872 it.Next();
1873 }
1874 // Compile virtual methods
1875 int64_t previous_virtual_method_idx = -1;
1876 while (it.HasNextVirtualMethod()) {
1877 uint32_t method_idx = it.GetMemberIndex();
1878 if (method_idx == previous_virtual_method_idx) {
1879 // smali can create dex files with two encoded_methods sharing the same method_idx
1880 // http://code.google.com/p/smali/issues/detail?id=119
1881 it.Next();
1882 continue;
1883 }
1884 previous_virtual_method_idx = method_idx;
Ian Rogersbe7149f2013-08-20 09:29:39 -07001885 driver->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1886 it.GetMethodInvokeType(class_def), class_def_index,
1887 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001888 it.Next();
1889 }
1890 DCHECK(!it.HasNext());
1891}
1892
1893void CompilerDriver::CompileDexFile(jobject class_loader, const DexFile& dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001894 ThreadPool* thread_pool, TimingLogger* timings) {
1895 timings->NewSplit("Compile Dex File");
Ian Rogersbe7149f2013-08-20 09:29:39 -07001896 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
1897 &dex_file, thread_pool);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001898 context.ForAll(0, dex_file.NumClassDefs(), CompilerDriver::CompileClass, thread_count_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001899}
1900
1901void CompilerDriver::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001902 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom7940e442013-07-12 13:46:57 -07001903 uint32_t method_idx, jobject class_loader,
1904 const DexFile& dex_file,
Sebastien Hertz75021222013-07-16 18:34:50 +02001905 DexToDexCompilationLevel dex_to_dex_compilation_level) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001906 CompiledMethod* compiled_method = NULL;
1907 uint64_t start_ns = NanoTime();
1908
1909 if ((access_flags & kAccNative) != 0) {
Ian Rogers0188ab72014-03-17 16:51:53 -07001910 // Are we interpreting only and have support for generic JNI down calls?
Jeff Hao4a200f52014-04-01 14:58:49 -07001911 if (!compiler_options_->IsCompilationEnabled() &&
Stuart Monteithb95a5342014-03-12 13:32:32 +00001912 (instruction_set_ == kX86_64 || instruction_set_ == kArm64)) {
Ian Rogers5b271492014-03-14 13:20:26 -07001913 // Leaving this empty will trigger the generic JNI version
1914 } else {
1915 compiled_method = compiler_->JniCompile(*this, access_flags, method_idx, dex_file);
1916 CHECK(compiled_method != NULL);
1917 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001918 } else if ((access_flags & kAccAbstract) != 0) {
1919 } else {
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07001920 MethodReference method_ref(&dex_file, method_idx);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001921 bool compile = verification_results_->IsCandidateForCompilation(method_ref, access_flags);
Sebastien Hertz4d4adb12013-07-24 16:14:19 +02001922 if (compile) {
buzbeea024a062013-07-31 10:47:37 -07001923 // NOTE: if compiler declines to compile this method, it will return NULL.
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001924 compiled_method = compiler_->Compile(
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +00001925 *this, code_item, access_flags, invoke_type, class_def_idx,
1926 method_idx, class_loader, dex_file);
Sebastien Hertz17965ed2014-04-04 15:59:53 +02001927 }
1928 if (compiled_method == nullptr && dex_to_dex_compilation_level != kDontDexToDexCompile) {
1929 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Sebastien Hertz75021222013-07-16 18:34:50 +02001930 (*dex_to_dex_compiler_)(*this, code_item, access_flags,
1931 invoke_type, class_def_idx,
1932 method_idx, class_loader, dex_file,
1933 dex_to_dex_compilation_level);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001934 }
1935 }
1936 uint64_t duration_ns = NanoTime() - start_ns;
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001937 if (duration_ns > MsToNs(compiler_->GetMaximumCompilationTimeBeforeWarning())) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001938 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
1939 << " took " << PrettyDuration(duration_ns);
1940 }
1941
1942 Thread* self = Thread::Current();
1943 if (compiled_method != NULL) {
1944 MethodReference ref(&dex_file, method_idx);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001945 DCHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001946 {
1947 MutexLock mu(self, compiled_methods_lock_);
1948 compiled_methods_.Put(ref, compiled_method);
1949 }
1950 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
1951 }
1952
1953 if (self->IsExceptionPending()) {
1954 ScopedObjectAccess soa(self);
1955 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
1956 << self->GetException(NULL)->Dump();
1957 }
1958}
1959
1960CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
1961 MutexLock mu(Thread::Current(), compiled_classes_lock_);
1962 ClassTable::const_iterator it = compiled_classes_.find(ref);
1963 if (it == compiled_classes_.end()) {
1964 return NULL;
1965 }
1966 CHECK(it->second != NULL);
1967 return it->second;
1968}
1969
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001970void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
1971 MutexLock mu(Thread::Current(), compiled_classes_lock_);
1972 auto it = compiled_classes_.find(ref);
1973 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
1974 // An entry doesn't exist or the status is lower than the new status.
1975 if (it != compiled_classes_.end()) {
1976 CHECK_GT(status, it->second->GetStatus());
1977 delete it->second;
1978 }
1979 switch (status) {
1980 case mirror::Class::kStatusNotReady:
1981 case mirror::Class::kStatusError:
1982 case mirror::Class::kStatusRetryVerificationAtRuntime:
1983 case mirror::Class::kStatusVerified:
1984 case mirror::Class::kStatusInitialized:
1985 break; // Expected states.
1986 default:
1987 LOG(FATAL) << "Unexpected class status for class "
1988 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
1989 << " of " << status;
1990 }
1991 CompiledClass* compiled_class = new CompiledClass(status);
1992 compiled_classes_.Overwrite(ref, compiled_class);
1993 }
1994}
1995
Brian Carlstrom7940e442013-07-12 13:46:57 -07001996CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
1997 MutexLock mu(Thread::Current(), compiled_methods_lock_);
1998 MethodTable::const_iterator it = compiled_methods_.find(ref);
1999 if (it == compiled_methods_.end()) {
2000 return NULL;
2001 }
2002 CHECK(it->second != NULL);
2003 return it->second;
2004}
2005
Brian Carlstrom7940e442013-07-12 13:46:57 -07002006void CompilerDriver::AddRequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002007 uint16_t class_def_index) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002008 WriterMutexLock mu(self, freezing_constructor_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002009 freezing_constructor_classes_.insert(ClassReference(dex_file, class_def_index));
2010}
2011
2012bool CompilerDriver::RequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002013 uint16_t class_def_index) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002014 ReaderMutexLock mu(self, freezing_constructor_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002015 return freezing_constructor_classes_.count(ClassReference(dex_file, class_def_index)) != 0;
2016}
2017
2018bool CompilerDriver::WriteElf(const std::string& android_root,
2019 bool is_host,
2020 const std::vector<const art::DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08002021 OatWriter* oat_writer,
Brian Carlstrom7940e442013-07-12 13:46:57 -07002022 art::File* file)
2023 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00002024 return compiler_->WriteElf(file, oat_writer, dex_files, android_root, is_host, *this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002025}
2026void CompilerDriver::InstructionSetToLLVMTarget(InstructionSet instruction_set,
Ian Rogers3d504072014-03-01 09:16:49 -08002027 std::string* target_triple,
2028 std::string* target_cpu,
2029 std::string* target_attr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002030 switch (instruction_set) {
2031 case kThumb2:
Ian Rogers3d504072014-03-01 09:16:49 -08002032 *target_triple = "thumb-none-linux-gnueabi";
2033 *target_cpu = "cortex-a9";
2034 *target_attr = "+thumb2,+neon,+neonfp,+vfp3,+db";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002035 break;
2036
2037 case kArm:
Ian Rogers3d504072014-03-01 09:16:49 -08002038 *target_triple = "armv7-none-linux-gnueabi";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002039 // TODO: Fix for Nexus S.
Ian Rogers3d504072014-03-01 09:16:49 -08002040 *target_cpu = "cortex-a9";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002041 // TODO: Fix for Xoom.
Ian Rogers3d504072014-03-01 09:16:49 -08002042 *target_attr = "+v7,+neon,+neonfp,+vfp3,+db";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002043 break;
2044
2045 case kX86:
Ian Rogers3d504072014-03-01 09:16:49 -08002046 *target_triple = "i386-pc-linux-gnu";
2047 *target_attr = "";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002048 break;
2049
Dmitry Petrochenko6a58cb12014-04-02 17:27:59 +07002050 case kX86_64:
2051 *target_triple = "x86_64-pc-linux-gnu";
2052 *target_attr = "";
2053 break;
2054
Brian Carlstrom7940e442013-07-12 13:46:57 -07002055 case kMips:
Ian Rogers3d504072014-03-01 09:16:49 -08002056 *target_triple = "mipsel-unknown-linux";
2057 *target_attr = "mips32r2";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002058 break;
2059
2060 default:
2061 LOG(FATAL) << "Unknown instruction set: " << instruction_set;
2062 }
2063 }
Dave Allison39c3bfb2014-01-28 18:33:52 -08002064
2065bool CompilerDriver::ReadProfile(const std::string& filename) {
2066 VLOG(compiler) << "reading profile file " << filename;
2067 struct stat st;
2068 int err = stat(filename.c_str(), &st);
2069 if (err == -1) {
2070 VLOG(compiler) << "not found";
2071 return false;
2072 }
2073 std::ifstream in(filename.c_str());
2074 if (!in) {
2075 VLOG(compiler) << "profile file " << filename << " exists but can't be opened";
2076 VLOG(compiler) << "file owner: " << st.st_uid << ":" << st.st_gid;
2077 VLOG(compiler) << "me: " << getuid() << ":" << getgid();
2078 VLOG(compiler) << "file permissions: " << std::oct << st.st_mode;
2079 VLOG(compiler) << "errno: " << errno;
2080 return false;
2081 }
2082 // The first line contains summary information.
2083 std::string line;
2084 std::getline(in, line);
2085 if (in.eof()) {
2086 return false;
2087 }
2088 std::vector<std::string> summary_info;
2089 Split(line, '/', summary_info);
2090 if (summary_info.size() != 3) {
Calin Juravle04ff2262014-04-02 19:08:47 +01002091 // Bad summary info. It should be count/total/bootpath.
Dave Allison39c3bfb2014-01-28 18:33:52 -08002092 return false;
2093 }
2094 // This is the number of hits in all methods.
2095 uint32_t total_count = 0;
2096 for (int i = 0 ; i < 3; ++i) {
Calin Juravleea1e5202014-04-02 15:41:43 +01002097 total_count += atoi(summary_info[i].c_str());
Dave Allison39c3bfb2014-01-28 18:33:52 -08002098 }
2099
Calin Juravle04ff2262014-04-02 19:08:47 +01002100 // Now read each line until the end of file. Each line consists of 3 fields separated by '/'.
2101 // Store the info in descending order given by the most used methods.
Calin Juravlef6a4cee2014-04-02 17:03:08 +01002102 typedef std::set<std::pair<int, std::vector<std::string>>> ProfileSet;
2103 ProfileSet countSet;
Dave Allison39c3bfb2014-01-28 18:33:52 -08002104 while (!in.eof()) {
2105 std::getline(in, line);
2106 if (in.eof()) {
2107 break;
2108 }
2109 std::vector<std::string> info;
2110 Split(line, '/', info);
2111 if (info.size() != 3) {
2112 // Malformed.
2113 break;
2114 }
Calin Juravlef6a4cee2014-04-02 17:03:08 +01002115 int count = atoi(info[1].c_str());
2116 countSet.insert(std::make_pair(-count, info));
2117 }
2118
2119 uint32_t curTotalCount = 0;
2120 ProfileSet::iterator end = countSet.end();
2121 const ProfileData* prevData = nullptr;
2122 for (ProfileSet::iterator it = countSet.begin(); it != end ; it++) {
2123 const std::string& methodname = it->second[0];
2124 uint32_t count = -it->first;
2125 uint32_t size = atoi(it->second[2].c_str());
2126 double usedPercent = (count * 100.0) / total_count;
2127
2128 curTotalCount += count;
Calin Juravle04ff2262014-04-02 19:08:47 +01002129 // Methods with the same count should be part of the same top K percentage bucket.
Calin Juravlef6a4cee2014-04-02 17:03:08 +01002130 double topKPercentage = (prevData != nullptr) && (prevData->GetCount() == count)
2131 ? prevData->GetTopKUsedPercentage()
2132 : 100 * static_cast<double>(curTotalCount) / static_cast<double>(total_count);
2133
Calin Juravle04ff2262014-04-02 19:08:47 +01002134 // Add it to the profile map.
Calin Juravlef6a4cee2014-04-02 17:03:08 +01002135 ProfileData curData = ProfileData(methodname, count, size, usedPercent, topKPercentage);
2136 profile_map_[methodname] = curData;
2137 prevData = &curData;
Dave Allison39c3bfb2014-01-28 18:33:52 -08002138 }
2139 return true;
2140}
2141
2142bool CompilerDriver::SkipCompilation(const std::string& method_name) {
2143 if (!profile_ok_) {
2144 return true;
2145 }
Calin Juravle04ff2262014-04-02 19:08:47 +01002146 // Methods that comprise topKPercentThreshold % of the total samples will be compiled.
2147 double topKPercentThreshold = 90.0;
2148#ifdef HAVE_ANDROID_OS
2149 char buf[PROP_VALUE_MAX];
2150 property_get("dalvik.vm.profile.compile_thr", buf, "90.0");
2151 topKPercentThreshold = strtod(buf, nullptr);
2152#endif
2153 // Test for reasonable thresholds.
2154 if (topKPercentThreshold < 10.0 || topKPercentThreshold > 90.0) {
2155 topKPercentThreshold = 90.0;
2156 }
Dave Allison39c3bfb2014-01-28 18:33:52 -08002157
2158 // First find the method in the profile map.
2159 ProfileMap::iterator i = profile_map_.find(method_name);
2160 if (i == profile_map_.end()) {
2161 // Not in profile, no information can be determined.
2162 VLOG(compiler) << "not compiling " << method_name << " because it's not in the profile";
2163 return true;
2164 }
2165 const ProfileData& data = i->second;
Calin Juravle04ff2262014-04-02 19:08:47 +01002166
Calin Juravlef6a4cee2014-04-02 17:03:08 +01002167 // Compare against the start of the topK percentage bucket just in case the threshold
Calin Juravle04ff2262014-04-02 19:08:47 +01002168 // falls inside a bucket.
2169 bool compile = data.GetTopKUsedPercentage() - data.GetUsedPercent() <= topKPercentThreshold;
Dave Allison39c3bfb2014-01-28 18:33:52 -08002170 if (compile) {
Calin Juravlef6a4cee2014-04-02 17:03:08 +01002171 LOG(INFO) << "compiling method " << method_name << " because its usage is part of top "
2172 << data.GetTopKUsedPercentage() << "% with a percent of " << data.GetUsedPercent() << "%";
Dave Allison39c3bfb2014-01-28 18:33:52 -08002173 } else {
Calin Juravle04ff2262014-04-02 19:08:47 +01002174 VLOG(compiler) << "not compiling method " << method_name << " because it's not part of leading "
2175 << topKPercentThreshold << "% samples)";
Dave Allison39c3bfb2014-01-28 18:33:52 -08002176 }
2177 return !compile;
2178}
Dave Allison754ddad2014-02-19 14:05:39 -08002179
2180FinalEntrypointRelocationSet* CompilerDriver::AllocateFinalEntrypointRelocationSet(
2181 CompilationUnit* cu) const {
2182 switch (instruction_set_) {
2183 case kArm:
2184 case kThumb2:
2185 return new FinalEntrypointRelocationSetArm(this);
2186 default:
2187 UNIMPLEMENTED(FATAL) << "Cannot allocate FinalEntrypointRelocationSet for non-ARM";
2188 return nullptr;
2189 }
2190}
2191
Brian Carlstrom7940e442013-07-12 13:46:57 -07002192} // namespace art