blob: 708cce643740f6bb3162428f2dd6998dfe98d379 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "compiler_driver.h"
18
Anwar Ghuloum67f99412013-08-12 14:19:48 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <utils/Trace.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
Anwar Ghuloum67f99412013-08-12 14:19:48 -070022#include <vector>
Brian Carlstrom7940e442013-07-12 13:46:57 -070023#include <unistd.h>
24
25#include "base/stl_util.h"
26#include "base/timing_logger.h"
27#include "class_linker.h"
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +000028#include "compiler_backend.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070029#include "dex_compilation_unit.h"
30#include "dex_file-inl.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000031#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000032#include "dex/verified_method.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000033#include "dex/quick/dex_file_method_inliner.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080034#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070035#include "jni_internal.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070036#include "object_utils.h"
37#include "runtime.h"
38#include "gc/accounting/card_table-inl.h"
39#include "gc/accounting/heap_bitmap.h"
40#include "gc/space/space.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070041#include "mirror/art_field-inl.h"
42#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070043#include "mirror/class_loader.h"
44#include "mirror/class-inl.h"
45#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "mirror/object-inl.h"
47#include "mirror/object_array-inl.h"
48#include "mirror/throwable.h"
49#include "scoped_thread_state_change.h"
50#include "ScopedLocalRef.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "thread.h"
52#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070053#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010054#include "transaction.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "verifier/method_verifier.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000056#include "verifier/method_verifier-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070057
Brian Carlstrom7940e442013-07-12 13:46:57 -070058namespace art {
59
60static double Percentage(size_t x, size_t y) {
61 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
62}
63
64static void DumpStat(size_t x, size_t y, const char* str) {
65 if (x == 0 && y == 0) {
66 return;
67 }
Ian Rogerse732ef12013-10-09 15:22:24 -070068 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -070069}
70
71class AOTCompilationStats {
72 public:
73 AOTCompilationStats()
74 : stats_lock_("AOT compilation statistics lock"),
75 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
76 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
77 resolved_types_(0), unresolved_types_(0),
78 resolved_instance_fields_(0), unresolved_instance_fields_(0),
79 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
80 type_based_devirtualization_(0),
81 safe_casts_(0), not_safe_casts_(0) {
82 for (size_t i = 0; i <= kMaxInvokeType; i++) {
83 resolved_methods_[i] = 0;
84 unresolved_methods_[i] = 0;
85 virtual_made_direct_[i] = 0;
86 direct_calls_to_boot_[i] = 0;
87 direct_methods_to_boot_[i] = 0;
88 }
89 }
90
91 void Dump() {
92 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
93 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
94 DumpStat(resolved_types_, unresolved_types_, "types resolved");
95 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
96 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
97 "static fields resolved");
98 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
99 "static fields local to a class");
100 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
101 // Note, the code below subtracts the stat value so that when added to the stat value we have
102 // 100% of samples. TODO: clean this up.
103 DumpStat(type_based_devirtualization_,
104 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
105 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
106 type_based_devirtualization_,
107 "virtual/interface calls made direct based on type information");
108
109 for (size_t i = 0; i <= kMaxInvokeType; i++) {
110 std::ostringstream oss;
111 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
112 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
113 if (virtual_made_direct_[i] > 0) {
114 std::ostringstream oss2;
115 oss2 << static_cast<InvokeType>(i) << " methods made direct";
116 DumpStat(virtual_made_direct_[i],
117 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
118 oss2.str().c_str());
119 }
120 if (direct_calls_to_boot_[i] > 0) {
121 std::ostringstream oss2;
122 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
123 DumpStat(direct_calls_to_boot_[i],
124 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
125 oss2.str().c_str());
126 }
127 if (direct_methods_to_boot_[i] > 0) {
128 std::ostringstream oss2;
129 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
130 DumpStat(direct_methods_to_boot_[i],
131 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
132 oss2.str().c_str());
133 }
134 }
135 }
136
137// Allow lossy statistics in non-debug builds.
138#ifndef NDEBUG
139#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
140#else
141#define STATS_LOCK()
142#endif
143
144 void TypeInDexCache() {
145 STATS_LOCK();
146 types_in_dex_cache_++;
147 }
148
149 void TypeNotInDexCache() {
150 STATS_LOCK();
151 types_not_in_dex_cache_++;
152 }
153
154 void StringInDexCache() {
155 STATS_LOCK();
156 strings_in_dex_cache_++;
157 }
158
159 void StringNotInDexCache() {
160 STATS_LOCK();
161 strings_not_in_dex_cache_++;
162 }
163
164 void TypeDoesntNeedAccessCheck() {
165 STATS_LOCK();
166 resolved_types_++;
167 }
168
169 void TypeNeedsAccessCheck() {
170 STATS_LOCK();
171 unresolved_types_++;
172 }
173
174 void ResolvedInstanceField() {
175 STATS_LOCK();
176 resolved_instance_fields_++;
177 }
178
179 void UnresolvedInstanceField() {
180 STATS_LOCK();
181 unresolved_instance_fields_++;
182 }
183
184 void ResolvedLocalStaticField() {
185 STATS_LOCK();
186 resolved_local_static_fields_++;
187 }
188
189 void ResolvedStaticField() {
190 STATS_LOCK();
191 resolved_static_fields_++;
192 }
193
194 void UnresolvedStaticField() {
195 STATS_LOCK();
196 unresolved_static_fields_++;
197 }
198
199 // Indicate that type information from the verifier led to devirtualization.
200 void PreciseTypeDevirtualization() {
201 STATS_LOCK();
202 type_based_devirtualization_++;
203 }
204
205 // Indicate that a method of the given type was resolved at compile time.
206 void ResolvedMethod(InvokeType type) {
207 DCHECK_LE(type, kMaxInvokeType);
208 STATS_LOCK();
209 resolved_methods_[type]++;
210 }
211
212 // Indicate that a method of the given type was unresolved at compile time as it was in an
213 // unknown dex file.
214 void UnresolvedMethod(InvokeType type) {
215 DCHECK_LE(type, kMaxInvokeType);
216 STATS_LOCK();
217 unresolved_methods_[type]++;
218 }
219
220 // Indicate that a type of virtual method dispatch has been converted into a direct method
221 // dispatch.
222 void VirtualMadeDirect(InvokeType type) {
223 DCHECK(type == kVirtual || type == kInterface || type == kSuper);
224 STATS_LOCK();
225 virtual_made_direct_[type]++;
226 }
227
228 // Indicate that a method of the given type was able to call directly into boot.
229 void DirectCallsToBoot(InvokeType type) {
230 DCHECK_LE(type, kMaxInvokeType);
231 STATS_LOCK();
232 direct_calls_to_boot_[type]++;
233 }
234
235 // Indicate that a method of the given type was able to be resolved directly from boot.
236 void DirectMethodsToBoot(InvokeType type) {
237 DCHECK_LE(type, kMaxInvokeType);
238 STATS_LOCK();
239 direct_methods_to_boot_[type]++;
240 }
241
242 // A check-cast could be eliminated due to verifier type analysis.
243 void SafeCast() {
244 STATS_LOCK();
245 safe_casts_++;
246 }
247
248 // A check-cast couldn't be eliminated due to verifier type analysis.
249 void NotASafeCast() {
250 STATS_LOCK();
251 not_safe_casts_++;
252 }
253
254 private:
255 Mutex stats_lock_;
256
257 size_t types_in_dex_cache_;
258 size_t types_not_in_dex_cache_;
259
260 size_t strings_in_dex_cache_;
261 size_t strings_not_in_dex_cache_;
262
263 size_t resolved_types_;
264 size_t unresolved_types_;
265
266 size_t resolved_instance_fields_;
267 size_t unresolved_instance_fields_;
268
269 size_t resolved_local_static_fields_;
270 size_t resolved_static_fields_;
271 size_t unresolved_static_fields_;
272 // Type based devirtualization for invoke interface and virtual.
273 size_t type_based_devirtualization_;
274
275 size_t resolved_methods_[kMaxInvokeType + 1];
276 size_t unresolved_methods_[kMaxInvokeType + 1];
277 size_t virtual_made_direct_[kMaxInvokeType + 1];
278 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
279 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
280
281 size_t safe_casts_;
282 size_t not_safe_casts_;
283
284 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
285};
286
Brian Carlstrom7940e442013-07-12 13:46:57 -0700287
288extern "C" art::CompiledMethod* ArtCompileDEX(art::CompilerDriver& compiler,
289 const art::DexFile::CodeItem* code_item,
290 uint32_t access_flags,
291 art::InvokeType invoke_type,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700292 uint16_t class_def_idx,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700293 uint32_t method_idx,
294 jobject class_loader,
295 const art::DexFile& dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700296
Brian Carlstrom6449c622014-02-10 23:48:36 -0800297CompilerDriver::CompilerDriver(const CompilerOptions* compiler_options,
298 VerificationResults* verification_results,
Vladimir Marko5816ed42013-11-27 17:04:20 +0000299 DexFileToMethodInlinerMap* method_inliner_map,
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000300 CompilerBackend::Kind compiler_backend_kind,
301 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700302 InstructionSetFeatures instruction_set_features,
buzbeea024a062013-07-31 10:47:37 -0700303 bool image, DescriptorSet* image_classes, size_t thread_count,
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000304 bool dump_stats, bool dump_passes, CumulativeLogger* timer)
Brian Carlstrom6449c622014-02-10 23:48:36 -0800305 : compiler_options_(compiler_options),
306 verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000307 method_inliner_map_(method_inliner_map),
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000308 compiler_backend_(CompilerBackend::Create(compiler_backend_kind)),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700309 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700310 instruction_set_features_(instruction_set_features),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700311 freezing_constructor_lock_("freezing constructor lock"),
312 compiled_classes_lock_("compiled classes lock"),
313 compiled_methods_lock_("compiled method lock"),
314 image_(image),
315 image_classes_(image_classes),
316 thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700317 start_ns_(0),
318 stats_(new AOTCompilationStats),
319 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000320 dump_passes_(dump_passes),
321 timings_logger_(timer),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700322 compiler_library_(NULL),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700323 compiler_context_(NULL),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700324 compiler_enable_auto_elf_loading_(NULL),
325 compiler_get_method_code_addr_(NULL),
Mark Mendell55d0eac2014-02-06 11:02:52 -0800326 support_boot_image_fixup_(instruction_set != kMips),
Mark Mendellae9fd932014-02-10 16:14:35 -0800327 cfi_info_(nullptr),
Ian Rogersd133b972013-09-05 11:01:30 -0700328 dedupe_code_("dedupe code"),
329 dedupe_mapping_table_("dedupe mapping table"),
330 dedupe_vmap_table_("dedupe vmap table"),
Mark Mendellae9fd932014-02-10 16:14:35 -0800331 dedupe_gc_map_("dedupe gc map"),
332 dedupe_cfi_info_("dedupe cfi info") {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800333 DCHECK(compiler_options_ != nullptr);
334 DCHECK(verification_results_ != nullptr);
335 DCHECK(method_inliner_map_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700336
Brian Carlstrom7940e442013-07-12 13:46:57 -0700337 CHECK_PTHREAD_CALL(pthread_key_create, (&tls_key_, NULL), "compiler tls key");
338
Sebastien Hertz75021222013-07-16 18:34:50 +0200339 dex_to_dex_compiler_ = reinterpret_cast<DexToDexCompilerFn>(ArtCompileDEX);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700340
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000341 compiler_backend_->Init(*this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700342
343 CHECK(!Runtime::Current()->IsStarted());
344 if (!image_) {
345 CHECK(image_classes_.get() == NULL);
346 }
Mark Mendellae9fd932014-02-10 16:14:35 -0800347
348 // Are we generating CFI information?
349 if (compiler_options->GetGenerateGDBInformation()) {
350 cfi_info_.reset(compiler_backend_->GetCallFrameInformationInitialization(*this));
351 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700352}
353
Mathieu Chartier193bad92013-08-29 18:46:00 -0700354std::vector<uint8_t>* CompilerDriver::DeduplicateCode(const std::vector<uint8_t>& code) {
355 return dedupe_code_.Add(Thread::Current(), code);
356}
357
358std::vector<uint8_t>* CompilerDriver::DeduplicateMappingTable(const std::vector<uint8_t>& code) {
359 return dedupe_mapping_table_.Add(Thread::Current(), code);
360}
361
362std::vector<uint8_t>* CompilerDriver::DeduplicateVMapTable(const std::vector<uint8_t>& code) {
363 return dedupe_vmap_table_.Add(Thread::Current(), code);
364}
365
366std::vector<uint8_t>* CompilerDriver::DeduplicateGCMap(const std::vector<uint8_t>& code) {
367 return dedupe_gc_map_.Add(Thread::Current(), code);
368}
369
Mark Mendellae9fd932014-02-10 16:14:35 -0800370std::vector<uint8_t>* CompilerDriver::DeduplicateCFIInfo(const std::vector<uint8_t>* cfi_info) {
371 if (cfi_info == nullptr) {
372 return nullptr;
373 }
374 return dedupe_cfi_info_.Add(Thread::Current(), *cfi_info);
375}
376
Brian Carlstrom7940e442013-07-12 13:46:57 -0700377CompilerDriver::~CompilerDriver() {
378 Thread* self = Thread::Current();
379 {
380 MutexLock mu(self, compiled_classes_lock_);
381 STLDeleteValues(&compiled_classes_);
382 }
383 {
384 MutexLock mu(self, compiled_methods_lock_);
385 STLDeleteValues(&compiled_methods_);
386 }
387 {
388 MutexLock mu(self, compiled_methods_lock_);
389 STLDeleteElements(&code_to_patch_);
390 }
391 {
392 MutexLock mu(self, compiled_methods_lock_);
393 STLDeleteElements(&methods_to_patch_);
394 }
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800395 {
396 MutexLock mu(self, compiled_methods_lock_);
397 STLDeleteElements(&classes_to_patch_);
398 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700399 CHECK_PTHREAD_CALL(pthread_key_delete, (tls_key_), "delete tls key");
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000400 compiler_backend_->UnInit(*this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700401}
402
403CompilerTls* CompilerDriver::GetTls() {
404 // Lazily create thread-local storage
405 CompilerTls* res = static_cast<CompilerTls*>(pthread_getspecific(tls_key_));
406 if (res == NULL) {
407 res = new CompilerTls();
408 CHECK_PTHREAD_CALL(pthread_setspecific, (tls_key_, res), "compiler tls");
409 }
410 return res;
411}
412
Ian Rogers848871b2013-08-05 10:56:33 -0700413const std::vector<uint8_t>* CompilerDriver::CreateInterpreterToInterpreterBridge() const {
414 return CreateTrampoline(instruction_set_, kInterpreterAbi,
415 INTERPRETER_ENTRYPOINT_OFFSET(pInterpreterToInterpreterBridge));
416}
417
418const std::vector<uint8_t>* CompilerDriver::CreateInterpreterToCompiledCodeBridge() const {
419 return CreateTrampoline(instruction_set_, kInterpreterAbi,
420 INTERPRETER_ENTRYPOINT_OFFSET(pInterpreterToCompiledCodeBridge));
421}
422
423const std::vector<uint8_t>* CompilerDriver::CreateJniDlsymLookup() const {
424 return CreateTrampoline(instruction_set_, kJniAbi, JNI_ENTRYPOINT_OFFSET(pDlsymLookup));
425}
426
Jeff Hao88474b42013-10-23 16:24:40 -0700427const std::vector<uint8_t>* CompilerDriver::CreatePortableImtConflictTrampoline() const {
428 return CreateTrampoline(instruction_set_, kPortableAbi,
429 PORTABLE_ENTRYPOINT_OFFSET(pPortableImtConflictTrampoline));
430}
431
Brian Carlstrom7940e442013-07-12 13:46:57 -0700432const std::vector<uint8_t>* CompilerDriver::CreatePortableResolutionTrampoline() const {
Ian Rogers848871b2013-08-05 10:56:33 -0700433 return CreateTrampoline(instruction_set_, kPortableAbi,
434 PORTABLE_ENTRYPOINT_OFFSET(pPortableResolutionTrampoline));
435}
436
437const std::vector<uint8_t>* CompilerDriver::CreatePortableToInterpreterBridge() const {
438 return CreateTrampoline(instruction_set_, kPortableAbi,
439 PORTABLE_ENTRYPOINT_OFFSET(pPortableToInterpreterBridge));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700440}
441
Jeff Hao88474b42013-10-23 16:24:40 -0700442const std::vector<uint8_t>* CompilerDriver::CreateQuickImtConflictTrampoline() const {
443 return CreateTrampoline(instruction_set_, kQuickAbi,
444 QUICK_ENTRYPOINT_OFFSET(pQuickImtConflictTrampoline));
445}
446
Brian Carlstrom7940e442013-07-12 13:46:57 -0700447const std::vector<uint8_t>* CompilerDriver::CreateQuickResolutionTrampoline() const {
Ian Rogers848871b2013-08-05 10:56:33 -0700448 return CreateTrampoline(instruction_set_, kQuickAbi,
449 QUICK_ENTRYPOINT_OFFSET(pQuickResolutionTrampoline));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700450}
451
Ian Rogers848871b2013-08-05 10:56:33 -0700452const std::vector<uint8_t>* CompilerDriver::CreateQuickToInterpreterBridge() const {
453 return CreateTrampoline(instruction_set_, kQuickAbi,
454 QUICK_ENTRYPOINT_OFFSET(pQuickToInterpreterBridge));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700455}
456
457void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700458 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800459 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700460 DCHECK(!Runtime::Current()->IsStarted());
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800461 UniquePtr<ThreadPool> thread_pool(new ThreadPool("Compiler driver thread pool", thread_count_ - 1));
Ian Rogers3d504072014-03-01 09:16:49 -0800462 PreCompile(class_loader, dex_files, thread_pool.get(), timings);
463 Compile(class_loader, dex_files, thread_pool.get(), timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700464 if (dump_stats_) {
465 stats_->Dump();
466 }
467}
468
Mathieu Chartier590fee92013-09-13 13:46:47 -0700469static DexToDexCompilationLevel GetDexToDexCompilationlevel(
Ian Rogers98379392014-02-24 16:53:16 -0800470 Thread* self, SirtRef<mirror::ClassLoader>& class_loader, const DexFile& dex_file,
Mathieu Chartier590fee92013-09-13 13:46:47 -0700471 const DexFile::ClassDef& class_def) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700472 const char* descriptor = dex_file.GetClassDescriptor(class_def);
473 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800474 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700475 if (klass == NULL) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700476 CHECK(self->IsExceptionPending());
477 self->ClearException();
Sebastien Hertz75021222013-07-16 18:34:50 +0200478 return kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700479 }
Sebastien Hertz75021222013-07-16 18:34:50 +0200480 // The verifier can only run on "quick" instructions at runtime (see usage of
481 // FindAccessedFieldAtDexPc and FindInvokedMethodAtDexPc in ThrowNullPointerExceptionFromDexPC
482 // function). Since image classes can be verified again while compiling an application,
483 // we must prevent the DEX-to-DEX compiler from introducing them.
484 // TODO: find a way to enable "quick" instructions for image classes and remove this check.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700485 bool compiling_image_classes = class_loader.get() == nullptr;
Sebastien Hertz75021222013-07-16 18:34:50 +0200486 if (compiling_image_classes) {
487 return kRequired;
488 } else if (klass->IsVerified()) {
489 // Class is verified so we can enable DEX-to-DEX compilation for performance.
490 return kOptimize;
491 } else if (klass->IsCompileTimeVerified()) {
492 // Class verification has soft-failed. Anyway, ensure at least correctness.
493 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
494 return kRequired;
495 } else {
496 // Class verification has failed: do not run DEX-to-DEX compilation.
497 return kDontDexToDexCompile;
498 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700499}
500
Ian Rogers3d504072014-03-01 09:16:49 -0800501void CompilerDriver::CompileOne(mirror::ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700502 DCHECK(!Runtime::Current()->IsStarted());
503 Thread* self = Thread::Current();
504 jobject jclass_loader;
505 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700506 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800507 uint32_t method_idx = method->GetDexMethodIndex();
508 uint32_t access_flags = method->GetAccessFlags();
509 InvokeType invoke_type = method->GetInvokeType();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700510 {
511 ScopedObjectAccessUnchecked soa(self);
512 ScopedLocalRef<jobject>
513 local_class_loader(soa.Env(),
514 soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
515 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
516 // Find the dex_file
517 MethodHelper mh(method);
518 dex_file = &mh.GetDexFile();
519 class_def_idx = mh.GetClassDefIndex();
520 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800521 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700522 self->TransitionFromRunnableToSuspended(kNative);
523
524 std::vector<const DexFile*> dex_files;
525 dex_files.push_back(dex_file);
526
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800527 UniquePtr<ThreadPool> thread_pool(new ThreadPool("Compiler driver thread pool", 0U));
Ian Rogers3d504072014-03-01 09:16:49 -0800528 PreCompile(jclass_loader, dex_files, thread_pool.get(), timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700529
Brian Carlstrom7940e442013-07-12 13:46:57 -0700530 // Can we run DEX-to-DEX compiler on this class ?
Sebastien Hertz75021222013-07-16 18:34:50 +0200531 DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700532 {
533 ScopedObjectAccess soa(Thread::Current());
534 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700535 SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
536 soa.Decode<mirror::ClassLoader*>(jclass_loader));
Ian Rogers98379392014-02-24 16:53:16 -0800537 dex_to_dex_compilation_level = GetDexToDexCompilationlevel(self, class_loader, *dex_file,
538 class_def);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700539 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800540 CompileMethod(code_item, access_flags, invoke_type, class_def_idx, method_idx, jclass_loader,
541 *dex_file, dex_to_dex_compilation_level);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700542
543 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
544
545 self->TransitionFromSuspendedToRunnable();
546}
547
548void CompilerDriver::Resolve(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800549 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700550 for (size_t i = 0; i != dex_files.size(); ++i) {
551 const DexFile* dex_file = dex_files[i];
552 CHECK(dex_file != NULL);
553 ResolveDexFile(class_loader, *dex_file, thread_pool, timings);
554 }
555}
556
557void CompilerDriver::PreCompile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800558 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700559 LoadImageClasses(timings);
560
561 Resolve(class_loader, dex_files, thread_pool, timings);
562
563 Verify(class_loader, dex_files, thread_pool, timings);
564
565 InitializeClasses(class_loader, dex_files, thread_pool, timings);
566
567 UpdateImageClasses(timings);
568}
569
Ian Rogersdfb325e2013-10-30 01:00:44 -0700570bool CompilerDriver::IsImageClass(const char* descriptor) const {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700571 if (!IsImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700572 return true;
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700573 } else {
Ian Rogersdfb325e2013-10-30 01:00:44 -0700574 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700575 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700576}
577
578static void ResolveExceptionsForMethod(MethodHelper* mh,
579 std::set<std::pair<uint16_t, const DexFile*> >& exceptions_to_resolve)
580 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
581 const DexFile::CodeItem* code_item = mh->GetCodeItem();
582 if (code_item == NULL) {
583 return; // native or abstract method
584 }
585 if (code_item->tries_size_ == 0) {
586 return; // nothing to process
587 }
588 const byte* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
589 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
590 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
591 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
592 bool has_catch_all = false;
593 if (encoded_catch_handler_size <= 0) {
594 encoded_catch_handler_size = -encoded_catch_handler_size;
595 has_catch_all = true;
596 }
597 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
598 uint16_t encoded_catch_handler_handlers_type_idx =
599 DecodeUnsignedLeb128(&encoded_catch_handler_list);
600 // Add to set of types to resolve if not already in the dex cache resolved types
601 if (!mh->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
602 exceptions_to_resolve.insert(
603 std::pair<uint16_t, const DexFile*>(encoded_catch_handler_handlers_type_idx,
604 &mh->GetDexFile()));
605 }
606 // ignore address associated with catch handler
607 DecodeUnsignedLeb128(&encoded_catch_handler_list);
608 }
609 if (has_catch_all) {
610 // ignore catch all address
611 DecodeUnsignedLeb128(&encoded_catch_handler_list);
612 }
613 }
614}
615
616static bool ResolveCatchBlockExceptionsClassVisitor(mirror::Class* c, void* arg)
617 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
618 std::set<std::pair<uint16_t, const DexFile*> >* exceptions_to_resolve =
619 reinterpret_cast<std::set<std::pair<uint16_t, const DexFile*> >*>(arg);
620 MethodHelper mh;
621 for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700622 mirror::ArtMethod* m = c->GetVirtualMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700623 mh.ChangeMethod(m);
624 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
625 }
626 for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700627 mirror::ArtMethod* m = c->GetDirectMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700628 mh.ChangeMethod(m);
629 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
630 }
631 return true;
632}
633
634static bool RecordImageClassesVisitor(mirror::Class* klass, void* arg)
635 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
636 CompilerDriver::DescriptorSet* image_classes =
637 reinterpret_cast<CompilerDriver::DescriptorSet*>(arg);
638 image_classes->insert(ClassHelper(klass).GetDescriptor());
639 return true;
640}
641
642// Make a list of descriptors for classes to include in the image
Ian Rogers3d504072014-03-01 09:16:49 -0800643void CompilerDriver::LoadImageClasses(TimingLogger* timings)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700644 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700645 if (!IsImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700646 return;
647 }
648
Ian Rogers3d504072014-03-01 09:16:49 -0800649 timings->NewSplit("LoadImageClasses");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700650 // Make a first class to load all classes explicitly listed in the file
651 Thread* self = Thread::Current();
652 ScopedObjectAccess soa(self);
653 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700654 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000655 const std::string& descriptor(*it);
Ian Rogers98379392014-02-24 16:53:16 -0800656 SirtRef<mirror::Class> klass(self, class_linker->FindSystemClass(self, descriptor.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700657 if (klass.get() == NULL) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700658 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000659 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -0700660 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700661 } else {
662 ++it;
663 }
664 }
665
666 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
667 // exceptions are resolved by the verifier when there is a catch block in an interested method.
668 // Do this here so that exception classes appear to have been specified image classes.
669 std::set<std::pair<uint16_t, const DexFile*> > unresolved_exception_types;
670 SirtRef<mirror::Class> java_lang_Throwable(self,
Ian Rogers98379392014-02-24 16:53:16 -0800671 class_linker->FindSystemClass(self, "Ljava/lang/Throwable;"));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700672 do {
673 unresolved_exception_types.clear();
674 class_linker->VisitClasses(ResolveCatchBlockExceptionsClassVisitor,
675 &unresolved_exception_types);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700676 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
677 uint16_t exception_type_idx = exception_type.first;
678 const DexFile* dex_file = exception_type.second;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700679 SirtRef<mirror::DexCache> dex_cache(self, class_linker->FindDexCache(*dex_file));
680 SirtRef<mirror::ClassLoader> class_loader(self, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700681 SirtRef<mirror::Class> klass(self, class_linker->ResolveType(*dex_file, exception_type_idx,
682 dex_cache, class_loader));
683 if (klass.get() == NULL) {
684 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
685 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
686 LOG(FATAL) << "Failed to resolve class " << descriptor;
687 }
688 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.get()));
689 }
690 // Resolving exceptions may load classes that reference more exceptions, iterate until no
691 // more are found
692 } while (!unresolved_exception_types.empty());
693
694 // We walk the roots looking for classes so that we'll pick up the
695 // above classes plus any classes them depend on such super
696 // classes, interfaces, and the required ClassLinker roots.
697 class_linker->VisitClasses(RecordImageClassesVisitor, image_classes_.get());
698
699 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700700}
701
702static void MaybeAddToImageClasses(mirror::Class* klass, CompilerDriver::DescriptorSet* image_classes)
703 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
704 while (!klass->IsObjectClass()) {
705 ClassHelper kh(klass);
706 const char* descriptor = kh.GetDescriptor();
707 std::pair<CompilerDriver::DescriptorSet::iterator, bool> result =
708 image_classes->insert(descriptor);
709 if (result.second) {
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700710 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700711 } else {
712 return;
713 }
714 for (size_t i = 0; i < kh.NumDirectInterfaces(); ++i) {
715 MaybeAddToImageClasses(kh.GetDirectInterface(i), image_classes);
716 }
717 if (klass->IsArrayClass()) {
718 MaybeAddToImageClasses(klass->GetComponentType(), image_classes);
719 }
720 klass = klass->GetSuperClass();
721 }
722}
723
724void CompilerDriver::FindClinitImageClassesCallback(mirror::Object* object, void* arg) {
725 DCHECK(object != NULL);
726 DCHECK(arg != NULL);
727 CompilerDriver* compiler_driver = reinterpret_cast<CompilerDriver*>(arg);
728 MaybeAddToImageClasses(object->GetClass(), compiler_driver->image_classes_.get());
729}
730
Ian Rogers3d504072014-03-01 09:16:49 -0800731void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700732 if (IsImage()) {
Ian Rogers3d504072014-03-01 09:16:49 -0800733 timings->NewSplit("UpdateImageClasses");
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700734
735 // Update image_classes_ with classes for objects created by <clinit> methods.
736 Thread* self = Thread::Current();
737 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
738 gc::Heap* heap = Runtime::Current()->GetHeap();
739 // TODO: Image spaces only?
Mathieu Chartier590fee92013-09-13 13:46:47 -0700740 ScopedObjectAccess soa(Thread::Current());
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700741 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700742 heap->VisitObjects(FindClinitImageClassesCallback, this);
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700743 self->EndAssertNoThreadSuspension(old_cause);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700744 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700745}
746
Mathieu Chartier590fee92013-09-13 13:46:47 -0700747bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(const DexFile& dex_file, uint32_t type_idx) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700748 if (IsImage() &&
Ian Rogersdfb325e2013-10-30 01:00:44 -0700749 IsImageClass(dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_))) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700750 if (kIsDebugBuild) {
751 ScopedObjectAccess soa(Thread::Current());
752 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
753 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
754 CHECK(resolved_class != NULL);
755 }
756 stats_->TypeInDexCache();
757 return true;
758 } else {
759 stats_->TypeNotInDexCache();
760 return false;
761 }
762}
763
764bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
765 uint32_t string_idx) {
766 // See also Compiler::ResolveDexFile
767
768 bool result = false;
769 if (IsImage()) {
770 // We resolve all const-string strings when building for the image.
771 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700772 SirtRef<mirror::DexCache> dex_cache(soa.Self(), Runtime::Current()->GetClassLinker()->FindDexCache(dex_file));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700773 Runtime::Current()->GetClassLinker()->ResolveString(dex_file, string_idx, dex_cache);
774 result = true;
775 }
776 if (result) {
777 stats_->StringInDexCache();
778 } else {
779 stats_->StringNotInDexCache();
780 }
781 return result;
782}
783
784bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
785 uint32_t type_idx,
786 bool* type_known_final, bool* type_known_abstract,
787 bool* equals_referrers_class) {
788 if (type_known_final != NULL) {
789 *type_known_final = false;
790 }
791 if (type_known_abstract != NULL) {
792 *type_known_abstract = false;
793 }
794 if (equals_referrers_class != NULL) {
795 *equals_referrers_class = false;
796 }
797 ScopedObjectAccess soa(Thread::Current());
798 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
799 // Get type from dex cache assuming it was populated by the verifier
800 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
801 if (resolved_class == NULL) {
802 stats_->TypeNeedsAccessCheck();
803 return false; // Unknown class needs access checks.
804 }
805 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
806 if (equals_referrers_class != NULL) {
807 *equals_referrers_class = (method_id.class_idx_ == type_idx);
808 }
809 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
810 if (referrer_class == NULL) {
811 stats_->TypeNeedsAccessCheck();
812 return false; // Incomplete referrer knowledge needs access check.
813 }
814 // Perform access check, will return true if access is ok or false if we're going to have to
815 // check this at runtime (for example for class loaders).
816 bool result = referrer_class->CanAccess(resolved_class);
817 if (result) {
818 stats_->TypeDoesntNeedAccessCheck();
819 if (type_known_final != NULL) {
820 *type_known_final = resolved_class->IsFinal() && !resolved_class->IsArrayClass();
821 }
822 if (type_known_abstract != NULL) {
823 *type_known_abstract = resolved_class->IsAbstract() && !resolved_class->IsArrayClass();
824 }
825 } else {
826 stats_->TypeNeedsAccessCheck();
827 }
828 return result;
829}
830
831bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
832 const DexFile& dex_file,
833 uint32_t type_idx) {
834 ScopedObjectAccess soa(Thread::Current());
835 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
836 // Get type from dex cache assuming it was populated by the verifier.
837 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
838 if (resolved_class == NULL) {
839 stats_->TypeNeedsAccessCheck();
840 return false; // Unknown class needs access checks.
841 }
842 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
843 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
844 if (referrer_class == NULL) {
845 stats_->TypeNeedsAccessCheck();
846 return false; // Incomplete referrer knowledge needs access check.
847 }
848 // Perform access and instantiable checks, will return true if access is ok or false if we're
849 // going to have to check this at runtime (for example for class loaders).
850 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
851 if (result) {
852 stats_->TypeDoesntNeedAccessCheck();
853 } else {
854 stats_->TypeNeedsAccessCheck();
855 }
856 return result;
857}
858
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800859bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
860 bool* is_type_initialized, bool* use_direct_type_ptr,
861 uintptr_t* direct_type_ptr) {
862 ScopedObjectAccess soa(Thread::Current());
863 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
864 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
865 if (resolved_class == nullptr) {
866 return false;
867 }
868 const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
869 if (compiling_boot) {
870 // boot -> boot class pointers.
871 // True if the class is in the image at boot compiling time.
872 const bool is_image_class = IsImage() && IsImageClass(
873 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
874 // True if pc relative load works.
875 const bool support_boot_image_fixup = GetSupportBootImageFixup();
876 if (is_image_class && support_boot_image_fixup) {
877 *is_type_initialized = resolved_class->IsInitialized();
878 *use_direct_type_ptr = false;
879 *direct_type_ptr = 0;
880 return true;
881 } else {
882 return false;
883 }
884 } else {
885 // True if the class is in the image at app compiling time.
886 const bool class_in_image =
887 Runtime::Current()->GetHeap()->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
888 if (class_in_image) {
889 // boot -> app class pointers.
890 *is_type_initialized = resolved_class->IsInitialized();
891 *use_direct_type_ptr = true;
892 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
893 return true;
894 } else {
895 // app -> app class pointers.
896 // Give up because app does not have an image and class
897 // isn't created at compile time. TODO: implement this
898 // if/when each app gets an image.
899 return false;
900 }
901 }
902}
903
Brian Carlstrom7940e442013-07-12 13:46:57 -0700904static mirror::Class* ComputeCompilingMethodsClass(ScopedObjectAccess& soa,
Mathieu Chartier590fee92013-09-13 13:46:47 -0700905 SirtRef<mirror::DexCache>& dex_cache,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700906 const DexCompilationUnit* mUnit)
907 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
908 // The passed dex_cache is a hint, sanity check before asking the class linker that will take a
909 // lock.
910 if (dex_cache->GetDexFile() != mUnit->GetDexFile()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700911 dex_cache.reset(mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700912 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700913 SirtRef<mirror::ClassLoader>
914 class_loader(soa.Self(), soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
915 const DexFile::MethodId& referrer_method_id =
916 mUnit->GetDexFile()->GetMethodId(mUnit->GetDexMethodIndex());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700917 return mUnit->GetClassLinker()->ResolveType(*mUnit->GetDexFile(), referrer_method_id.class_idx_,
918 dex_cache, class_loader);
919}
920
Mathieu Chartier590fee92013-09-13 13:46:47 -0700921static mirror::ArtField* ComputeFieldReferencedFromCompilingMethod(
Vladimir Markoe549da52014-02-12 19:19:58 +0000922 ScopedObjectAccess& soa, const DexCompilationUnit* mUnit, uint32_t field_idx, bool is_static)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700923 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700924 SirtRef<mirror::DexCache> dex_cache(soa.Self(), mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
925 SirtRef<mirror::ClassLoader> class_loader(soa.Self(), soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700926 return mUnit->GetClassLinker()->ResolveField(*mUnit->GetDexFile(), field_idx, dex_cache,
Vladimir Markoe549da52014-02-12 19:19:58 +0000927 class_loader, is_static);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700928}
929
Brian Carlstromea46f952013-07-30 01:26:50 -0700930static mirror::ArtMethod* ComputeMethodReferencedFromCompilingMethod(ScopedObjectAccess& soa,
Ian Rogers65ec92c2013-09-06 10:49:58 -0700931 const DexCompilationUnit* mUnit,
932 uint32_t method_idx,
933 InvokeType type)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700934 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700935 SirtRef<mirror::DexCache> dex_cache(soa.Self(), mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
936 SirtRef<mirror::ClassLoader> class_loader(soa.Self(), soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700937 return mUnit->GetClassLinker()->ResolveMethod(*mUnit->GetDexFile(), method_idx, dex_cache,
938 class_loader, NULL, type);
939}
940
Vladimir Marko2bc47802014-02-10 09:43:07 +0000941bool CompilerDriver::ComputeSpecialAccessorInfo(uint32_t field_idx, bool is_put,
942 verifier::MethodVerifier* verifier,
943 InlineIGetIPutData* result) {
944 mirror::DexCache* dex_cache = verifier->GetDexCache();
945 uint32_t method_idx = verifier->GetMethodReference().dex_method_index;
946 mirror::ArtMethod* method = dex_cache->GetResolvedMethod(method_idx);
947 mirror::ArtField* field = dex_cache->GetResolvedField(field_idx);
Vladimir Markoc7ac6492014-02-12 10:17:09 +0000948 if (method == nullptr || field == nullptr || field->IsStatic()) {
Vladimir Marko2bc47802014-02-10 09:43:07 +0000949 return false;
950 }
951 mirror::Class* method_class = method->GetDeclaringClass();
952 mirror::Class* field_class = field->GetDeclaringClass();
953 if (!method_class->CanAccessResolvedField(field_class, field, dex_cache, field_idx) ||
954 (is_put && field->IsFinal() && method_class != field_class)) {
955 return false;
956 }
957 DCHECK_GE(field->GetOffset().Int32Value(), 0);
Vladimir Marko2bc47802014-02-10 09:43:07 +0000958 result->field_idx = field_idx;
959 result->field_offset = field->GetOffset().Int32Value();
960 result->is_volatile = field->IsVolatile();
961 return true;
962}
963
Brian Carlstrom7940e442013-07-12 13:46:57 -0700964bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
Ian Rogers9b297bf2013-09-06 11:11:25 -0700965 bool is_put, int* field_offset, bool* is_volatile) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700966 ScopedObjectAccess soa(Thread::Current());
967 // Conservative defaults.
Ian Rogers9b297bf2013-09-06 11:11:25 -0700968 *field_offset = -1;
969 *is_volatile = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700970 // Try to resolve field and ignore if an Incompatible Class Change Error (ie is static).
Vladimir Markoe549da52014-02-12 19:19:58 +0000971 mirror::ArtField* resolved_field =
972 ComputeFieldReferencedFromCompilingMethod(soa, mUnit, field_idx, false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700973 if (resolved_field != NULL && !resolved_field->IsStatic()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700974 SirtRef<mirror::DexCache> dex_cache(soa.Self(),
975 resolved_field->GetDeclaringClass()->GetDexCache());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700976 mirror::Class* referrer_class =
Mathieu Chartier590fee92013-09-13 13:46:47 -0700977 ComputeCompilingMethodsClass(soa, dex_cache, mUnit);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700978 if (referrer_class != NULL) {
979 mirror::Class* fields_class = resolved_field->GetDeclaringClass();
Vladimir Marko89786432014-01-31 15:03:55 +0000980 bool access_ok = referrer_class->CanAccessResolvedField(fields_class, resolved_field,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800981 dex_cache.get(), field_idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700982 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal() &&
983 fields_class != referrer_class;
984 if (access_ok && !is_write_to_final_from_wrong_class) {
Ian Rogers9b297bf2013-09-06 11:11:25 -0700985 *field_offset = resolved_field->GetOffset().Int32Value();
986 *is_volatile = resolved_field->IsVolatile();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700987 stats_->ResolvedInstanceField();
988 return true; // Fast path.
989 }
990 }
991 }
992 // Clean up any exception left by field/type resolution
993 if (soa.Self()->IsExceptionPending()) {
994 soa.Self()->ClearException();
995 }
996 stats_->UnresolvedInstanceField();
997 return false; // Incomplete knowledge needs slow path.
998}
999
1000bool CompilerDriver::ComputeStaticFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
Ian Rogers5ddb4102014-01-07 08:58:46 -08001001 bool is_put, int* field_offset, int* storage_index,
1002 bool* is_referrers_class, bool* is_volatile,
1003 bool* is_initialized) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001004 ScopedObjectAccess soa(Thread::Current());
1005 // Conservative defaults.
Ian Rogers9b297bf2013-09-06 11:11:25 -07001006 *field_offset = -1;
Ian Rogers5ddb4102014-01-07 08:58:46 -08001007 *storage_index = -1;
Ian Rogers9b297bf2013-09-06 11:11:25 -07001008 *is_referrers_class = false;
1009 *is_volatile = true;
Ian Rogers5ddb4102014-01-07 08:58:46 -08001010 *is_initialized = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001011 // Try to resolve field and ignore if an Incompatible Class Change Error (ie isn't static).
Vladimir Markoe549da52014-02-12 19:19:58 +00001012 mirror::ArtField* resolved_field =
1013 ComputeFieldReferencedFromCompilingMethod(soa, mUnit, field_idx, true);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001014 if (resolved_field != NULL && resolved_field->IsStatic()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001015 SirtRef<mirror::DexCache> dex_cache(soa.Self(), resolved_field->GetDeclaringClass()->GetDexCache());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001016 mirror::Class* referrer_class =
Mathieu Chartier590fee92013-09-13 13:46:47 -07001017 ComputeCompilingMethodsClass(soa, dex_cache, mUnit);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001018 if (referrer_class != NULL) {
1019 mirror::Class* fields_class = resolved_field->GetDeclaringClass();
1020 if (fields_class == referrer_class) {
Ian Rogers9b297bf2013-09-06 11:11:25 -07001021 *is_referrers_class = true; // implies no worrying about class initialization
Ian Rogers5ddb4102014-01-07 08:58:46 -08001022 *is_initialized = true;
Ian Rogers9b297bf2013-09-06 11:11:25 -07001023 *field_offset = resolved_field->GetOffset().Int32Value();
1024 *is_volatile = resolved_field->IsVolatile();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001025 stats_->ResolvedLocalStaticField();
1026 return true; // fast path
1027 } else {
Vladimir Marko89786432014-01-31 15:03:55 +00001028 bool access_ok = referrer_class->CanAccessResolvedField(fields_class, resolved_field,
Ian Rogersef7d42f2014-01-06 12:55:46 -08001029 dex_cache.get(), field_idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001030 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal();
1031 if (access_ok && !is_write_to_final_from_wrong_class) {
Ian Rogers5ddb4102014-01-07 08:58:46 -08001032 // We have the resolved field, we must make it into a index for the referrer
1033 // in its static storage (which may fail if it doesn't have a slot for it)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001034 // TODO: for images we can elide the static storage base null check
1035 // if we know there's a non-null entry in the image
1036 mirror::DexCache* dex_cache = mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile());
1037 if (fields_class->GetDexCache() == dex_cache) {
1038 // common case where the dex cache of both the referrer and the field are the same,
1039 // no need to search the dex file
Ian Rogers5ddb4102014-01-07 08:58:46 -08001040 *storage_index = fields_class->GetDexTypeIndex();
Ian Rogers9b297bf2013-09-06 11:11:25 -07001041 *field_offset = resolved_field->GetOffset().Int32Value();
1042 *is_volatile = resolved_field->IsVolatile();
Ian Rogers5ddb4102014-01-07 08:58:46 -08001043 *is_initialized = fields_class->IsInitialized() &&
1044 CanAssumeTypeIsPresentInDexCache(*mUnit->GetDexFile(), *storage_index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001045 stats_->ResolvedStaticField();
1046 return true;
1047 }
1048 // Search dex file for localized ssb index, may fail if field's class is a parent
1049 // of the class mentioned in the dex file and there is no dex cache entry.
1050 const DexFile::StringId* string_id =
1051 mUnit->GetDexFile()->FindStringId(FieldHelper(resolved_field).GetDeclaringClassDescriptor());
1052 if (string_id != NULL) {
1053 const DexFile::TypeId* type_id =
1054 mUnit->GetDexFile()->FindTypeId(mUnit->GetDexFile()->GetIndexForStringId(*string_id));
1055 if (type_id != NULL) {
1056 // medium path, needs check of static storage base being initialized
Ian Rogers5ddb4102014-01-07 08:58:46 -08001057 *storage_index = mUnit->GetDexFile()->GetIndexForTypeId(*type_id);
Ian Rogers9b297bf2013-09-06 11:11:25 -07001058 *field_offset = resolved_field->GetOffset().Int32Value();
1059 *is_volatile = resolved_field->IsVolatile();
Ian Rogers5ddb4102014-01-07 08:58:46 -08001060 *is_initialized = fields_class->IsInitialized() &&
1061 CanAssumeTypeIsPresentInDexCache(*mUnit->GetDexFile(), *storage_index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001062 stats_->ResolvedStaticField();
1063 return true;
1064 }
1065 }
1066 }
1067 }
1068 }
1069 }
1070 // Clean up any exception left by field/type resolution
1071 if (soa.Self()->IsExceptionPending()) {
1072 soa.Self()->ClearException();
1073 }
1074 stats_->UnresolvedStaticField();
1075 return false; // Incomplete knowledge needs slow path.
1076}
1077
Ian Rogers83883d72013-10-21 21:07:24 -07001078void CompilerDriver::GetCodeAndMethodForDirectCall(InvokeType* type, InvokeType sharp_type,
1079 bool no_guarantee_of_dex_cache_entry,
Brian Carlstrom7940e442013-07-12 13:46:57 -07001080 mirror::Class* referrer_class,
Brian Carlstromea46f952013-07-30 01:26:50 -07001081 mirror::ArtMethod* method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001082 bool update_stats,
Ian Rogers83883d72013-10-21 21:07:24 -07001083 MethodReference* target_method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001084 uintptr_t* direct_code,
1085 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001086 // For direct and static methods compute possible direct_code and direct_method values, ie
1087 // an address for the Method* being invoked and an address of the code for that Method*.
1088 // For interface calls compute a value for direct_method that is the interface method being
1089 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001090 *direct_code = 0;
1091 *direct_method = 0;
Ian Rogers83883d72013-10-21 21:07:24 -07001092 bool use_dex_cache = false;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001093 const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +00001094 if (compiler_backend_->IsPortable()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001095 if (sharp_type != kStatic && sharp_type != kDirect) {
1096 return;
1097 }
Ian Rogers83883d72013-10-21 21:07:24 -07001098 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001099 } else {
Jeff Hao88474b42013-10-23 16:24:40 -07001100 if (sharp_type != kStatic && sharp_type != kDirect) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001101 return;
1102 }
Ian Rogers83883d72013-10-21 21:07:24 -07001103 // TODO: support patching on all architectures.
1104 use_dex_cache = compiling_boot && !support_boot_image_fixup_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001105 }
Ian Rogers83883d72013-10-21 21:07:24 -07001106 bool method_code_in_boot = (method->GetDeclaringClass()->GetClassLoader() == nullptr);
1107 if (!use_dex_cache) {
1108 if (!method_code_in_boot) {
1109 use_dex_cache = true;
1110 } else {
1111 bool has_clinit_trampoline =
1112 method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
1113 if (has_clinit_trampoline && (method->GetDeclaringClass() != referrer_class)) {
1114 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1115 // class.
1116 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001117 }
1118 }
Ian Rogers83883d72013-10-21 21:07:24 -07001119 }
1120 if (update_stats && method_code_in_boot) {
Jeff Hao88474b42013-10-23 16:24:40 -07001121 stats_->DirectCallsToBoot(*type);
Ian Rogers83883d72013-10-21 21:07:24 -07001122 stats_->DirectMethodsToBoot(*type);
1123 }
1124 if (!use_dex_cache && compiling_boot) {
1125 MethodHelper mh(method);
Ian Rogersdfb325e2013-10-30 01:00:44 -07001126 if (!IsImageClass(mh.GetDeclaringClassDescriptor())) {
Ian Rogers83883d72013-10-21 21:07:24 -07001127 // We can only branch directly to Methods that are resolved in the DexCache.
1128 // Otherwise we won't invoke the resolution trampoline.
1129 use_dex_cache = true;
1130 }
1131 }
1132 // The method is defined not within this dex file. We need a dex cache slot within the current
1133 // dex file or direct pointers.
1134 bool must_use_direct_pointers = false;
1135 if (target_method->dex_file == method->GetDeclaringClass()->GetDexCache()->GetDexFile()) {
1136 target_method->dex_method_index = method->GetDexMethodIndex();
1137 } else {
1138 // TODO: support patching from one dex file to another in the boot image.
1139 use_dex_cache = use_dex_cache || compiling_boot;
1140 if (no_guarantee_of_dex_cache_entry) {
1141 // See if the method is also declared in this dex cache.
1142 uint32_t dex_method_idx = MethodHelper(method).FindDexMethodIndexInOtherDexFile(
Vladimir Markobbcc0c02014-02-03 14:08:42 +00001143 *target_method->dex_file, target_method->dex_method_index);
Ian Rogers83883d72013-10-21 21:07:24 -07001144 if (dex_method_idx != DexFile::kDexNoIndex) {
1145 target_method->dex_method_index = dex_method_idx;
1146 } else {
1147 must_use_direct_pointers = true;
1148 }
1149 }
1150 }
1151 if (use_dex_cache) {
1152 if (must_use_direct_pointers) {
1153 // Fail. Test above showed the only safe dispatch was via the dex cache, however, the direct
1154 // pointers are required as the dex cache lacks an appropriate entry.
1155 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1156 } else {
1157 *type = sharp_type;
1158 }
1159 } else {
1160 if (compiling_boot) {
1161 *type = sharp_type;
1162 *direct_method = -1;
Jeff Hao88474b42013-10-23 16:24:40 -07001163 *direct_code = -1;
Ian Rogers83883d72013-10-21 21:07:24 -07001164 } else {
1165 bool method_in_image =
1166 Runtime::Current()->GetHeap()->FindSpaceFromObject(method, false)->IsImageSpace();
1167 if (method_in_image) {
Jeff Hao88474b42013-10-23 16:24:40 -07001168 CHECK(!method->IsAbstract());
Ian Rogers83883d72013-10-21 21:07:24 -07001169 *type = sharp_type;
1170 *direct_method = reinterpret_cast<uintptr_t>(method);
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +00001171 *direct_code = compiler_backend_->GetEntryPointOf(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001172 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1173 target_method->dex_method_index = method->GetDexMethodIndex();
1174 } else if (!must_use_direct_pointers) {
1175 // Set the code and rely on the dex cache for the method.
1176 *type = sharp_type;
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +00001177 *direct_code = compiler_backend_->GetEntryPointOf(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001178 } else {
1179 // Direct pointers were required but none were available.
1180 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1181 }
1182 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001183 }
1184}
1185
1186bool CompilerDriver::ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001187 bool update_stats, bool enable_devirtualization,
1188 InvokeType* invoke_type, MethodReference* target_method,
1189 int* vtable_idx, uintptr_t* direct_code,
1190 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001191 ScopedObjectAccess soa(Thread::Current());
Ian Rogers65ec92c2013-09-06 10:49:58 -07001192 *vtable_idx = -1;
1193 *direct_code = 0;
1194 *direct_method = 0;
Brian Carlstromea46f952013-07-30 01:26:50 -07001195 mirror::ArtMethod* resolved_method =
Ian Rogers65ec92c2013-09-06 10:49:58 -07001196 ComputeMethodReferencedFromCompilingMethod(soa, mUnit, target_method->dex_method_index,
1197 *invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001198 if (resolved_method != NULL) {
Ian Rogers83883d72013-10-21 21:07:24 -07001199 if (*invoke_type == kVirtual || *invoke_type == kSuper) {
1200 *vtable_idx = resolved_method->GetMethodIndex();
Jeff Hao88474b42013-10-23 16:24:40 -07001201 } else if (*invoke_type == kInterface) {
1202 *vtable_idx = resolved_method->GetDexMethodIndex();
Ian Rogers83883d72013-10-21 21:07:24 -07001203 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001204 // Don't try to fast-path if we don't understand the caller's class or this appears to be an
1205 // Incompatible Class Change Error.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001206 SirtRef<mirror::DexCache> dex_cache(soa.Self(), resolved_method->GetDeclaringClass()->GetDexCache());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001207 mirror::Class* referrer_class =
Mathieu Chartier590fee92013-09-13 13:46:47 -07001208 ComputeCompilingMethodsClass(soa, dex_cache, mUnit);
Ian Rogers65ec92c2013-09-06 10:49:58 -07001209 bool icce = resolved_method->CheckIncompatibleClassChange(*invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001210 if (referrer_class != NULL && !icce) {
1211 mirror::Class* methods_class = resolved_method->GetDeclaringClass();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001212 if (referrer_class->CanAccessResolvedMethod(methods_class, resolved_method, dex_cache.get(),
1213 target_method->dex_method_index)) {
Sebastien Hertz1e54d682013-09-06 14:52:10 +02001214 const bool enableFinalBasedSharpening = enable_devirtualization;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001215 // Sharpen a virtual call into a direct call when the target is known not to have been
1216 // overridden (ie is final).
1217 bool can_sharpen_virtual_based_on_type =
Ian Rogers65ec92c2013-09-06 10:49:58 -07001218 (*invoke_type == kVirtual) && (resolved_method->IsFinal() || methods_class->IsFinal());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001219 // For invoke-super, ensure the vtable index will be correct to dispatch in the vtable of
1220 // the super class.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001221 bool can_sharpen_super_based_on_type = (*invoke_type == kSuper) &&
Brian Carlstrom7940e442013-07-12 13:46:57 -07001222 (referrer_class != methods_class) && referrer_class->IsSubClass(methods_class) &&
1223 resolved_method->GetMethodIndex() < methods_class->GetVTable()->GetLength() &&
1224 (methods_class->GetVTable()->Get(resolved_method->GetMethodIndex()) == resolved_method);
1225
Sebastien Hertz1e54d682013-09-06 14:52:10 +02001226 if (enableFinalBasedSharpening && (can_sharpen_virtual_based_on_type ||
Brian Carlstrom7940e442013-07-12 13:46:57 -07001227 can_sharpen_super_based_on_type)) {
Vladimir Marko89786432014-01-31 15:03:55 +00001228 // Sharpen a virtual call into a direct call. The method_idx is into the DexCache
1229 // associated with target_method->dex_file.
1230 CHECK(target_method->dex_file == mUnit->GetDexFile());
1231 DCHECK(dex_cache.get() == mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
1232 CHECK(dex_cache->GetResolvedMethod(target_method->dex_method_index) ==
Brian Carlstrom7940e442013-07-12 13:46:57 -07001233 resolved_method) << PrettyMethod(resolved_method);
Ian Rogers83883d72013-10-21 21:07:24 -07001234 InvokeType orig_invoke_type = *invoke_type;
1235 GetCodeAndMethodForDirectCall(invoke_type, kDirect, false, referrer_class, resolved_method,
1236 update_stats, target_method, direct_code, direct_method);
1237 if (update_stats && (*invoke_type == kDirect)) {
1238 stats_->ResolvedMethod(orig_invoke_type);
1239 stats_->VirtualMadeDirect(orig_invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001240 }
Ian Rogers83883d72013-10-21 21:07:24 -07001241 DCHECK_NE(*invoke_type, kSuper) << PrettyMethod(resolved_method);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001242 return true;
1243 }
Sebastien Hertz1e54d682013-09-06 14:52:10 +02001244 const bool enableVerifierBasedSharpening = enable_devirtualization;
Ian Rogers65ec92c2013-09-06 10:49:58 -07001245 if (enableVerifierBasedSharpening && (*invoke_type == kVirtual ||
1246 *invoke_type == kInterface)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001247 // Did the verifier record a more precise invoke target based on its type information?
Vladimir Marko2730db02014-01-27 11:15:17 +00001248 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001249 const MethodReference* devirt_map_target =
Vladimir Marko2730db02014-01-27 11:15:17 +00001250 mUnit->GetVerifiedMethod()->GetDevirtTarget(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001251 if (devirt_map_target != NULL) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001252 SirtRef<mirror::DexCache> target_dex_cache(soa.Self(), mUnit->GetClassLinker()->FindDexCache(*devirt_map_target->dex_file));
1253 SirtRef<mirror::ClassLoader> class_loader(soa.Self(), soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
Brian Carlstromea46f952013-07-30 01:26:50 -07001254 mirror::ArtMethod* called_method =
Brian Carlstrom7940e442013-07-12 13:46:57 -07001255 mUnit->GetClassLinker()->ResolveMethod(*devirt_map_target->dex_file,
1256 devirt_map_target->dex_method_index,
1257 target_dex_cache, class_loader, NULL,
1258 kVirtual);
1259 CHECK(called_method != NULL);
1260 CHECK(!called_method->IsAbstract());
Ian Rogers83883d72013-10-21 21:07:24 -07001261 InvokeType orig_invoke_type = *invoke_type;
1262 GetCodeAndMethodForDirectCall(invoke_type, kDirect, true, referrer_class, called_method,
1263 update_stats, target_method, direct_code, direct_method);
1264 if (update_stats && (*invoke_type == kDirect)) {
1265 stats_->ResolvedMethod(orig_invoke_type);
1266 stats_->VirtualMadeDirect(orig_invoke_type);
1267 stats_->PreciseTypeDevirtualization();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001268 }
Ian Rogers83883d72013-10-21 21:07:24 -07001269 DCHECK_NE(*invoke_type, kSuper);
1270 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001271 }
1272 }
Ian Rogers65ec92c2013-09-06 10:49:58 -07001273 if (*invoke_type == kSuper) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001274 // Unsharpened super calls are suspicious so go slow-path.
1275 } else {
1276 // Sharpening failed so generate a regular resolved method dispatch.
1277 if (update_stats) {
Ian Rogers65ec92c2013-09-06 10:49:58 -07001278 stats_->ResolvedMethod(*invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001279 }
Ian Rogers83883d72013-10-21 21:07:24 -07001280 GetCodeAndMethodForDirectCall(invoke_type, *invoke_type, false, referrer_class, resolved_method,
1281 update_stats, target_method, direct_code, direct_method);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001282 return true;
1283 }
1284 }
1285 }
1286 }
1287 // Clean up any exception left by method/invoke_type resolution
1288 if (soa.Self()->IsExceptionPending()) {
1289 soa.Self()->ClearException();
1290 }
1291 if (update_stats) {
Ian Rogers65ec92c2013-09-06 10:49:58 -07001292 stats_->UnresolvedMethod(*invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001293 }
1294 return false; // Incomplete knowledge needs slow path.
1295}
1296
Vladimir Marko2730db02014-01-27 11:15:17 +00001297const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1298 uint32_t method_idx) const {
1299 MethodReference ref(dex_file, method_idx);
1300 return verification_results_->GetVerifiedMethod(ref);
1301}
1302
1303bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
1304 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1305 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001306 if (result) {
1307 stats_->SafeCast();
1308 } else {
1309 stats_->NotASafeCast();
1310 }
1311 return result;
1312}
1313
1314
1315void CompilerDriver::AddCodePatch(const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001316 uint16_t referrer_class_def_idx,
1317 uint32_t referrer_method_idx,
1318 InvokeType referrer_invoke_type,
1319 uint32_t target_method_idx,
1320 InvokeType target_invoke_type,
1321 size_t literal_offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001322 MutexLock mu(Thread::Current(), compiled_methods_lock_);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001323 code_to_patch_.push_back(new CallPatchInformation(dex_file,
1324 referrer_class_def_idx,
1325 referrer_method_idx,
1326 referrer_invoke_type,
1327 target_method_idx,
1328 target_invoke_type,
1329 literal_offset));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001330}
Mark Mendell55d0eac2014-02-06 11:02:52 -08001331void CompilerDriver::AddRelativeCodePatch(const DexFile* dex_file,
1332 uint16_t referrer_class_def_idx,
1333 uint32_t referrer_method_idx,
1334 InvokeType referrer_invoke_type,
1335 uint32_t target_method_idx,
1336 InvokeType target_invoke_type,
1337 size_t literal_offset,
1338 int32_t pc_relative_offset) {
1339 MutexLock mu(Thread::Current(), compiled_methods_lock_);
1340 code_to_patch_.push_back(new RelativeCallPatchInformation(dex_file,
1341 referrer_class_def_idx,
1342 referrer_method_idx,
1343 referrer_invoke_type,
1344 target_method_idx,
1345 target_invoke_type,
1346 literal_offset,
1347 pc_relative_offset));
1348}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001349void CompilerDriver::AddMethodPatch(const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001350 uint16_t referrer_class_def_idx,
1351 uint32_t referrer_method_idx,
1352 InvokeType referrer_invoke_type,
1353 uint32_t target_method_idx,
1354 InvokeType target_invoke_type,
1355 size_t literal_offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001356 MutexLock mu(Thread::Current(), compiled_methods_lock_);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001357 methods_to_patch_.push_back(new CallPatchInformation(dex_file,
1358 referrer_class_def_idx,
1359 referrer_method_idx,
1360 referrer_invoke_type,
1361 target_method_idx,
1362 target_invoke_type,
1363 literal_offset));
1364}
1365void CompilerDriver::AddClassPatch(const DexFile* dex_file,
1366 uint16_t referrer_class_def_idx,
1367 uint32_t referrer_method_idx,
1368 uint32_t target_type_idx,
1369 size_t literal_offset) {
1370 MutexLock mu(Thread::Current(), compiled_methods_lock_);
1371 classes_to_patch_.push_back(new TypePatchInformation(dex_file,
1372 referrer_class_def_idx,
1373 referrer_method_idx,
1374 target_type_idx,
1375 literal_offset));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001376}
1377
1378class ParallelCompilationManager {
1379 public:
1380 typedef void Callback(const ParallelCompilationManager* manager, size_t index);
1381
1382 ParallelCompilationManager(ClassLinker* class_linker,
1383 jobject class_loader,
1384 CompilerDriver* compiler,
1385 const DexFile* dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001386 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001387 : index_(0),
1388 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001389 class_loader_(class_loader),
1390 compiler_(compiler),
1391 dex_file_(dex_file),
Ian Rogers3d504072014-03-01 09:16:49 -08001392 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001393
1394 ClassLinker* GetClassLinker() const {
1395 CHECK(class_linker_ != NULL);
1396 return class_linker_;
1397 }
1398
1399 jobject GetClassLoader() const {
1400 return class_loader_;
1401 }
1402
1403 CompilerDriver* GetCompiler() const {
1404 CHECK(compiler_ != NULL);
1405 return compiler_;
1406 }
1407
1408 const DexFile* GetDexFile() const {
1409 CHECK(dex_file_ != NULL);
1410 return dex_file_;
1411 }
1412
1413 void ForAll(size_t begin, size_t end, Callback callback, size_t work_units) {
1414 Thread* self = Thread::Current();
1415 self->AssertNoPendingException();
1416 CHECK_GT(work_units, 0U);
1417
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001418 index_ = begin;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001419 for (size_t i = 0; i < work_units; ++i) {
Sebastien Hertz501baec2013-12-13 12:02:36 +01001420 thread_pool_->AddTask(self, new ForAllClosure(this, end, callback));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001421 }
1422 thread_pool_->StartWorkers(self);
1423
1424 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1425 // thread destructor's called below perform join).
1426 CHECK_NE(self->GetState(), kRunnable);
1427
1428 // Wait for all the worker threads to finish.
1429 thread_pool_->Wait(self, true, false);
1430 }
1431
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001432 size_t NextIndex() {
Ian Rogersb122a4b2013-11-19 18:00:50 -08001433 return index_.FetchAndAdd(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001434 }
1435
Brian Carlstrom7940e442013-07-12 13:46:57 -07001436 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001437 class ForAllClosure : public Task {
1438 public:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001439 ForAllClosure(ParallelCompilationManager* manager, size_t end, Callback* callback)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001440 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001441 end_(end),
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001442 callback_(callback) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001443
1444 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001445 while (true) {
1446 const size_t index = manager_->NextIndex();
1447 if (UNLIKELY(index >= end_)) {
1448 break;
1449 }
1450 callback_(manager_, index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001451 self->AssertNoPendingException();
1452 }
1453 }
1454
1455 virtual void Finalize() {
1456 delete this;
1457 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001458
Brian Carlstrom7940e442013-07-12 13:46:57 -07001459 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001460 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001461 const size_t end_;
Bernhard Rosenkränzer46053622013-12-12 02:15:52 +01001462 Callback* const callback_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001463 };
1464
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001465 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001466 ClassLinker* const class_linker_;
1467 const jobject class_loader_;
1468 CompilerDriver* const compiler_;
1469 const DexFile* const dex_file_;
1470 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001471
1472 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001473};
1474
Jeff Hao0e49b422013-11-08 12:16:56 -08001475// Return true if the class should be skipped during compilation.
1476//
1477// The first case where we skip is for redundant class definitions in
1478// the boot classpath. We skip all but the first definition in that case.
1479//
1480// The second case where we skip is when an app bundles classes found
1481// in the boot classpath. Since at runtime we will select the class from
1482// the boot classpath, we ignore the one from the app.
Ian Rogersbe7149f2013-08-20 09:29:39 -07001483static bool SkipClass(ClassLinker* class_linker, jobject class_loader, const DexFile& dex_file,
1484 const DexFile::ClassDef& class_def) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001485 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001486 if (class_loader == NULL) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001487 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_linker->GetBootClassPath());
1488 CHECK(pair.second != NULL);
1489 if (pair.first != &dex_file) {
1490 LOG(WARNING) << "Skipping class " << descriptor << " from " << dex_file.GetLocation()
1491 << " previously found in " << pair.first->GetLocation();
1492 return true;
1493 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001494 return false;
1495 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07001496 return class_linker->IsInBootClassPath(descriptor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001497}
1498
Jeff Hao0e49b422013-11-08 12:16:56 -08001499// A fast version of SkipClass above if the class pointer is available
1500// that avoids the expensive FindInClassPath search.
1501static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
1502 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1503 DCHECK(klass != NULL);
1504 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1505 if (&dex_file != &original_dex_file) {
1506 if (class_loader == NULL) {
1507 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1508 << dex_file.GetLocation() << " previously found in "
1509 << original_dex_file.GetLocation();
1510 }
1511 return true;
1512 }
1513 return false;
1514}
1515
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001516static void ResolveClassFieldsAndMethods(const ParallelCompilationManager* manager,
1517 size_t class_def_index)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001518 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001519 ATRACE_CALL();
Ian Rogersbe7149f2013-08-20 09:29:39 -07001520 Thread* self = Thread::Current();
1521 jobject jclass_loader = manager->GetClassLoader();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001522 const DexFile& dex_file = *manager->GetDexFile();
Ian Rogersbe7149f2013-08-20 09:29:39 -07001523 ClassLinker* class_linker = manager->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001524
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001525 // If an instance field is final then we need to have a barrier on the return, static final
1526 // fields are assigned within the lock held for class initialization. Conservatively assume
1527 // constructor barriers are always required.
1528 bool requires_constructor_barrier = true;
1529
Brian Carlstrom7940e442013-07-12 13:46:57 -07001530 // Method and Field are the worst. We can't resolve without either
1531 // context from the code use (to disambiguate virtual vs direct
1532 // method and instance vs static field) or from class
1533 // definitions. While the compiler will resolve what it can as it
1534 // needs it, here we try to resolve fields and methods used in class
1535 // definitions, since many of them many never be referenced by
1536 // generated code.
1537 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogersbe7149f2013-08-20 09:29:39 -07001538 if (!SkipClass(class_linker, jclass_loader, dex_file, class_def)) {
Brian Carlstromcb5f5e52013-09-23 17:48:16 -07001539 ScopedObjectAccess soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001540 SirtRef<mirror::ClassLoader> class_loader(soa.Self(), soa.Decode<mirror::ClassLoader*>(jclass_loader));
1541 SirtRef<mirror::DexCache> dex_cache(soa.Self(), class_linker->FindDexCache(dex_file));
Brian Carlstromcb5f5e52013-09-23 17:48:16 -07001542 // Resolve the class.
1543 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
1544 class_loader);
Brian Carlstromcb5f5e52013-09-23 17:48:16 -07001545 bool resolve_fields_and_methods;
1546 if (klass == NULL) {
1547 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
1548 // attempt to resolve methods and fields when there is no declaring class.
1549 CHECK(soa.Self()->IsExceptionPending());
1550 soa.Self()->ClearException();
1551 resolve_fields_and_methods = false;
1552 } else {
1553 resolve_fields_and_methods = manager->GetCompiler()->IsImage();
1554 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001555 // Note the class_data pointer advances through the headers,
1556 // static fields, instance fields, direct methods, and virtual
1557 // methods.
1558 const byte* class_data = dex_file.GetClassData(class_def);
1559 if (class_data == NULL) {
1560 // Empty class such as a marker interface.
1561 requires_constructor_barrier = false;
1562 } else {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001563 ClassDataItemIterator it(dex_file, class_data);
1564 while (it.HasNextStaticField()) {
1565 if (resolve_fields_and_methods) {
1566 mirror::ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1567 dex_cache, class_loader, true);
1568 if (field == NULL) {
1569 CHECK(soa.Self()->IsExceptionPending());
1570 soa.Self()->ClearException();
1571 }
1572 }
1573 it.Next();
1574 }
1575 // We require a constructor barrier if there are final instance fields.
1576 requires_constructor_barrier = false;
1577 while (it.HasNextInstanceField()) {
1578 if ((it.GetMemberAccessFlags() & kAccFinal) != 0) {
1579 requires_constructor_barrier = true;
1580 }
1581 if (resolve_fields_and_methods) {
1582 mirror::ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1583 dex_cache, class_loader, false);
1584 if (field == NULL) {
1585 CHECK(soa.Self()->IsExceptionPending());
1586 soa.Self()->ClearException();
1587 }
1588 }
1589 it.Next();
1590 }
1591 if (resolve_fields_and_methods) {
1592 while (it.HasNextDirectMethod()) {
1593 mirror::ArtMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1594 dex_cache, class_loader, NULL,
1595 it.GetMethodInvokeType(class_def));
1596 if (method == NULL) {
1597 CHECK(soa.Self()->IsExceptionPending());
1598 soa.Self()->ClearException();
1599 }
1600 it.Next();
1601 }
1602 while (it.HasNextVirtualMethod()) {
1603 mirror::ArtMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1604 dex_cache, class_loader, NULL,
1605 it.GetMethodInvokeType(class_def));
1606 if (method == NULL) {
1607 CHECK(soa.Self()->IsExceptionPending());
1608 soa.Self()->ClearException();
1609 }
1610 it.Next();
1611 }
1612 DCHECK(!it.HasNext());
1613 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001614 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001615 }
1616 if (requires_constructor_barrier) {
Ian Rogersbe7149f2013-08-20 09:29:39 -07001617 manager->GetCompiler()->AddRequiresConstructorBarrier(self, &dex_file, class_def_index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001618 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001619}
1620
1621static void ResolveType(const ParallelCompilationManager* manager, size_t type_idx)
1622 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1623 // Class derived values are more complicated, they require the linker and loader.
1624 ScopedObjectAccess soa(Thread::Current());
1625 ClassLinker* class_linker = manager->GetClassLinker();
1626 const DexFile& dex_file = *manager->GetDexFile();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001627 SirtRef<mirror::DexCache> dex_cache(soa.Self(), class_linker->FindDexCache(dex_file));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001628 SirtRef<mirror::ClassLoader> class_loader(
1629 soa.Self(), soa.Decode<mirror::ClassLoader*>(manager->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001630 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
1631
1632 if (klass == NULL) {
1633 CHECK(soa.Self()->IsExceptionPending());
Ian Rogersa436fde2013-08-27 23:34:06 -07001634 mirror::Throwable* exception = soa.Self()->GetException(NULL);
1635 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
Ian Rogersdfb325e2013-10-30 01:00:44 -07001636 if (strcmp("Ljava/lang/OutOfMemoryError;",
1637 ClassHelper(exception->GetClass()).GetDescriptor()) == 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001638 // There's little point continuing compilation if the heap is exhausted.
1639 LOG(FATAL) << "Out of memory during type resolution for compilation";
1640 }
1641 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001642 }
1643}
1644
1645void CompilerDriver::ResolveDexFile(jobject class_loader, const DexFile& dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001646 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001647 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1648
1649 // TODO: we could resolve strings here, although the string table is largely filled with class
1650 // and method names.
1651
1652 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001653 if (IsImage()) {
1654 // For images we resolve all types, such as array, whereas for applications just those with
1655 // classdefs are resolved by ResolveClassFieldsAndMethods.
Ian Rogers3d504072014-03-01 09:16:49 -08001656 timings->NewSplit("Resolve Types");
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001657 context.ForAll(0, dex_file.NumTypeIds(), ResolveType, thread_count_);
1658 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001659
Ian Rogers3d504072014-03-01 09:16:49 -08001660 timings->NewSplit("Resolve MethodsAndFields");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001661 context.ForAll(0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001662}
1663
1664void CompilerDriver::Verify(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001665 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001666 for (size_t i = 0; i != dex_files.size(); ++i) {
1667 const DexFile* dex_file = dex_files[i];
1668 CHECK(dex_file != NULL);
1669 VerifyDexFile(class_loader, *dex_file, thread_pool, timings);
1670 }
1671}
1672
1673static void VerifyClass(const ParallelCompilationManager* manager, size_t class_def_index)
1674 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001675 ATRACE_CALL();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001676 ScopedObjectAccess soa(Thread::Current());
Jeff Hao0e49b422013-11-08 12:16:56 -08001677 const DexFile& dex_file = *manager->GetDexFile();
1678 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1679 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1680 ClassLinker* class_linker = manager->GetClassLinker();
1681 jobject jclass_loader = manager->GetClassLoader();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001682 SirtRef<mirror::ClassLoader> class_loader(
1683 soa.Self(), soa.Decode<mirror::ClassLoader*>(jclass_loader));
Ian Rogers98379392014-02-24 16:53:16 -08001684 SirtRef<mirror::Class> klass(soa.Self(), class_linker->FindClass(soa.Self(), descriptor,
1685 class_loader));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001686 if (klass.get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001687 CHECK(soa.Self()->IsExceptionPending());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001688 soa.Self()->ClearException();
1689
1690 /*
1691 * At compile time, we can still structurally verify the class even if FindClass fails.
1692 * This is to ensure the class is structurally sound for compilation. An unsound class
1693 * will be rejected by the verifier and later skipped during compilation in the compiler.
1694 */
Mathieu Chartier590fee92013-09-13 13:46:47 -07001695 SirtRef<mirror::DexCache> dex_cache(soa.Self(), class_linker->FindDexCache(dex_file));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001696 std::string error_msg;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001697 if (verifier::MethodVerifier::VerifyClass(&dex_file, dex_cache, class_loader, &class_def, true,
1698 &error_msg) ==
Brian Carlstrom7940e442013-07-12 13:46:57 -07001699 verifier::MethodVerifier::kHardFailure) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001700 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001701 << " because: " << error_msg;
1702 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001703 } else if (!SkipClass(jclass_loader, dex_file, klass.get())) {
1704 CHECK(klass->IsResolved()) << PrettyClass(klass.get());
Jeff Hao0e49b422013-11-08 12:16:56 -08001705 class_linker->VerifyClass(klass);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001706
1707 if (klass->IsErroneous()) {
1708 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1709 CHECK(soa.Self()->IsExceptionPending());
1710 soa.Self()->ClearException();
1711 }
1712
1713 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001714 << PrettyDescriptor(klass.get()) << ": state=" << klass->GetStatus();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001715 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001716 soa.Self()->AssertNoPendingException();
1717}
1718
1719void CompilerDriver::VerifyDexFile(jobject class_loader, const DexFile& dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001720 ThreadPool* thread_pool, TimingLogger* timings) {
1721 timings->NewSplit("Verify Dex File");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001722 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1723 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
1724 context.ForAll(0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001725}
1726
Brian Carlstrom7940e442013-07-12 13:46:57 -07001727static void InitializeClass(const ParallelCompilationManager* manager, size_t class_def_index)
1728 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001729 ATRACE_CALL();
Jeff Hao0e49b422013-11-08 12:16:56 -08001730 jobject jclass_loader = manager->GetClassLoader();
1731 const DexFile& dex_file = *manager->GetDexFile();
1732 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Jeff Haobcdbbfe2013-11-08 18:03:22 -08001733 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
1734 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001735
Brian Carlstrom7940e442013-07-12 13:46:57 -07001736 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001737 SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
1738 soa.Decode<mirror::ClassLoader*>(jclass_loader));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001739 SirtRef<mirror::Class> klass(soa.Self(),
Ian Rogers98379392014-02-24 16:53:16 -08001740 manager->GetClassLinker()->FindClass(soa.Self(), descriptor,
1741 class_loader));
Jeff Hao0e49b422013-11-08 12:16:56 -08001742
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001743 if (klass.get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.get())) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001744 // Only try to initialize classes that were successfully verified.
1745 if (klass->IsVerified()) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001746 // Attempt to initialize the class but bail if we either need to initialize the super-class
1747 // or static fields.
1748 manager->GetClassLinker()->EnsureInitialized(klass, false, false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001749 if (!klass->IsInitialized()) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001750 // We don't want non-trivial class initialization occurring on multiple threads due to
1751 // deadlock problems. For example, a parent class is initialized (holding its lock) that
1752 // refers to a sub-class in its static/class initializer causing it to try to acquire the
1753 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
1754 // after first initializing its parents, whose locks are acquired. This leads to a
1755 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
1756 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
1757 // than use a special Object for the purpose we use the Class of java.lang.Class.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001758 SirtRef<mirror::Class> sirt_klass(soa.Self(), klass->GetClass());
1759 ObjectLock<mirror::Class> lock(soa.Self(), &sirt_klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001760 // Attempt to initialize allowing initialization of parent classes but still not static
1761 // fields.
1762 manager->GetClassLinker()->EnsureInitialized(klass, false, true);
1763 if (!klass->IsInitialized()) {
1764 // We need to initialize static fields, we only do this for image classes that aren't
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001765 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001766 bool can_init_static_fields = manager->GetCompiler()->IsImage() &&
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001767 manager->GetCompiler()->IsImageClass(descriptor) &&
1768 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001769 if (can_init_static_fields) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001770 VLOG(compiler) << "Initializing: " << descriptor;
1771 if (strcmp("Ljava/lang/Void;", descriptor) == 0) {
1772 // Hand initialize j.l.Void to avoid Dex file operations in un-started runtime.
1773 ObjectLock<mirror::Class> lock(soa.Self(), &klass);
1774 mirror::ObjectArray<mirror::ArtField>* fields = klass->GetSFields();
1775 CHECK_EQ(fields->GetLength(), 1);
1776 fields->Get(0)->SetObj<false>(klass.get(),
1777 manager->GetClassLinker()->FindPrimitiveClass('V'));
1778 klass->SetStatus(mirror::Class::kStatusInitialized, soa.Self());
1779 } else {
1780 // TODO multithreading support. We should ensure the current compilation thread has
1781 // exclusive access to the runtime and the transaction. To achieve this, we could use
1782 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
1783 // checks in Thread::AssertThreadSuspensionIsAllowable.
1784 Runtime* const runtime = Runtime::Current();
1785 Transaction transaction;
1786
1787 // Run the class initializer in transaction mode.
1788 runtime->EnterTransactionMode(&transaction);
1789 const mirror::Class::Status old_status = klass->GetStatus();
1790 bool success = manager->GetClassLinker()->EnsureInitialized(klass, true, true);
1791 // TODO we detach transaction from runtime to indicate we quit the transactional
1792 // mode which prevents the GC from visiting objects modified during the transaction.
1793 // Ensure GC is not run so don't access freed objects when aborting transaction.
1794 const char* old_casue = soa.Self()->StartAssertNoThreadSuspension("Transaction end");
1795 runtime->ExitTransactionMode();
1796
1797 if (!success) {
1798 CHECK(soa.Self()->IsExceptionPending());
1799 ThrowLocation throw_location;
1800 mirror::Throwable* exception = soa.Self()->GetException(&throw_location);
1801 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
1802 << exception->Dump();
1803 soa.Self()->ClearException();
1804 transaction.Abort();
1805 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001806 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001807 soa.Self()->EndAssertNoThreadSuspension(old_casue);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001808 }
1809 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001810 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001811 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001812 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001813 }
1814 // Record the final class status if necessary.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001815 ClassReference ref(manager->GetDexFile(), class_def_index);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001816 manager->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001817 }
1818 // Clear any class not found or verification exceptions.
1819 soa.Self()->ClearException();
1820}
1821
1822void CompilerDriver::InitializeClasses(jobject jni_class_loader, const DexFile& dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001823 ThreadPool* thread_pool, TimingLogger* timings) {
1824 timings->NewSplit("InitializeNoClinit");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001825 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1826 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, thread_pool);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001827 size_t thread_count;
1828 if (IsImage()) {
1829 // TODO: remove this when transactional mode supports multithreading.
1830 thread_count = 1U;
1831 } else {
1832 thread_count = thread_count_;
1833 }
1834 context.ForAll(0, dex_file.NumClassDefs(), InitializeClass, thread_count);
1835 if (IsImage()) {
1836 // Prune garbage objects created during aborted transactions.
1837 Runtime::Current()->GetHeap()->CollectGarbage(true);
1838 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001839}
1840
1841void CompilerDriver::InitializeClasses(jobject class_loader,
1842 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001843 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001844 for (size_t i = 0; i != dex_files.size(); ++i) {
1845 const DexFile* dex_file = dex_files[i];
1846 CHECK(dex_file != NULL);
1847 InitializeClasses(class_loader, *dex_file, thread_pool, timings);
1848 }
1849}
1850
1851void CompilerDriver::Compile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001852 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001853 for (size_t i = 0; i != dex_files.size(); ++i) {
1854 const DexFile* dex_file = dex_files[i];
1855 CHECK(dex_file != NULL);
1856 CompileDexFile(class_loader, *dex_file, thread_pool, timings);
1857 }
1858}
1859
1860void CompilerDriver::CompileClass(const ParallelCompilationManager* manager, size_t class_def_index) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001861 ATRACE_CALL();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001862 jobject jclass_loader = manager->GetClassLoader();
1863 const DexFile& dex_file = *manager->GetDexFile();
1864 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogersbe7149f2013-08-20 09:29:39 -07001865 ClassLinker* class_linker = manager->GetClassLinker();
1866 if (SkipClass(class_linker, jclass_loader, dex_file, class_def)) {
1867 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001868 }
1869 ClassReference ref(&dex_file, class_def_index);
1870 // Skip compiling classes with generic verifier failures since they will still fail at runtime
Vladimir Markoc7f83202014-01-24 17:55:18 +00001871 if (manager->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001872 return;
1873 }
1874 const byte* class_data = dex_file.GetClassData(class_def);
1875 if (class_data == NULL) {
1876 // empty class, probably a marker interface
1877 return;
1878 }
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001879
Brian Carlstrom7940e442013-07-12 13:46:57 -07001880 // Can we run DEX-to-DEX compiler on this class ?
Sebastien Hertz75021222013-07-16 18:34:50 +02001881 DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001882 {
1883 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001884 SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
1885 soa.Decode<mirror::ClassLoader*>(jclass_loader));
Ian Rogers98379392014-02-24 16:53:16 -08001886 dex_to_dex_compilation_level = GetDexToDexCompilationlevel(soa.Self(), class_loader, dex_file,
1887 class_def);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001888 }
1889 ClassDataItemIterator it(dex_file, class_data);
1890 // Skip fields
1891 while (it.HasNextStaticField()) {
1892 it.Next();
1893 }
1894 while (it.HasNextInstanceField()) {
1895 it.Next();
1896 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07001897 CompilerDriver* driver = manager->GetCompiler();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001898 // Compile direct methods
1899 int64_t previous_direct_method_idx = -1;
1900 while (it.HasNextDirectMethod()) {
1901 uint32_t method_idx = it.GetMemberIndex();
1902 if (method_idx == previous_direct_method_idx) {
1903 // smali can create dex files with two encoded_methods sharing the same method_idx
1904 // http://code.google.com/p/smali/issues/detail?id=119
1905 it.Next();
1906 continue;
1907 }
1908 previous_direct_method_idx = method_idx;
Ian Rogersbe7149f2013-08-20 09:29:39 -07001909 driver->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1910 it.GetMethodInvokeType(class_def), class_def_index,
1911 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001912 it.Next();
1913 }
1914 // Compile virtual methods
1915 int64_t previous_virtual_method_idx = -1;
1916 while (it.HasNextVirtualMethod()) {
1917 uint32_t method_idx = it.GetMemberIndex();
1918 if (method_idx == previous_virtual_method_idx) {
1919 // smali can create dex files with two encoded_methods sharing the same method_idx
1920 // http://code.google.com/p/smali/issues/detail?id=119
1921 it.Next();
1922 continue;
1923 }
1924 previous_virtual_method_idx = method_idx;
Ian Rogersbe7149f2013-08-20 09:29:39 -07001925 driver->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1926 it.GetMethodInvokeType(class_def), class_def_index,
1927 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001928 it.Next();
1929 }
1930 DCHECK(!it.HasNext());
1931}
1932
1933void CompilerDriver::CompileDexFile(jobject class_loader, const DexFile& dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001934 ThreadPool* thread_pool, TimingLogger* timings) {
1935 timings->NewSplit("Compile Dex File");
Ian Rogersbe7149f2013-08-20 09:29:39 -07001936 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
1937 &dex_file, thread_pool);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001938 context.ForAll(0, dex_file.NumClassDefs(), CompilerDriver::CompileClass, thread_count_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001939}
1940
1941void CompilerDriver::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001942 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom7940e442013-07-12 13:46:57 -07001943 uint32_t method_idx, jobject class_loader,
1944 const DexFile& dex_file,
Sebastien Hertz75021222013-07-16 18:34:50 +02001945 DexToDexCompilationLevel dex_to_dex_compilation_level) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001946 CompiledMethod* compiled_method = NULL;
1947 uint64_t start_ns = NanoTime();
1948
1949 if ((access_flags & kAccNative) != 0) {
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +00001950 compiled_method = compiler_backend_->JniCompile(*this, access_flags, method_idx, dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001951 CHECK(compiled_method != NULL);
1952 } else if ((access_flags & kAccAbstract) != 0) {
1953 } else {
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07001954 MethodReference method_ref(&dex_file, method_idx);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001955 bool compile = verification_results_->IsCandidateForCompilation(method_ref, access_flags);
Dragos Sbirleabd136a22013-08-13 18:07:04 -07001956
Sebastien Hertz4d4adb12013-07-24 16:14:19 +02001957 if (compile) {
buzbeea024a062013-07-31 10:47:37 -07001958 // NOTE: if compiler declines to compile this method, it will return NULL.
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +00001959 compiled_method = compiler_backend_->Compile(
1960 *this, code_item, access_flags, invoke_type, class_def_idx,
1961 method_idx, class_loader, dex_file);
Sebastien Hertz75021222013-07-16 18:34:50 +02001962 } else if (dex_to_dex_compilation_level != kDontDexToDexCompile) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001963 // TODO: add a mode to disable DEX-to-DEX compilation ?
Sebastien Hertz75021222013-07-16 18:34:50 +02001964 (*dex_to_dex_compiler_)(*this, code_item, access_flags,
1965 invoke_type, class_def_idx,
1966 method_idx, class_loader, dex_file,
1967 dex_to_dex_compilation_level);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001968 }
1969 }
1970 uint64_t duration_ns = NanoTime() - start_ns;
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +00001971 if (duration_ns > MsToNs(compiler_backend_->GetMaximumCompilationTimeBeforeWarning())) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001972 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
1973 << " took " << PrettyDuration(duration_ns);
1974 }
1975
1976 Thread* self = Thread::Current();
1977 if (compiled_method != NULL) {
1978 MethodReference ref(&dex_file, method_idx);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001979 DCHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001980 {
1981 MutexLock mu(self, compiled_methods_lock_);
1982 compiled_methods_.Put(ref, compiled_method);
1983 }
1984 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
1985 }
1986
1987 if (self->IsExceptionPending()) {
1988 ScopedObjectAccess soa(self);
1989 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
1990 << self->GetException(NULL)->Dump();
1991 }
1992}
1993
1994CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
1995 MutexLock mu(Thread::Current(), compiled_classes_lock_);
1996 ClassTable::const_iterator it = compiled_classes_.find(ref);
1997 if (it == compiled_classes_.end()) {
1998 return NULL;
1999 }
2000 CHECK(it->second != NULL);
2001 return it->second;
2002}
2003
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002004void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2005 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2006 auto it = compiled_classes_.find(ref);
2007 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2008 // An entry doesn't exist or the status is lower than the new status.
2009 if (it != compiled_classes_.end()) {
2010 CHECK_GT(status, it->second->GetStatus());
2011 delete it->second;
2012 }
2013 switch (status) {
2014 case mirror::Class::kStatusNotReady:
2015 case mirror::Class::kStatusError:
2016 case mirror::Class::kStatusRetryVerificationAtRuntime:
2017 case mirror::Class::kStatusVerified:
2018 case mirror::Class::kStatusInitialized:
2019 break; // Expected states.
2020 default:
2021 LOG(FATAL) << "Unexpected class status for class "
2022 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2023 << " of " << status;
2024 }
2025 CompiledClass* compiled_class = new CompiledClass(status);
2026 compiled_classes_.Overwrite(ref, compiled_class);
2027 }
2028}
2029
Brian Carlstrom7940e442013-07-12 13:46:57 -07002030CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2031 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2032 MethodTable::const_iterator it = compiled_methods_.find(ref);
2033 if (it == compiled_methods_.end()) {
2034 return NULL;
2035 }
2036 CHECK(it->second != NULL);
2037 return it->second;
2038}
2039
Brian Carlstrom7940e442013-07-12 13:46:57 -07002040void CompilerDriver::AddRequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002041 uint16_t class_def_index) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002042 WriterMutexLock mu(self, freezing_constructor_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002043 freezing_constructor_classes_.insert(ClassReference(dex_file, class_def_index));
2044}
2045
2046bool CompilerDriver::RequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002047 uint16_t class_def_index) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002048 ReaderMutexLock mu(self, freezing_constructor_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002049 return freezing_constructor_classes_.count(ClassReference(dex_file, class_def_index)) != 0;
2050}
2051
2052bool CompilerDriver::WriteElf(const std::string& android_root,
2053 bool is_host,
2054 const std::vector<const art::DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08002055 OatWriter* oat_writer,
Brian Carlstrom7940e442013-07-12 13:46:57 -07002056 art::File* file)
2057 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +00002058 return compiler_backend_->WriteElf(file, oat_writer, dex_files, android_root, is_host, *this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002059}
2060void CompilerDriver::InstructionSetToLLVMTarget(InstructionSet instruction_set,
Ian Rogers3d504072014-03-01 09:16:49 -08002061 std::string* target_triple,
2062 std::string* target_cpu,
2063 std::string* target_attr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002064 switch (instruction_set) {
2065 case kThumb2:
Ian Rogers3d504072014-03-01 09:16:49 -08002066 *target_triple = "thumb-none-linux-gnueabi";
2067 *target_cpu = "cortex-a9";
2068 *target_attr = "+thumb2,+neon,+neonfp,+vfp3,+db";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002069 break;
2070
2071 case kArm:
Ian Rogers3d504072014-03-01 09:16:49 -08002072 *target_triple = "armv7-none-linux-gnueabi";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002073 // TODO: Fix for Nexus S.
Ian Rogers3d504072014-03-01 09:16:49 -08002074 *target_cpu = "cortex-a9";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002075 // TODO: Fix for Xoom.
Ian Rogers3d504072014-03-01 09:16:49 -08002076 *target_attr = "+v7,+neon,+neonfp,+vfp3,+db";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002077 break;
2078
2079 case kX86:
Ian Rogers3d504072014-03-01 09:16:49 -08002080 *target_triple = "i386-pc-linux-gnu";
2081 *target_attr = "";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002082 break;
2083
2084 case kMips:
Ian Rogers3d504072014-03-01 09:16:49 -08002085 *target_triple = "mipsel-unknown-linux";
2086 *target_attr = "mips32r2";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002087 break;
2088
2089 default:
2090 LOG(FATAL) << "Unknown instruction set: " << instruction_set;
2091 }
2092 }
2093} // namespace art