compiler_driver.cc revision 25fda92083d5b93b38cc1f6b12ac6a44d992d6a4
1/*
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
19#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <utils/Trace.h>
21
22#include <vector>
23#include <unistd.h>
24
25#ifndef __APPLE__
26#include <malloc.h>  // For mallinfo
27#endif
28
29#include "base/stl_util.h"
30#include "base/timing_logger.h"
31#include "class_linker.h"
32#include "compiled_class.h"
33#include "compiler.h"
34#include "compiler_driver-inl.h"
35#include "dex_compilation_unit.h"
36#include "dex_file-inl.h"
37#include "dex/verification_results.h"
38#include "dex/verified_method.h"
39#include "dex/quick/dex_file_method_inliner.h"
40#include "driver/compiler_options.h"
41#include "jni_internal.h"
42#include "object_lock.h"
43#include "profiler.h"
44#include "runtime.h"
45#include "gc/accounting/card_table-inl.h"
46#include "gc/accounting/heap_bitmap.h"
47#include "gc/space/space.h"
48#include "mirror/art_field-inl.h"
49#include "mirror/art_method-inl.h"
50#include "mirror/class_loader.h"
51#include "mirror/class-inl.h"
52#include "mirror/dex_cache-inl.h"
53#include "mirror/object-inl.h"
54#include "mirror/object_array-inl.h"
55#include "mirror/throwable.h"
56#include "scoped_thread_state_change.h"
57#include "ScopedLocalRef.h"
58#include "handle_scope-inl.h"
59#include "thread.h"
60#include "thread_pool.h"
61#include "trampolines/trampoline_compiler.h"
62#include "transaction.h"
63#include "verifier/method_verifier.h"
64#include "verifier/method_verifier-inl.h"
65
66namespace art {
67
68static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
69
70static double Percentage(size_t x, size_t y) {
71  return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
72}
73
74static void DumpStat(size_t x, size_t y, const char* str) {
75  if (x == 0 && y == 0) {
76    return;
77  }
78  LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
79}
80
81class CompilerDriver::AOTCompilationStats {
82 public:
83  AOTCompilationStats()
84      : stats_lock_("AOT compilation statistics lock"),
85        types_in_dex_cache_(0), types_not_in_dex_cache_(0),
86        strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
87        resolved_types_(0), unresolved_types_(0),
88        resolved_instance_fields_(0), unresolved_instance_fields_(0),
89        resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
90        type_based_devirtualization_(0),
91        safe_casts_(0), not_safe_casts_(0) {
92    for (size_t i = 0; i <= kMaxInvokeType; i++) {
93      resolved_methods_[i] = 0;
94      unresolved_methods_[i] = 0;
95      virtual_made_direct_[i] = 0;
96      direct_calls_to_boot_[i] = 0;
97      direct_methods_to_boot_[i] = 0;
98    }
99  }
100
101  void Dump() {
102    DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
103    DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
104    DumpStat(resolved_types_, unresolved_types_, "types resolved");
105    DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
106    DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
107             "static fields resolved");
108    DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
109             "static fields local to a class");
110    DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
111    // Note, the code below subtracts the stat value so that when added to the stat value we have
112    // 100% of samples. TODO: clean this up.
113    DumpStat(type_based_devirtualization_,
114             resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
115             resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
116             type_based_devirtualization_,
117             "virtual/interface calls made direct based on type information");
118
119    for (size_t i = 0; i <= kMaxInvokeType; i++) {
120      std::ostringstream oss;
121      oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
122      DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
123      if (virtual_made_direct_[i] > 0) {
124        std::ostringstream oss2;
125        oss2 << static_cast<InvokeType>(i) << " methods made direct";
126        DumpStat(virtual_made_direct_[i],
127                 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
128                 oss2.str().c_str());
129      }
130      if (direct_calls_to_boot_[i] > 0) {
131        std::ostringstream oss2;
132        oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
133        DumpStat(direct_calls_to_boot_[i],
134                 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
135                 oss2.str().c_str());
136      }
137      if (direct_methods_to_boot_[i] > 0) {
138        std::ostringstream oss2;
139        oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
140        DumpStat(direct_methods_to_boot_[i],
141                 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
142                 oss2.str().c_str());
143      }
144    }
145  }
146
147// Allow lossy statistics in non-debug builds.
148#ifndef NDEBUG
149#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
150#else
151#define STATS_LOCK()
152#endif
153
154  void TypeInDexCache() {
155    STATS_LOCK();
156    types_in_dex_cache_++;
157  }
158
159  void TypeNotInDexCache() {
160    STATS_LOCK();
161    types_not_in_dex_cache_++;
162  }
163
164  void StringInDexCache() {
165    STATS_LOCK();
166    strings_in_dex_cache_++;
167  }
168
169  void StringNotInDexCache() {
170    STATS_LOCK();
171    strings_not_in_dex_cache_++;
172  }
173
174  void TypeDoesntNeedAccessCheck() {
175    STATS_LOCK();
176    resolved_types_++;
177  }
178
179  void TypeNeedsAccessCheck() {
180    STATS_LOCK();
181    unresolved_types_++;
182  }
183
184  void ResolvedInstanceField() {
185    STATS_LOCK();
186    resolved_instance_fields_++;
187  }
188
189  void UnresolvedInstanceField() {
190    STATS_LOCK();
191    unresolved_instance_fields_++;
192  }
193
194  void ResolvedLocalStaticField() {
195    STATS_LOCK();
196    resolved_local_static_fields_++;
197  }
198
199  void ResolvedStaticField() {
200    STATS_LOCK();
201    resolved_static_fields_++;
202  }
203
204  void UnresolvedStaticField() {
205    STATS_LOCK();
206    unresolved_static_fields_++;
207  }
208
209  // Indicate that type information from the verifier led to devirtualization.
210  void PreciseTypeDevirtualization() {
211    STATS_LOCK();
212    type_based_devirtualization_++;
213  }
214
215  // Indicate that a method of the given type was resolved at compile time.
216  void ResolvedMethod(InvokeType type) {
217    DCHECK_LE(type, kMaxInvokeType);
218    STATS_LOCK();
219    resolved_methods_[type]++;
220  }
221
222  // Indicate that a method of the given type was unresolved at compile time as it was in an
223  // unknown dex file.
224  void UnresolvedMethod(InvokeType type) {
225    DCHECK_LE(type, kMaxInvokeType);
226    STATS_LOCK();
227    unresolved_methods_[type]++;
228  }
229
230  // Indicate that a type of virtual method dispatch has been converted into a direct method
231  // dispatch.
232  void VirtualMadeDirect(InvokeType type) {
233    DCHECK(type == kVirtual || type == kInterface || type == kSuper);
234    STATS_LOCK();
235    virtual_made_direct_[type]++;
236  }
237
238  // Indicate that a method of the given type was able to call directly into boot.
239  void DirectCallsToBoot(InvokeType type) {
240    DCHECK_LE(type, kMaxInvokeType);
241    STATS_LOCK();
242    direct_calls_to_boot_[type]++;
243  }
244
245  // Indicate that a method of the given type was able to be resolved directly from boot.
246  void DirectMethodsToBoot(InvokeType type) {
247    DCHECK_LE(type, kMaxInvokeType);
248    STATS_LOCK();
249    direct_methods_to_boot_[type]++;
250  }
251
252  void ProcessedInvoke(InvokeType type, int flags) {
253    STATS_LOCK();
254    if (flags == 0) {
255      unresolved_methods_[type]++;
256    } else {
257      DCHECK_NE((flags & kFlagMethodResolved), 0);
258      resolved_methods_[type]++;
259      if ((flags & kFlagVirtualMadeDirect) != 0) {
260        virtual_made_direct_[type]++;
261        if ((flags & kFlagPreciseTypeDevirtualization) != 0) {
262          type_based_devirtualization_++;
263        }
264      } else {
265        DCHECK_EQ((flags & kFlagPreciseTypeDevirtualization), 0);
266      }
267      if ((flags & kFlagDirectCallToBoot) != 0) {
268        direct_calls_to_boot_[type]++;
269      }
270      if ((flags & kFlagDirectMethodToBoot) != 0) {
271        direct_methods_to_boot_[type]++;
272      }
273    }
274  }
275
276  // A check-cast could be eliminated due to verifier type analysis.
277  void SafeCast() {
278    STATS_LOCK();
279    safe_casts_++;
280  }
281
282  // A check-cast couldn't be eliminated due to verifier type analysis.
283  void NotASafeCast() {
284    STATS_LOCK();
285    not_safe_casts_++;
286  }
287
288 private:
289  Mutex stats_lock_;
290
291  size_t types_in_dex_cache_;
292  size_t types_not_in_dex_cache_;
293
294  size_t strings_in_dex_cache_;
295  size_t strings_not_in_dex_cache_;
296
297  size_t resolved_types_;
298  size_t unresolved_types_;
299
300  size_t resolved_instance_fields_;
301  size_t unresolved_instance_fields_;
302
303  size_t resolved_local_static_fields_;
304  size_t resolved_static_fields_;
305  size_t unresolved_static_fields_;
306  // Type based devirtualization for invoke interface and virtual.
307  size_t type_based_devirtualization_;
308
309  size_t resolved_methods_[kMaxInvokeType + 1];
310  size_t unresolved_methods_[kMaxInvokeType + 1];
311  size_t virtual_made_direct_[kMaxInvokeType + 1];
312  size_t direct_calls_to_boot_[kMaxInvokeType + 1];
313  size_t direct_methods_to_boot_[kMaxInvokeType + 1];
314
315  size_t safe_casts_;
316  size_t not_safe_casts_;
317
318  DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
319};
320
321
322extern "C" art::CompiledMethod* ArtCompileDEX(art::CompilerDriver& compiler,
323                                              const art::DexFile::CodeItem* code_item,
324                                              uint32_t access_flags,
325                                              art::InvokeType invoke_type,
326                                              uint16_t class_def_idx,
327                                              uint32_t method_idx,
328                                              jobject class_loader,
329                                              const art::DexFile& dex_file);
330
331CompilerDriver::CompilerDriver(const CompilerOptions* compiler_options,
332                               VerificationResults* verification_results,
333                               DexFileToMethodInlinerMap* method_inliner_map,
334                               Compiler::Kind compiler_kind,
335                               InstructionSet instruction_set,
336                               InstructionSetFeatures instruction_set_features,
337                               bool image, std::set<std::string>* image_classes,
338                               std::set<std::string>* compiled_classes, size_t thread_count,
339                               bool dump_stats, bool dump_passes, CumulativeLogger* timer,
340                               std::string profile_file)
341    : profile_present_(false), compiler_options_(compiler_options),
342      verification_results_(verification_results),
343      method_inliner_map_(method_inliner_map),
344      compiler_(Compiler::Create(this, compiler_kind)),
345      instruction_set_(instruction_set),
346      instruction_set_features_(instruction_set_features),
347      freezing_constructor_lock_("freezing constructor lock"),
348      compiled_classes_lock_("compiled classes lock"),
349      compiled_methods_lock_("compiled method lock"),
350      image_(image),
351      image_classes_(image_classes),
352      classes_to_compile_(compiled_classes),
353      thread_count_(thread_count),
354      start_ns_(0),
355      stats_(new AOTCompilationStats),
356      dump_stats_(dump_stats),
357      dump_passes_(dump_passes),
358      timings_logger_(timer),
359      compiler_library_(nullptr),
360      compiler_context_(nullptr),
361      compiler_enable_auto_elf_loading_(nullptr),
362      compiler_get_method_code_addr_(nullptr),
363      support_boot_image_fixup_(instruction_set != kMips),
364      cfi_info_(nullptr),
365      dedupe_code_("dedupe code"),
366      dedupe_mapping_table_("dedupe mapping table"),
367      dedupe_vmap_table_("dedupe vmap table"),
368      dedupe_gc_map_("dedupe gc map"),
369      dedupe_cfi_info_("dedupe cfi info") {
370  DCHECK(compiler_options_ != nullptr);
371  DCHECK(verification_results_ != nullptr);
372  DCHECK(method_inliner_map_ != nullptr);
373
374  CHECK_PTHREAD_CALL(pthread_key_create, (&tls_key_, nullptr), "compiler tls key");
375
376  dex_to_dex_compiler_ = reinterpret_cast<DexToDexCompilerFn>(ArtCompileDEX);
377
378  compiler_->Init();
379
380  CHECK(!Runtime::Current()->IsStarted());
381  if (image_) {
382    CHECK(image_classes_.get() != nullptr);
383  } else {
384    CHECK(image_classes_.get() == nullptr);
385  }
386
387  // Are we generating CFI information?
388  if (compiler_options->GetGenerateGDBInformation()) {
389    cfi_info_.reset(compiler_->GetCallFrameInformationInitialization(*this));
390  }
391
392  // Read the profile file if one is provided.
393  if (!profile_file.empty()) {
394    profile_present_ = profile_file_.LoadFile(profile_file);
395    if (profile_present_) {
396      LOG(INFO) << "Using profile data form file " << profile_file;
397    } else {
398      LOG(INFO) << "Failed to load profile file " << profile_file;
399    }
400  }
401}
402
403std::vector<uint8_t>* CompilerDriver::DeduplicateCode(const std::vector<uint8_t>& code) {
404  return dedupe_code_.Add(Thread::Current(), code);
405}
406
407std::vector<uint8_t>* CompilerDriver::DeduplicateMappingTable(const std::vector<uint8_t>& code) {
408  return dedupe_mapping_table_.Add(Thread::Current(), code);
409}
410
411std::vector<uint8_t>* CompilerDriver::DeduplicateVMapTable(const std::vector<uint8_t>& code) {
412  return dedupe_vmap_table_.Add(Thread::Current(), code);
413}
414
415std::vector<uint8_t>* CompilerDriver::DeduplicateGCMap(const std::vector<uint8_t>& code) {
416  return dedupe_gc_map_.Add(Thread::Current(), code);
417}
418
419std::vector<uint8_t>* CompilerDriver::DeduplicateCFIInfo(const std::vector<uint8_t>* cfi_info) {
420  if (cfi_info == nullptr) {
421    return nullptr;
422  }
423  return dedupe_cfi_info_.Add(Thread::Current(), *cfi_info);
424}
425
426CompilerDriver::~CompilerDriver() {
427  Thread* self = Thread::Current();
428  {
429    MutexLock mu(self, compiled_classes_lock_);
430    STLDeleteValues(&compiled_classes_);
431    STLDeleteValues(&compiled_methods_);
432    STLDeleteElements(&code_to_patch_);
433    STLDeleteElements(&methods_to_patch_);
434    STLDeleteElements(&classes_to_patch_);
435    STLDeleteElements(&strings_to_patch_);
436  }
437  CHECK_PTHREAD_CALL(pthread_key_delete, (tls_key_), "delete tls key");
438  compiler_->UnInit();
439}
440
441CompilerTls* CompilerDriver::GetTls() {
442  // Lazily create thread-local storage
443  CompilerTls* res = static_cast<CompilerTls*>(pthread_getspecific(tls_key_));
444  if (res == nullptr) {
445    res = new CompilerTls();
446    CHECK_PTHREAD_CALL(pthread_setspecific, (tls_key_, res), "compiler tls");
447  }
448  return res;
449}
450
451#define CREATE_TRAMPOLINE(type, abi, offset) \
452    if (Is64BitInstructionSet(instruction_set_)) { \
453      return CreateTrampoline64(instruction_set_, abi, \
454                                type ## _ENTRYPOINT_OFFSET(8, offset)); \
455    } else { \
456      return CreateTrampoline32(instruction_set_, abi, \
457                                type ## _ENTRYPOINT_OFFSET(4, offset)); \
458    }
459
460const std::vector<uint8_t>* CompilerDriver::CreateInterpreterToInterpreterBridge() const {
461  CREATE_TRAMPOLINE(INTERPRETER, kInterpreterAbi, pInterpreterToInterpreterBridge)
462}
463
464const std::vector<uint8_t>* CompilerDriver::CreateInterpreterToCompiledCodeBridge() const {
465  CREATE_TRAMPOLINE(INTERPRETER, kInterpreterAbi, pInterpreterToCompiledCodeBridge)
466}
467
468const std::vector<uint8_t>* CompilerDriver::CreateJniDlsymLookup() const {
469  CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
470}
471
472const std::vector<uint8_t>* CompilerDriver::CreatePortableImtConflictTrampoline() const {
473  CREATE_TRAMPOLINE(PORTABLE, kPortableAbi, pPortableImtConflictTrampoline)
474}
475
476const std::vector<uint8_t>* CompilerDriver::CreatePortableResolutionTrampoline() const {
477  CREATE_TRAMPOLINE(PORTABLE, kPortableAbi, pPortableResolutionTrampoline)
478}
479
480const std::vector<uint8_t>* CompilerDriver::CreatePortableToInterpreterBridge() const {
481  CREATE_TRAMPOLINE(PORTABLE, kPortableAbi, pPortableToInterpreterBridge)
482}
483
484const std::vector<uint8_t>* CompilerDriver::CreateQuickGenericJniTrampoline() const {
485  CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
486}
487
488const std::vector<uint8_t>* CompilerDriver::CreateQuickImtConflictTrampoline() const {
489  CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
490}
491
492const std::vector<uint8_t>* CompilerDriver::CreateQuickResolutionTrampoline() const {
493  CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
494}
495
496const std::vector<uint8_t>* CompilerDriver::CreateQuickToInterpreterBridge() const {
497  CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
498}
499#undef CREATE_TRAMPOLINE
500
501void CompilerDriver::CompileAll(jobject class_loader,
502                                const std::vector<const DexFile*>& dex_files,
503                                TimingLogger* timings) {
504  DCHECK(!Runtime::Current()->IsStarted());
505  std::unique_ptr<ThreadPool> thread_pool(new ThreadPool("Compiler driver thread pool", thread_count_ - 1));
506  VLOG(compiler) << "Before precompile " << GetMemoryUsageString();
507  PreCompile(class_loader, dex_files, thread_pool.get(), timings);
508  Compile(class_loader, dex_files, thread_pool.get(), timings);
509  if (dump_stats_) {
510    stats_->Dump();
511  }
512}
513
514static DexToDexCompilationLevel GetDexToDexCompilationlevel(
515    Thread* self, Handle<mirror::ClassLoader> class_loader, const DexFile& dex_file,
516    const DexFile::ClassDef& class_def) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
517  const char* descriptor = dex_file.GetClassDescriptor(class_def);
518  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
519  mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
520  if (klass == nullptr) {
521    CHECK(self->IsExceptionPending());
522    self->ClearException();
523    return kDontDexToDexCompile;
524  }
525  // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
526  // references with actual offsets. We cannot re-verify such instructions.
527  //
528  // We store the verification information in the class status in the oat file, which the linker
529  // can validate (checksums) and use to skip load-time verification. It is thus safe to
530  // optimize when a class has been fully verified before.
531  if (klass->IsVerified()) {
532    // Class is verified so we can enable DEX-to-DEX compilation for performance.
533    return kOptimize;
534  } else if (klass->IsCompileTimeVerified()) {
535    // Class verification has soft-failed. Anyway, ensure at least correctness.
536    DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
537    return kRequired;
538  } else {
539    // Class verification has failed: do not run DEX-to-DEX compilation.
540    return kDontDexToDexCompile;
541  }
542}
543
544void CompilerDriver::CompileOne(mirror::ArtMethod* method, TimingLogger* timings) {
545  DCHECK(!Runtime::Current()->IsStarted());
546  Thread* self = Thread::Current();
547  jobject jclass_loader;
548  const DexFile* dex_file;
549  uint16_t class_def_idx;
550  uint32_t method_idx = method->GetDexMethodIndex();
551  uint32_t access_flags = method->GetAccessFlags();
552  InvokeType invoke_type = method->GetInvokeType();
553  {
554    ScopedObjectAccessUnchecked soa(self);
555    ScopedLocalRef<jobject>
556      local_class_loader(soa.Env(),
557                    soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
558    jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
559    // Find the dex_file
560    dex_file = method->GetDexFile();
561    class_def_idx = method->GetClassDefIndex();
562  }
563  const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
564  self->TransitionFromRunnableToSuspended(kNative);
565
566  std::vector<const DexFile*> dex_files;
567  dex_files.push_back(dex_file);
568
569  std::unique_ptr<ThreadPool> thread_pool(new ThreadPool("Compiler driver thread pool", 0U));
570  PreCompile(jclass_loader, dex_files, thread_pool.get(), timings);
571
572  // Can we run DEX-to-DEX compiler on this class ?
573  DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
574  {
575    ScopedObjectAccess soa(Thread::Current());
576    const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
577    StackHandleScope<1> hs(soa.Self());
578    Handle<mirror::ClassLoader> class_loader(
579        hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
580    dex_to_dex_compilation_level = GetDexToDexCompilationlevel(self, class_loader, *dex_file,
581                                                               class_def);
582  }
583  CompileMethod(code_item, access_flags, invoke_type, class_def_idx, method_idx, jclass_loader,
584                *dex_file, dex_to_dex_compilation_level, true);
585
586  self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
587
588  self->TransitionFromSuspendedToRunnable();
589}
590
591void CompilerDriver::Resolve(jobject class_loader, const std::vector<const DexFile*>& dex_files,
592                             ThreadPool* thread_pool, TimingLogger* timings) {
593  for (size_t i = 0; i != dex_files.size(); ++i) {
594    const DexFile* dex_file = dex_files[i];
595    CHECK(dex_file != nullptr);
596    ResolveDexFile(class_loader, *dex_file, dex_files, thread_pool, timings);
597  }
598}
599
600void CompilerDriver::PreCompile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
601                                ThreadPool* thread_pool, TimingLogger* timings) {
602  LoadImageClasses(timings);
603  VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString();
604
605  Resolve(class_loader, dex_files, thread_pool, timings);
606  VLOG(compiler) << "Resolve: " << GetMemoryUsageString();
607
608  if (!compiler_options_->IsVerificationEnabled()) {
609    VLOG(compiler) << "Verify none mode specified, skipping verification.";
610    SetVerified(class_loader, dex_files, thread_pool, timings);
611    return;
612  }
613
614  Verify(class_loader, dex_files, thread_pool, timings);
615  VLOG(compiler) << "Verify: " << GetMemoryUsageString();
616
617  InitializeClasses(class_loader, dex_files, thread_pool, timings);
618  VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString();
619
620  UpdateImageClasses(timings);
621  VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString();
622}
623
624bool CompilerDriver::IsImageClass(const char* descriptor) const {
625  if (!IsImage()) {
626    return true;
627  } else {
628    return image_classes_->find(descriptor) != image_classes_->end();
629  }
630}
631
632bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
633  if (!IsImage()) {
634    return true;
635  } else {
636    if (classes_to_compile_ == nullptr) {
637      return true;
638    }
639    return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
640  }
641}
642
643static void ResolveExceptionsForMethod(MethodHelper* mh,
644    std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve)
645    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
646  const DexFile::CodeItem* code_item = mh->GetMethod()->GetCodeItem();
647  if (code_item == nullptr) {
648    return;  // native or abstract method
649  }
650  if (code_item->tries_size_ == 0) {
651    return;  // nothing to process
652  }
653  const byte* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
654  size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
655  for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
656    int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
657    bool has_catch_all = false;
658    if (encoded_catch_handler_size <= 0) {
659      encoded_catch_handler_size = -encoded_catch_handler_size;
660      has_catch_all = true;
661    }
662    for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
663      uint16_t encoded_catch_handler_handlers_type_idx =
664          DecodeUnsignedLeb128(&encoded_catch_handler_list);
665      // Add to set of types to resolve if not already in the dex cache resolved types
666      if (!mh->GetMethod()->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
667        exceptions_to_resolve.insert(
668            std::pair<uint16_t, const DexFile*>(encoded_catch_handler_handlers_type_idx,
669                                                mh->GetMethod()->GetDexFile()));
670      }
671      // ignore address associated with catch handler
672      DecodeUnsignedLeb128(&encoded_catch_handler_list);
673    }
674    if (has_catch_all) {
675      // ignore catch all address
676      DecodeUnsignedLeb128(&encoded_catch_handler_list);
677    }
678  }
679}
680
681static bool ResolveCatchBlockExceptionsClassVisitor(mirror::Class* c, void* arg)
682    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
683  std::set<std::pair<uint16_t, const DexFile*>>* exceptions_to_resolve =
684      reinterpret_cast<std::set<std::pair<uint16_t, const DexFile*>>*>(arg);
685  StackHandleScope<1> hs(Thread::Current());
686  MethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
687  for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
688    mh.ChangeMethod(c->GetVirtualMethod(i));
689    ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
690  }
691  for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
692    mh.ChangeMethod(c->GetDirectMethod(i));
693    ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
694  }
695  return true;
696}
697
698static bool RecordImageClassesVisitor(mirror::Class* klass, void* arg)
699    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
700  std::set<std::string>* image_classes = reinterpret_cast<std::set<std::string>*>(arg);
701  std::string temp;
702  image_classes->insert(klass->GetDescriptor(&temp));
703  return true;
704}
705
706// Make a list of descriptors for classes to include in the image
707void CompilerDriver::LoadImageClasses(TimingLogger* timings)
708      LOCKS_EXCLUDED(Locks::mutator_lock_) {
709  CHECK(timings != nullptr);
710  if (!IsImage()) {
711    return;
712  }
713
714  TimingLogger::ScopedTiming t("LoadImageClasses", timings);
715  // Make a first class to load all classes explicitly listed in the file
716  Thread* self = Thread::Current();
717  ScopedObjectAccess soa(self);
718  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
719  CHECK(image_classes_.get() != nullptr);
720  for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
721    const std::string& descriptor(*it);
722    StackHandleScope<1> hs(self);
723    Handle<mirror::Class> klass(
724        hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
725    if (klass.Get() == nullptr) {
726      VLOG(compiler) << "Failed to find class " << descriptor;
727      image_classes_->erase(it++);
728      self->ClearException();
729    } else {
730      ++it;
731    }
732  }
733
734  // Resolve exception classes referenced by the loaded classes. The catch logic assumes
735  // exceptions are resolved by the verifier when there is a catch block in an interested method.
736  // Do this here so that exception classes appear to have been specified image classes.
737  std::set<std::pair<uint16_t, const DexFile*>> unresolved_exception_types;
738  StackHandleScope<1> hs(self);
739  Handle<mirror::Class> java_lang_Throwable(
740      hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
741  do {
742    unresolved_exception_types.clear();
743    class_linker->VisitClasses(ResolveCatchBlockExceptionsClassVisitor,
744                               &unresolved_exception_types);
745    for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
746      uint16_t exception_type_idx = exception_type.first;
747      const DexFile* dex_file = exception_type.second;
748      StackHandleScope<2> hs(self);
749      Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(*dex_file)));
750      Handle<mirror::Class> klass(hs.NewHandle(
751          class_linker->ResolveType(*dex_file, exception_type_idx, dex_cache,
752                                    NullHandle<mirror::ClassLoader>())));
753      if (klass.Get() == nullptr) {
754        const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
755        const char* descriptor = dex_file->GetTypeDescriptor(type_id);
756        LOG(FATAL) << "Failed to resolve class " << descriptor;
757      }
758      DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
759    }
760    // Resolving exceptions may load classes that reference more exceptions, iterate until no
761    // more are found
762  } while (!unresolved_exception_types.empty());
763
764  // We walk the roots looking for classes so that we'll pick up the
765  // above classes plus any classes them depend on such super
766  // classes, interfaces, and the required ClassLinker roots.
767  class_linker->VisitClasses(RecordImageClassesVisitor, image_classes_.get());
768
769  CHECK_NE(image_classes_->size(), 0U);
770}
771
772static void MaybeAddToImageClasses(Handle<mirror::Class> c, std::set<std::string>* image_classes)
773    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
774  Thread* self = Thread::Current();
775  StackHandleScope<1> hs(self);
776  // Make a copy of the handle so that we don't clobber it doing Assign.
777  Handle<mirror::Class> klass(hs.NewHandle(c.Get()));
778  std::string temp;
779  while (!klass->IsObjectClass()) {
780    const char* descriptor = klass->GetDescriptor(&temp);
781    std::pair<std::set<std::string>::iterator, bool> result = image_classes->insert(descriptor);
782    if (!result.second) {  // Previously inserted.
783      break;
784    }
785    VLOG(compiler) << "Adding " << descriptor << " to image classes";
786    for (size_t i = 0; i < klass->NumDirectInterfaces(); ++i) {
787      StackHandleScope<1> hs(self);
788      MaybeAddToImageClasses(hs.NewHandle(mirror::Class::GetDirectInterface(self, klass, i)),
789                             image_classes);
790    }
791    if (klass->IsArrayClass()) {
792      StackHandleScope<1> hs(self);
793      MaybeAddToImageClasses(hs.NewHandle(klass->GetComponentType()), image_classes);
794    }
795    klass.Assign(klass->GetSuperClass());
796  }
797}
798
799void CompilerDriver::FindClinitImageClassesCallback(mirror::Object* object, void* arg) {
800  DCHECK(object != nullptr);
801  DCHECK(arg != nullptr);
802  CompilerDriver* compiler_driver = reinterpret_cast<CompilerDriver*>(arg);
803  StackHandleScope<1> hs(Thread::Current());
804  MaybeAddToImageClasses(hs.NewHandle(object->GetClass()), compiler_driver->image_classes_.get());
805}
806
807void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
808  if (IsImage()) {
809    TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
810    // Update image_classes_ with classes for objects created by <clinit> methods.
811    Thread* self = Thread::Current();
812    const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
813    gc::Heap* heap = Runtime::Current()->GetHeap();
814    // TODO: Image spaces only?
815    ScopedObjectAccess soa(Thread::Current());
816    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
817    heap->VisitObjects(FindClinitImageClassesCallback, this);
818    self->EndAssertNoThreadSuspension(old_cause);
819  }
820}
821
822bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(const DexFile& dex_file, uint32_t type_idx) {
823  if (IsImage() &&
824      IsImageClass(dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_))) {
825    {
826      ScopedObjectAccess soa(Thread::Current());
827      mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
828      mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
829      if (resolved_class == nullptr) {
830        // Erroneous class.
831        stats_->TypeNotInDexCache();
832        return false;
833      }
834    }
835    stats_->TypeInDexCache();
836    return true;
837  } else {
838    stats_->TypeNotInDexCache();
839    return false;
840  }
841}
842
843bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
844                                                        uint32_t string_idx) {
845  // See also Compiler::ResolveDexFile
846
847  bool result = false;
848  if (IsImage()) {
849    // We resolve all const-string strings when building for the image.
850    ScopedObjectAccess soa(Thread::Current());
851    StackHandleScope<1> hs(soa.Self());
852    Handle<mirror::DexCache> dex_cache(
853        hs.NewHandle(Runtime::Current()->GetClassLinker()->FindDexCache(dex_file)));
854    Runtime::Current()->GetClassLinker()->ResolveString(dex_file, string_idx, dex_cache);
855    result = true;
856  }
857  if (result) {
858    stats_->StringInDexCache();
859  } else {
860    stats_->StringNotInDexCache();
861  }
862  return result;
863}
864
865bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
866                                                uint32_t type_idx,
867                                                bool* type_known_final, bool* type_known_abstract,
868                                                bool* equals_referrers_class) {
869  if (type_known_final != nullptr) {
870    *type_known_final = false;
871  }
872  if (type_known_abstract != nullptr) {
873    *type_known_abstract = false;
874  }
875  if (equals_referrers_class != nullptr) {
876    *equals_referrers_class = false;
877  }
878  ScopedObjectAccess soa(Thread::Current());
879  mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
880  // Get type from dex cache assuming it was populated by the verifier
881  mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
882  if (resolved_class == nullptr) {
883    stats_->TypeNeedsAccessCheck();
884    return false;  // Unknown class needs access checks.
885  }
886  const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
887  if (equals_referrers_class != nullptr) {
888    *equals_referrers_class = (method_id.class_idx_ == type_idx);
889  }
890  mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
891  if (referrer_class == nullptr) {
892    stats_->TypeNeedsAccessCheck();
893    return false;  // Incomplete referrer knowledge needs access check.
894  }
895  // Perform access check, will return true if access is ok or false if we're going to have to
896  // check this at runtime (for example for class loaders).
897  bool result = referrer_class->CanAccess(resolved_class);
898  if (result) {
899    stats_->TypeDoesntNeedAccessCheck();
900    if (type_known_final != nullptr) {
901      *type_known_final = resolved_class->IsFinal() && !resolved_class->IsArrayClass();
902    }
903    if (type_known_abstract != nullptr) {
904      *type_known_abstract = resolved_class->IsAbstract() && !resolved_class->IsArrayClass();
905    }
906  } else {
907    stats_->TypeNeedsAccessCheck();
908  }
909  return result;
910}
911
912bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
913                                                            const DexFile& dex_file,
914                                                            uint32_t type_idx) {
915  ScopedObjectAccess soa(Thread::Current());
916  mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
917  // Get type from dex cache assuming it was populated by the verifier.
918  mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
919  if (resolved_class == nullptr) {
920    stats_->TypeNeedsAccessCheck();
921    return false;  // Unknown class needs access checks.
922  }
923  const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
924  mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
925  if (referrer_class == nullptr) {
926    stats_->TypeNeedsAccessCheck();
927    return false;  // Incomplete referrer knowledge needs access check.
928  }
929  // Perform access and instantiable checks, will return true if access is ok or false if we're
930  // going to have to check this at runtime (for example for class loaders).
931  bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
932  if (result) {
933    stats_->TypeDoesntNeedAccessCheck();
934  } else {
935    stats_->TypeNeedsAccessCheck();
936  }
937  return result;
938}
939
940bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
941                                        bool* is_type_initialized, bool* use_direct_type_ptr,
942                                        uintptr_t* direct_type_ptr, bool* out_is_finalizable) {
943  if (GetCompilerOptions().GetCompilePic()) {
944    // Do not allow a direct class pointer to be used when compiling for position-independent
945    return false;
946  }
947  ScopedObjectAccess soa(Thread::Current());
948  mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
949  mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
950  if (resolved_class == nullptr) {
951    return false;
952  }
953  *out_is_finalizable = resolved_class->IsFinalizable();
954  const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
955  const bool support_boot_image_fixup = GetSupportBootImageFixup();
956  if (compiling_boot) {
957    // boot -> boot class pointers.
958    // True if the class is in the image at boot compiling time.
959    const bool is_image_class = IsImage() && IsImageClass(
960        dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
961    // True if pc relative load works.
962    if (is_image_class && support_boot_image_fixup) {
963      *is_type_initialized = resolved_class->IsInitialized();
964      *use_direct_type_ptr = false;
965      *direct_type_ptr = 0;
966      return true;
967    } else {
968      return false;
969    }
970  } else {
971    // True if the class is in the image at app compiling time.
972    const bool class_in_image =
973        Runtime::Current()->GetHeap()->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
974    if (class_in_image && support_boot_image_fixup) {
975      // boot -> app class pointers.
976      *is_type_initialized = resolved_class->IsInitialized();
977      // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
978      *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
979      *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
980      return true;
981    } else {
982      // app -> app class pointers.
983      // Give up because app does not have an image and class
984      // isn't created at compile time.  TODO: implement this
985      // if/when each app gets an image.
986      return false;
987    }
988  }
989}
990
991bool CompilerDriver::CanEmbedStringInCode(const DexFile& dex_file, uint32_t string_idx,
992                                          bool* use_direct_type_ptr, uintptr_t* direct_type_ptr) {
993  if (GetCompilerOptions().GetCompilePic()) {
994    // Do not allow a direct class pointer to be used when compiling for position-independent
995    return false;
996  }
997  ScopedObjectAccess soa(Thread::Current());
998  mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
999  mirror::String* resolved_string = dex_cache->GetResolvedString(string_idx);
1000  if (resolved_string == nullptr) {
1001    return false;
1002  }
1003  const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
1004  const bool support_boot_image_fixup = GetSupportBootImageFixup();
1005  if (compiling_boot) {
1006    // boot -> boot class pointers.
1007    // True if the class is in the image at boot compiling time.
1008    const bool is_image_string = IsImage();
1009    // True if pc relative load works.
1010    if (is_image_string && support_boot_image_fixup) {
1011      *use_direct_type_ptr = false;
1012      *direct_type_ptr = 0;
1013      return true;
1014    }
1015    return false;
1016  } else {
1017    // True if the class is in the image at app compiling time.
1018    const bool obj_in_image =
1019        false && Runtime::Current()->GetHeap()->FindSpaceFromObject(resolved_string, false)->IsImageSpace();
1020    if (obj_in_image && support_boot_image_fixup) {
1021      // boot -> app class pointers.
1022      // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1023      *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
1024      *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_string);
1025      return true;
1026    }
1027
1028    // app -> app class pointers.
1029    // Give up because app does not have an image and class
1030    // isn't created at compile time.  TODO: implement this
1031    // if/when each app gets an image.
1032    return false;
1033  }
1034}
1035
1036void CompilerDriver::ProcessedInstanceField(bool resolved) {
1037  if (!resolved) {
1038    stats_->UnresolvedInstanceField();
1039  } else {
1040    stats_->ResolvedInstanceField();
1041  }
1042}
1043
1044void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1045  if (!resolved) {
1046    stats_->UnresolvedStaticField();
1047  } else if (local) {
1048    stats_->ResolvedLocalStaticField();
1049  } else {
1050    stats_->ResolvedStaticField();
1051  }
1052}
1053
1054void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
1055  stats_->ProcessedInvoke(invoke_type, flags);
1056}
1057
1058mirror::ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1059                                                           const DexCompilationUnit* mUnit,
1060                                                           bool is_put,
1061                                                           const ScopedObjectAccess& soa) {
1062  // Try to resolve the field and compiling method's class.
1063  mirror::ArtField* resolved_field;
1064  mirror::Class* referrer_class;
1065  mirror::DexCache* dex_cache;
1066  {
1067    StackHandleScope<3> hs(soa.Self());
1068    Handle<mirror::DexCache> dex_cache_handle(
1069        hs.NewHandle(mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile())));
1070    Handle<mirror::ClassLoader> class_loader_handle(
1071        hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
1072    Handle<mirror::ArtField> resolved_field_handle(hs.NewHandle(
1073        ResolveField(soa, dex_cache_handle, class_loader_handle, mUnit, field_idx, false)));
1074    referrer_class = (resolved_field_handle.Get() != nullptr)
1075        ? ResolveCompilingMethodsClass(soa, dex_cache_handle, class_loader_handle, mUnit) : nullptr;
1076    resolved_field = resolved_field_handle.Get();
1077    dex_cache = dex_cache_handle.Get();
1078  }
1079  bool can_link = false;
1080  if (resolved_field != nullptr && referrer_class != nullptr) {
1081    std::pair<bool, bool> fast_path = IsFastInstanceField(
1082        dex_cache, referrer_class, resolved_field, field_idx);
1083    can_link = is_put ? fast_path.second : fast_path.first;
1084  }
1085  ProcessedInstanceField(can_link);
1086  return can_link ? resolved_field : nullptr;
1087}
1088
1089bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1090                                              bool is_put, MemberOffset* field_offset,
1091                                              bool* is_volatile) {
1092  ScopedObjectAccess soa(Thread::Current());
1093  StackHandleScope<1> hs(soa.Self());
1094  Handle<mirror::ArtField> resolved_field =
1095      hs.NewHandle(ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa));
1096
1097  if (resolved_field.Get() == nullptr) {
1098    // Conservative defaults.
1099    *is_volatile = true;
1100    *field_offset = MemberOffset(static_cast<size_t>(-1));
1101    return false;
1102  } else {
1103    *is_volatile = resolved_field->IsVolatile();
1104    *field_offset = resolved_field->GetOffset();
1105    return true;
1106  }
1107}
1108
1109bool CompilerDriver::ComputeStaticFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1110                                            bool is_put, MemberOffset* field_offset,
1111                                            uint32_t* storage_index, bool* is_referrers_class,
1112                                            bool* is_volatile, bool* is_initialized) {
1113  ScopedObjectAccess soa(Thread::Current());
1114  // Try to resolve the field and compiling method's class.
1115  mirror::ArtField* resolved_field;
1116  mirror::Class* referrer_class;
1117  mirror::DexCache* dex_cache;
1118  {
1119    StackHandleScope<3> hs(soa.Self());
1120    Handle<mirror::DexCache> dex_cache_handle(
1121        hs.NewHandle(mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile())));
1122    Handle<mirror::ClassLoader> class_loader_handle(
1123        hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
1124    Handle<mirror::ArtField> resolved_field_handle(hs.NewHandle(
1125        ResolveField(soa, dex_cache_handle, class_loader_handle, mUnit, field_idx, true)));
1126    referrer_class = (resolved_field_handle.Get() != nullptr)
1127        ? ResolveCompilingMethodsClass(soa, dex_cache_handle, class_loader_handle, mUnit) : nullptr;
1128    resolved_field = resolved_field_handle.Get();
1129    dex_cache = dex_cache_handle.Get();
1130  }
1131  bool result = false;
1132  if (resolved_field != nullptr && referrer_class != nullptr) {
1133    *is_volatile = IsFieldVolatile(resolved_field);
1134    std::pair<bool, bool> fast_path = IsFastStaticField(
1135        dex_cache, referrer_class, resolved_field, field_idx, field_offset,
1136        storage_index, is_referrers_class, is_initialized);
1137    result = is_put ? fast_path.second : fast_path.first;
1138  }
1139  if (!result) {
1140    // Conservative defaults.
1141    *is_volatile = true;
1142    *field_offset = MemberOffset(static_cast<size_t>(-1));
1143    *storage_index = -1;
1144    *is_referrers_class = false;
1145    *is_initialized = false;
1146  }
1147  ProcessedStaticField(result, *is_referrers_class);
1148  return result;
1149}
1150
1151void CompilerDriver::GetCodeAndMethodForDirectCall(InvokeType* type, InvokeType sharp_type,
1152                                                   bool no_guarantee_of_dex_cache_entry,
1153                                                   const mirror::Class* referrer_class,
1154                                                   mirror::ArtMethod* method,
1155                                                   int* stats_flags,
1156                                                   MethodReference* target_method,
1157                                                   uintptr_t* direct_code,
1158                                                   uintptr_t* direct_method) {
1159  // For direct and static methods compute possible direct_code and direct_method values, ie
1160  // an address for the Method* being invoked and an address of the code for that Method*.
1161  // For interface calls compute a value for direct_method that is the interface method being
1162  // invoked, so this can be passed to the out-of-line runtime support code.
1163  *direct_code = 0;
1164  *direct_method = 0;
1165  bool use_dex_cache = GetCompilerOptions().GetCompilePic();  // Off by default
1166  const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
1167  // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1168  const bool force_relocations = (compiling_boot ||
1169                                  GetCompilerOptions().GetIncludePatchInformation());
1170  if (compiler_->IsPortable()) {
1171    if (sharp_type != kStatic && sharp_type != kDirect) {
1172      return;
1173    }
1174    use_dex_cache = true;
1175  } else {
1176    if (sharp_type != kStatic && sharp_type != kDirect) {
1177      return;
1178    }
1179    // TODO: support patching on all architectures.
1180    use_dex_cache = use_dex_cache || (force_relocations && !support_boot_image_fixup_);
1181  }
1182  bool method_code_in_boot = (method->GetDeclaringClass()->GetClassLoader() == nullptr);
1183  if (!use_dex_cache) {
1184    if (!method_code_in_boot) {
1185      use_dex_cache = true;
1186    } else {
1187      bool has_clinit_trampoline =
1188          method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
1189      if (has_clinit_trampoline && (method->GetDeclaringClass() != referrer_class)) {
1190        // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1191        // class.
1192        use_dex_cache = true;
1193      }
1194    }
1195  }
1196  if (method_code_in_boot) {
1197    *stats_flags |= kFlagDirectCallToBoot | kFlagDirectMethodToBoot;
1198  }
1199  if (!use_dex_cache && force_relocations) {
1200    if (!IsImage() || !IsImageClass(method->GetDeclaringClassDescriptor())) {
1201      // We can only branch directly to Methods that are resolved in the DexCache.
1202      // Otherwise we won't invoke the resolution trampoline.
1203      use_dex_cache = true;
1204    }
1205  }
1206  // The method is defined not within this dex file. We need a dex cache slot within the current
1207  // dex file or direct pointers.
1208  bool must_use_direct_pointers = false;
1209  if (target_method->dex_file == method->GetDeclaringClass()->GetDexCache()->GetDexFile()) {
1210    target_method->dex_method_index = method->GetDexMethodIndex();
1211  } else {
1212    if (no_guarantee_of_dex_cache_entry) {
1213      StackHandleScope<1> hs(Thread::Current());
1214      MethodHelper mh(hs.NewHandle(method));
1215      // See if the method is also declared in this dex cache.
1216      uint32_t dex_method_idx = mh.FindDexMethodIndexInOtherDexFile(
1217          *target_method->dex_file, target_method->dex_method_index);
1218      if (dex_method_idx != DexFile::kDexNoIndex) {
1219        target_method->dex_method_index = dex_method_idx;
1220      } else {
1221        if (force_relocations && !use_dex_cache) {
1222          target_method->dex_method_index = method->GetDexMethodIndex();
1223          target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1224        }
1225        must_use_direct_pointers = true;
1226      }
1227    }
1228  }
1229  if (use_dex_cache) {
1230    if (must_use_direct_pointers) {
1231      // Fail. Test above showed the only safe dispatch was via the dex cache, however, the direct
1232      // pointers are required as the dex cache lacks an appropriate entry.
1233      VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1234    } else {
1235      *type = sharp_type;
1236    }
1237  } else {
1238    bool method_in_image =
1239        Runtime::Current()->GetHeap()->FindSpaceFromObject(method, false)->IsImageSpace();
1240    if (method_in_image || compiling_boot) {
1241      // We know we must be able to get to the method in the image, so use that pointer.
1242      CHECK(!method->IsAbstract());
1243      *type = sharp_type;
1244      *direct_method = force_relocations ? -1 : reinterpret_cast<uintptr_t>(method);
1245      *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
1246      target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1247      target_method->dex_method_index = method->GetDexMethodIndex();
1248    } else if (!must_use_direct_pointers) {
1249      // Set the code and rely on the dex cache for the method.
1250      *type = sharp_type;
1251      if (force_relocations) {
1252        *direct_code = -1;
1253        target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1254        target_method->dex_method_index = method->GetDexMethodIndex();
1255      } else {
1256        *direct_code = compiler_->GetEntryPointOf(method);
1257      }
1258    } else {
1259      // Direct pointers were required but none were available.
1260      VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1261    }
1262  }
1263}
1264
1265bool CompilerDriver::ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
1266                                       bool update_stats, bool enable_devirtualization,
1267                                       InvokeType* invoke_type, MethodReference* target_method,
1268                                       int* vtable_idx, uintptr_t* direct_code,
1269                                       uintptr_t* direct_method) {
1270  InvokeType orig_invoke_type = *invoke_type;
1271  int stats_flags = 0;
1272  ScopedObjectAccess soa(Thread::Current());
1273  // Try to resolve the method and compiling method's class.
1274  mirror::ArtMethod* resolved_method;
1275  mirror::Class* referrer_class;
1276  StackHandleScope<3> hs(soa.Self());
1277  Handle<mirror::DexCache> dex_cache(
1278      hs.NewHandle(mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile())));
1279  Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1280      soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
1281  {
1282    uint32_t method_idx = target_method->dex_method_index;
1283    Handle<mirror::ArtMethod> resolved_method_handle(hs.NewHandle(
1284        ResolveMethod(soa, dex_cache, class_loader, mUnit, method_idx, orig_invoke_type)));
1285    referrer_class = (resolved_method_handle.Get() != nullptr)
1286        ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr;
1287    resolved_method = resolved_method_handle.Get();
1288  }
1289  bool result = false;
1290  if (resolved_method != nullptr) {
1291    *vtable_idx = GetResolvedMethodVTableIndex(resolved_method, orig_invoke_type);
1292
1293    if (enable_devirtualization) {
1294      DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1295      const MethodReference* devirt_target = mUnit->GetVerifiedMethod()->GetDevirtTarget(dex_pc);
1296
1297      stats_flags = IsFastInvoke(
1298          soa, dex_cache, class_loader, mUnit, referrer_class, resolved_method,
1299          invoke_type, target_method, devirt_target, direct_code, direct_method);
1300      result = stats_flags != 0;
1301    } else {
1302      // Devirtualization not enabled. Inline IsFastInvoke(), dropping the devirtualization parts.
1303      if (UNLIKELY(referrer_class == nullptr) ||
1304          UNLIKELY(!referrer_class->CanAccessResolvedMethod(resolved_method->GetDeclaringClass(),
1305                                                            resolved_method, dex_cache.Get(),
1306                                                            target_method->dex_method_index)) ||
1307          *invoke_type == kSuper) {
1308        // Slow path. (Without devirtualization, all super calls go slow path as well.)
1309      } else {
1310        // Sharpening failed so generate a regular resolved method dispatch.
1311        stats_flags = kFlagMethodResolved;
1312        GetCodeAndMethodForDirectCall(invoke_type, *invoke_type, false, referrer_class, resolved_method,
1313                                      &stats_flags, target_method, direct_code, direct_method);
1314        result = true;
1315      }
1316    }
1317  }
1318  if (!result) {
1319    // Conservative defaults.
1320    *vtable_idx = -1;
1321    *direct_code = 0u;
1322    *direct_method = 0u;
1323  }
1324  if (update_stats) {
1325    ProcessedInvoke(orig_invoke_type, stats_flags);
1326  }
1327  return result;
1328}
1329
1330const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1331                                                        uint32_t method_idx) const {
1332  MethodReference ref(dex_file, method_idx);
1333  return verification_results_->GetVerifiedMethod(ref);
1334}
1335
1336bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
1337  if (!compiler_options_->IsVerificationEnabled()) {
1338    // If we didn't verify, every cast has to be treated as non-safe.
1339    return false;
1340  }
1341  DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1342  bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
1343  if (result) {
1344    stats_->SafeCast();
1345  } else {
1346    stats_->NotASafeCast();
1347  }
1348  return result;
1349}
1350
1351void CompilerDriver::AddCodePatch(const DexFile* dex_file,
1352                                  uint16_t referrer_class_def_idx,
1353                                  uint32_t referrer_method_idx,
1354                                  InvokeType referrer_invoke_type,
1355                                  uint32_t target_method_idx,
1356                                  const DexFile* target_dex_file,
1357                                  InvokeType target_invoke_type,
1358                                  size_t literal_offset) {
1359  MutexLock mu(Thread::Current(), compiled_methods_lock_);
1360  code_to_patch_.push_back(new CallPatchInformation(dex_file,
1361                                                    referrer_class_def_idx,
1362                                                    referrer_method_idx,
1363                                                    referrer_invoke_type,
1364                                                    target_method_idx,
1365                                                    target_dex_file,
1366                                                    target_invoke_type,
1367                                                    literal_offset));
1368}
1369void CompilerDriver::AddRelativeCodePatch(const DexFile* dex_file,
1370                                          uint16_t referrer_class_def_idx,
1371                                          uint32_t referrer_method_idx,
1372                                          InvokeType referrer_invoke_type,
1373                                          uint32_t target_method_idx,
1374                                          const DexFile* target_dex_file,
1375                                          InvokeType target_invoke_type,
1376                                          size_t literal_offset,
1377                                          int32_t pc_relative_offset) {
1378  MutexLock mu(Thread::Current(), compiled_methods_lock_);
1379  code_to_patch_.push_back(new RelativeCallPatchInformation(dex_file,
1380                                                            referrer_class_def_idx,
1381                                                            referrer_method_idx,
1382                                                            referrer_invoke_type,
1383                                                            target_method_idx,
1384                                                            target_dex_file,
1385                                                            target_invoke_type,
1386                                                            literal_offset,
1387                                                            pc_relative_offset));
1388}
1389void CompilerDriver::AddMethodPatch(const DexFile* dex_file,
1390                                    uint16_t referrer_class_def_idx,
1391                                    uint32_t referrer_method_idx,
1392                                    InvokeType referrer_invoke_type,
1393                                    uint32_t target_method_idx,
1394                                    const DexFile* target_dex_file,
1395                                    InvokeType target_invoke_type,
1396                                    size_t literal_offset) {
1397  MutexLock mu(Thread::Current(), compiled_methods_lock_);
1398  methods_to_patch_.push_back(new CallPatchInformation(dex_file,
1399                                                       referrer_class_def_idx,
1400                                                       referrer_method_idx,
1401                                                       referrer_invoke_type,
1402                                                       target_method_idx,
1403                                                       target_dex_file,
1404                                                       target_invoke_type,
1405                                                       literal_offset));
1406}
1407void CompilerDriver::AddClassPatch(const DexFile* dex_file,
1408                                    uint16_t referrer_class_def_idx,
1409                                    uint32_t referrer_method_idx,
1410                                    uint32_t target_type_idx,
1411                                    size_t literal_offset) {
1412  MutexLock mu(Thread::Current(), compiled_methods_lock_);
1413  classes_to_patch_.push_back(new TypePatchInformation(dex_file,
1414                                                       referrer_class_def_idx,
1415                                                       referrer_method_idx,
1416                                                       target_type_idx,
1417                                                       literal_offset));
1418}
1419void CompilerDriver::AddStringPatch(const DexFile* dex_file,
1420                                    uint16_t referrer_class_def_idx,
1421                                    uint32_t referrer_method_idx,
1422                                    uint32_t string_idx,
1423                                    size_t literal_offset) {
1424  MutexLock mu(Thread::Current(), compiled_methods_lock_);
1425  strings_to_patch_.push_back(new StringPatchInformation(dex_file,
1426                                                         referrer_class_def_idx,
1427                                                         referrer_method_idx,
1428                                                         string_idx,
1429                                                         literal_offset));
1430}
1431
1432class ParallelCompilationManager {
1433 public:
1434  typedef void Callback(const ParallelCompilationManager* manager, size_t index);
1435
1436  ParallelCompilationManager(ClassLinker* class_linker,
1437                             jobject class_loader,
1438                             CompilerDriver* compiler,
1439                             const DexFile* dex_file,
1440                             const std::vector<const DexFile*>& dex_files,
1441                             ThreadPool* thread_pool)
1442    : index_(0),
1443      class_linker_(class_linker),
1444      class_loader_(class_loader),
1445      compiler_(compiler),
1446      dex_file_(dex_file),
1447      dex_files_(dex_files),
1448      thread_pool_(thread_pool) {}
1449
1450  ClassLinker* GetClassLinker() const {
1451    CHECK(class_linker_ != nullptr);
1452    return class_linker_;
1453  }
1454
1455  jobject GetClassLoader() const {
1456    return class_loader_;
1457  }
1458
1459  CompilerDriver* GetCompiler() const {
1460    CHECK(compiler_ != nullptr);
1461    return compiler_;
1462  }
1463
1464  const DexFile* GetDexFile() const {
1465    CHECK(dex_file_ != nullptr);
1466    return dex_file_;
1467  }
1468
1469  const std::vector<const DexFile*>& GetDexFiles() const {
1470    return dex_files_;
1471  }
1472
1473  void ForAll(size_t begin, size_t end, Callback callback, size_t work_units) {
1474    Thread* self = Thread::Current();
1475    self->AssertNoPendingException();
1476    CHECK_GT(work_units, 0U);
1477
1478    index_.StoreRelaxed(begin);
1479    for (size_t i = 0; i < work_units; ++i) {
1480      thread_pool_->AddTask(self, new ForAllClosure(this, end, callback));
1481    }
1482    thread_pool_->StartWorkers(self);
1483
1484    // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1485    // thread destructor's called below perform join).
1486    CHECK_NE(self->GetState(), kRunnable);
1487
1488    // Wait for all the worker threads to finish.
1489    thread_pool_->Wait(self, true, false);
1490  }
1491
1492  size_t NextIndex() {
1493    return index_.FetchAndAddSequentiallyConsistent(1);
1494  }
1495
1496 private:
1497  class ForAllClosure : public Task {
1498   public:
1499    ForAllClosure(ParallelCompilationManager* manager, size_t end, Callback* callback)
1500        : manager_(manager),
1501          end_(end),
1502          callback_(callback) {}
1503
1504    virtual void Run(Thread* self) {
1505      while (true) {
1506        const size_t index = manager_->NextIndex();
1507        if (UNLIKELY(index >= end_)) {
1508          break;
1509        }
1510        callback_(manager_, index);
1511        self->AssertNoPendingException();
1512      }
1513    }
1514
1515    virtual void Finalize() {
1516      delete this;
1517    }
1518
1519   private:
1520    ParallelCompilationManager* const manager_;
1521    const size_t end_;
1522    Callback* const callback_;
1523  };
1524
1525  AtomicInteger index_;
1526  ClassLinker* const class_linker_;
1527  const jobject class_loader_;
1528  CompilerDriver* const compiler_;
1529  const DexFile* const dex_file_;
1530  const std::vector<const DexFile*>& dex_files_;
1531  ThreadPool* const thread_pool_;
1532
1533  DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
1534};
1535
1536// A fast version of SkipClass above if the class pointer is available
1537// that avoids the expensive FindInClassPath search.
1538static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
1539    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1540  DCHECK(klass != nullptr);
1541  const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1542  if (&dex_file != &original_dex_file) {
1543    if (class_loader == nullptr) {
1544      LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1545                   << dex_file.GetLocation() << " previously found in "
1546                   << original_dex_file.GetLocation();
1547    }
1548    return true;
1549  }
1550  return false;
1551}
1552
1553static void CheckAndClearResolveException(Thread* self)
1554    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1555  CHECK(self->IsExceptionPending());
1556  mirror::Throwable* exception = self->GetException(nullptr);
1557  std::string temp;
1558  const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1559  const char* expected_exceptions[] = {
1560      "Ljava/lang/IllegalAccessError;",
1561      "Ljava/lang/IncompatibleClassChangeError;",
1562      "Ljava/lang/InstantiationError;",
1563      "Ljava/lang/LinkageError;",
1564      "Ljava/lang/NoClassDefFoundError;",
1565      "Ljava/lang/NoSuchFieldError;",
1566      "Ljava/lang/NoSuchMethodError;"
1567  };
1568  bool found = false;
1569  for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1570    if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1571      found = true;
1572    }
1573  }
1574  if (!found) {
1575    LOG(FATAL) << "Unexpected exception " << exception->Dump();
1576  }
1577  self->ClearException();
1578}
1579
1580static void ResolveClassFieldsAndMethods(const ParallelCompilationManager* manager,
1581                                         size_t class_def_index)
1582    LOCKS_EXCLUDED(Locks::mutator_lock_) {
1583  ATRACE_CALL();
1584  Thread* self = Thread::Current();
1585  jobject jclass_loader = manager->GetClassLoader();
1586  const DexFile& dex_file = *manager->GetDexFile();
1587  ClassLinker* class_linker = manager->GetClassLinker();
1588
1589  // If an instance field is final then we need to have a barrier on the return, static final
1590  // fields are assigned within the lock held for class initialization. Conservatively assume
1591  // constructor barriers are always required.
1592  bool requires_constructor_barrier = true;
1593
1594  // Method and Field are the worst. We can't resolve without either
1595  // context from the code use (to disambiguate virtual vs direct
1596  // method and instance vs static field) or from class
1597  // definitions. While the compiler will resolve what it can as it
1598  // needs it, here we try to resolve fields and methods used in class
1599  // definitions, since many of them many never be referenced by
1600  // generated code.
1601  const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1602  ScopedObjectAccess soa(self);
1603  StackHandleScope<2> hs(soa.Self());
1604  Handle<mirror::ClassLoader> class_loader(
1605      hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
1606  Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(dex_file)));
1607  // Resolve the class.
1608  mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
1609                                                   class_loader);
1610  bool resolve_fields_and_methods;
1611  if (klass == nullptr) {
1612    // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
1613    // attempt to resolve methods and fields when there is no declaring class.
1614    CheckAndClearResolveException(soa.Self());
1615    resolve_fields_and_methods = false;
1616  } else {
1617    // We successfully resolved a class, should we skip it?
1618    if (SkipClass(jclass_loader, dex_file, klass)) {
1619      return;
1620    }
1621    // We want to resolve the methods and fields eagerly.
1622    resolve_fields_and_methods = true;
1623  }
1624  // Note the class_data pointer advances through the headers,
1625  // static fields, instance fields, direct methods, and virtual
1626  // methods.
1627  const byte* class_data = dex_file.GetClassData(class_def);
1628  if (class_data == nullptr) {
1629    // Empty class such as a marker interface.
1630    requires_constructor_barrier = false;
1631  } else {
1632    ClassDataItemIterator it(dex_file, class_data);
1633    while (it.HasNextStaticField()) {
1634      if (resolve_fields_and_methods) {
1635        mirror::ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1636                                                             dex_cache, class_loader, true);
1637        if (field == nullptr) {
1638          CheckAndClearResolveException(soa.Self());
1639        }
1640      }
1641      it.Next();
1642    }
1643    // We require a constructor barrier if there are final instance fields.
1644    requires_constructor_barrier = false;
1645    while (it.HasNextInstanceField()) {
1646      if (it.MemberIsFinal()) {
1647        requires_constructor_barrier = true;
1648      }
1649      if (resolve_fields_and_methods) {
1650        mirror::ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1651                                                             dex_cache, class_loader, false);
1652        if (field == nullptr) {
1653          CheckAndClearResolveException(soa.Self());
1654        }
1655      }
1656      it.Next();
1657    }
1658    if (resolve_fields_and_methods) {
1659      while (it.HasNextDirectMethod()) {
1660        mirror::ArtMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1661                                                                dex_cache, class_loader,
1662                                                                NullHandle<mirror::ArtMethod>(),
1663                                                                it.GetMethodInvokeType(class_def));
1664        if (method == nullptr) {
1665          CheckAndClearResolveException(soa.Self());
1666        }
1667        it.Next();
1668      }
1669      while (it.HasNextVirtualMethod()) {
1670        mirror::ArtMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1671                                                                dex_cache, class_loader,
1672                                                                NullHandle<mirror::ArtMethod>(),
1673                                                                it.GetMethodInvokeType(class_def));
1674        if (method == nullptr) {
1675          CheckAndClearResolveException(soa.Self());
1676        }
1677        it.Next();
1678      }
1679      DCHECK(!it.HasNext());
1680    }
1681  }
1682  if (requires_constructor_barrier) {
1683    manager->GetCompiler()->AddRequiresConstructorBarrier(self, &dex_file, class_def_index);
1684  }
1685}
1686
1687static void ResolveType(const ParallelCompilationManager* manager, size_t type_idx)
1688    LOCKS_EXCLUDED(Locks::mutator_lock_) {
1689  // Class derived values are more complicated, they require the linker and loader.
1690  ScopedObjectAccess soa(Thread::Current());
1691  ClassLinker* class_linker = manager->GetClassLinker();
1692  const DexFile& dex_file = *manager->GetDexFile();
1693  StackHandleScope<2> hs(soa.Self());
1694  Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(dex_file)));
1695  Handle<mirror::ClassLoader> class_loader(
1696      hs.NewHandle(soa.Decode<mirror::ClassLoader*>(manager->GetClassLoader())));
1697  mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
1698
1699  if (klass == nullptr) {
1700    CHECK(soa.Self()->IsExceptionPending());
1701    mirror::Throwable* exception = soa.Self()->GetException(nullptr);
1702    VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
1703    if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
1704      // There's little point continuing compilation if the heap is exhausted.
1705      LOG(FATAL) << "Out of memory during type resolution for compilation";
1706    }
1707    soa.Self()->ClearException();
1708  }
1709}
1710
1711void CompilerDriver::ResolveDexFile(jobject class_loader, const DexFile& dex_file,
1712                                    const std::vector<const DexFile*>& dex_files,
1713                                    ThreadPool* thread_pool, TimingLogger* timings) {
1714  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1715
1716  // TODO: we could resolve strings here, although the string table is largely filled with class
1717  //       and method names.
1718
1719  ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
1720                                     thread_pool);
1721  if (IsImage()) {
1722    // For images we resolve all types, such as array, whereas for applications just those with
1723    // classdefs are resolved by ResolveClassFieldsAndMethods.
1724    TimingLogger::ScopedTiming t("Resolve Types", timings);
1725    context.ForAll(0, dex_file.NumTypeIds(), ResolveType, thread_count_);
1726  }
1727
1728  TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
1729  context.ForAll(0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
1730}
1731
1732void CompilerDriver::SetVerified(jobject class_loader, const std::vector<const DexFile*>& dex_files,
1733                                 ThreadPool* thread_pool, TimingLogger* timings) {
1734  for (size_t i = 0; i != dex_files.size(); ++i) {
1735    const DexFile* dex_file = dex_files[i];
1736    CHECK(dex_file != nullptr);
1737    SetVerifiedDexFile(class_loader, *dex_file, dex_files, thread_pool, timings);
1738  }
1739}
1740
1741void CompilerDriver::Verify(jobject class_loader, const std::vector<const DexFile*>& dex_files,
1742                            ThreadPool* thread_pool, TimingLogger* timings) {
1743  for (size_t i = 0; i != dex_files.size(); ++i) {
1744    const DexFile* dex_file = dex_files[i];
1745    CHECK(dex_file != nullptr);
1746    VerifyDexFile(class_loader, *dex_file, dex_files, thread_pool, timings);
1747  }
1748}
1749
1750static void VerifyClass(const ParallelCompilationManager* manager, size_t class_def_index)
1751    LOCKS_EXCLUDED(Locks::mutator_lock_) {
1752  ATRACE_CALL();
1753  ScopedObjectAccess soa(Thread::Current());
1754  const DexFile& dex_file = *manager->GetDexFile();
1755  const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1756  const char* descriptor = dex_file.GetClassDescriptor(class_def);
1757  ClassLinker* class_linker = manager->GetClassLinker();
1758  jobject jclass_loader = manager->GetClassLoader();
1759  StackHandleScope<3> hs(soa.Self());
1760  Handle<mirror::ClassLoader> class_loader(
1761      hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
1762  Handle<mirror::Class> klass(
1763      hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
1764  if (klass.Get() == nullptr) {
1765    CHECK(soa.Self()->IsExceptionPending());
1766    soa.Self()->ClearException();
1767
1768    /*
1769     * At compile time, we can still structurally verify the class even if FindClass fails.
1770     * This is to ensure the class is structurally sound for compilation. An unsound class
1771     * will be rejected by the verifier and later skipped during compilation in the compiler.
1772     */
1773    Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(dex_file)));
1774    std::string error_msg;
1775    if (verifier::MethodVerifier::VerifyClass(&dex_file, dex_cache, class_loader, &class_def, true,
1776                                              &error_msg) ==
1777                                                  verifier::MethodVerifier::kHardFailure) {
1778      LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
1779                 << " because: " << error_msg;
1780    }
1781  } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
1782    CHECK(klass->IsResolved()) << PrettyClass(klass.Get());
1783    class_linker->VerifyClass(klass);
1784
1785    if (klass->IsErroneous()) {
1786      // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1787      CHECK(soa.Self()->IsExceptionPending());
1788      soa.Self()->ClearException();
1789    }
1790
1791    CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
1792        << PrettyDescriptor(klass.Get()) << ": state=" << klass->GetStatus();
1793  }
1794  soa.Self()->AssertNoPendingException();
1795}
1796
1797void CompilerDriver::VerifyDexFile(jobject class_loader, const DexFile& dex_file,
1798                                   const std::vector<const DexFile*>& dex_files,
1799                                   ThreadPool* thread_pool, TimingLogger* timings) {
1800  TimingLogger::ScopedTiming t("Verify Dex File", timings);
1801  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1802  ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
1803                                     thread_pool);
1804  context.ForAll(0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
1805}
1806
1807static void SetVerifiedClass(const ParallelCompilationManager* manager, size_t class_def_index)
1808    LOCKS_EXCLUDED(Locks::mutator_lock_) {
1809  ATRACE_CALL();
1810  ScopedObjectAccess soa(Thread::Current());
1811  const DexFile& dex_file = *manager->GetDexFile();
1812  const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1813  const char* descriptor = dex_file.GetClassDescriptor(class_def);
1814  ClassLinker* class_linker = manager->GetClassLinker();
1815  jobject jclass_loader = manager->GetClassLoader();
1816  StackHandleScope<3> hs(soa.Self());
1817  Handle<mirror::ClassLoader> class_loader(
1818      hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
1819  Handle<mirror::Class> klass(
1820      hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
1821  // Class might have failed resolution. Then don't set it to verified.
1822  if (klass.Get() != nullptr) {
1823    // Only do this if the class is resolved. If even resolution fails, quickening will go very,
1824    // very wrong.
1825    if (klass->IsResolved()) {
1826      if (klass->GetStatus() < mirror::Class::kStatusVerified) {
1827        ObjectLock<mirror::Class> lock(soa.Self(), klass);
1828        klass->SetStatus(mirror::Class::kStatusVerified, soa.Self());
1829      }
1830      // Record the final class status if necessary.
1831      ClassReference ref(manager->GetDexFile(), class_def_index);
1832      manager->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
1833    }
1834  } else {
1835    Thread* self = soa.Self();
1836    DCHECK(self->IsExceptionPending());
1837    self->ClearException();
1838  }
1839}
1840
1841void CompilerDriver::SetVerifiedDexFile(jobject class_loader, const DexFile& dex_file,
1842                                        const std::vector<const DexFile*>& dex_files,
1843                                        ThreadPool* thread_pool, TimingLogger* timings) {
1844  TimingLogger::ScopedTiming t("Verify Dex File", timings);
1845  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1846  ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
1847                                     thread_pool);
1848  context.ForAll(0, dex_file.NumClassDefs(), SetVerifiedClass, thread_count_);
1849}
1850
1851static void InitializeClass(const ParallelCompilationManager* manager, size_t class_def_index)
1852    LOCKS_EXCLUDED(Locks::mutator_lock_) {
1853  ATRACE_CALL();
1854  jobject jclass_loader = manager->GetClassLoader();
1855  const DexFile& dex_file = *manager->GetDexFile();
1856  const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1857  const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
1858  const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
1859
1860  ScopedObjectAccess soa(Thread::Current());
1861  StackHandleScope<3> hs(soa.Self());
1862  Handle<mirror::ClassLoader> class_loader(
1863      hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
1864  Handle<mirror::Class> klass(
1865      hs.NewHandle(manager->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
1866
1867  if (klass.Get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) {
1868    // Only try to initialize classes that were successfully verified.
1869    if (klass->IsVerified()) {
1870      // Attempt to initialize the class but bail if we either need to initialize the super-class
1871      // or static fields.
1872      manager->GetClassLinker()->EnsureInitialized(klass, false, false);
1873      if (!klass->IsInitialized()) {
1874        // We don't want non-trivial class initialization occurring on multiple threads due to
1875        // deadlock problems. For example, a parent class is initialized (holding its lock) that
1876        // refers to a sub-class in its static/class initializer causing it to try to acquire the
1877        // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
1878        // after first initializing its parents, whose locks are acquired. This leads to a
1879        // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
1880        // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
1881        // than use a special Object for the purpose we use the Class of java.lang.Class.
1882        Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
1883        ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
1884        // Attempt to initialize allowing initialization of parent classes but still not static
1885        // fields.
1886        manager->GetClassLinker()->EnsureInitialized(klass, false, true);
1887        if (!klass->IsInitialized()) {
1888          // We need to initialize static fields, we only do this for image classes that aren't
1889          // marked with the $NoPreloadHolder (which implies this should not be initialized early).
1890          bool can_init_static_fields = manager->GetCompiler()->IsImage() &&
1891              manager->GetCompiler()->IsImageClass(descriptor) &&
1892              !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
1893          if (can_init_static_fields) {
1894            VLOG(compiler) << "Initializing: " << descriptor;
1895            // TODO multithreading support. We should ensure the current compilation thread has
1896            // exclusive access to the runtime and the transaction. To achieve this, we could use
1897            // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
1898            // checks in Thread::AssertThreadSuspensionIsAllowable.
1899            Runtime* const runtime = Runtime::Current();
1900            Transaction transaction;
1901
1902            // Run the class initializer in transaction mode.
1903            runtime->EnterTransactionMode(&transaction);
1904            const mirror::Class::Status old_status = klass->GetStatus();
1905            bool success = manager->GetClassLinker()->EnsureInitialized(klass, true, true);
1906            // TODO we detach transaction from runtime to indicate we quit the transactional
1907            // mode which prevents the GC from visiting objects modified during the transaction.
1908            // Ensure GC is not run so don't access freed objects when aborting transaction.
1909            const char* old_casue = soa.Self()->StartAssertNoThreadSuspension("Transaction end");
1910            runtime->ExitTransactionMode();
1911
1912            if (!success) {
1913              CHECK(soa.Self()->IsExceptionPending());
1914              ThrowLocation throw_location;
1915              mirror::Throwable* exception = soa.Self()->GetException(&throw_location);
1916              VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
1917                  << exception->Dump();
1918              soa.Self()->ClearException();
1919              transaction.Abort();
1920              CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
1921            }
1922            soa.Self()->EndAssertNoThreadSuspension(old_casue);
1923          }
1924        }
1925        soa.Self()->AssertNoPendingException();
1926      }
1927    }
1928    // Record the final class status if necessary.
1929    ClassReference ref(manager->GetDexFile(), class_def_index);
1930    manager->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
1931  }
1932  // Clear any class not found or verification exceptions.
1933  soa.Self()->ClearException();
1934}
1935
1936void CompilerDriver::InitializeClasses(jobject jni_class_loader, const DexFile& dex_file,
1937                                       const std::vector<const DexFile*>& dex_files,
1938                                       ThreadPool* thread_pool, TimingLogger* timings) {
1939  TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
1940  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1941  ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
1942                                     thread_pool);
1943  size_t thread_count;
1944  if (IsImage()) {
1945    // TODO: remove this when transactional mode supports multithreading.
1946    thread_count = 1U;
1947  } else {
1948    thread_count = thread_count_;
1949  }
1950  context.ForAll(0, dex_file.NumClassDefs(), InitializeClass, thread_count);
1951}
1952
1953void CompilerDriver::InitializeClasses(jobject class_loader,
1954                                       const std::vector<const DexFile*>& dex_files,
1955                                       ThreadPool* thread_pool, TimingLogger* timings) {
1956  for (size_t i = 0; i != dex_files.size(); ++i) {
1957    const DexFile* dex_file = dex_files[i];
1958    CHECK(dex_file != nullptr);
1959    InitializeClasses(class_loader, *dex_file, dex_files, thread_pool, timings);
1960  }
1961  if (IsImage()) {
1962    // Prune garbage objects created during aborted transactions.
1963    Runtime::Current()->GetHeap()->CollectGarbage(true);
1964  }
1965}
1966
1967void CompilerDriver::Compile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
1968                             ThreadPool* thread_pool, TimingLogger* timings) {
1969  for (size_t i = 0; i != dex_files.size(); ++i) {
1970    const DexFile* dex_file = dex_files[i];
1971    CHECK(dex_file != nullptr);
1972    CompileDexFile(class_loader, *dex_file, dex_files, thread_pool, timings);
1973  }
1974  VLOG(compiler) << "Compile: " << GetMemoryUsageString();
1975}
1976
1977void CompilerDriver::CompileClass(const ParallelCompilationManager* manager, size_t class_def_index) {
1978  ATRACE_CALL();
1979  const DexFile& dex_file = *manager->GetDexFile();
1980  const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1981  ClassLinker* class_linker = manager->GetClassLinker();
1982  jobject jclass_loader = manager->GetClassLoader();
1983  {
1984    // Use a scoped object access to perform to the quick SkipClass check.
1985    const char* descriptor = dex_file.GetClassDescriptor(class_def);
1986    ScopedObjectAccess soa(Thread::Current());
1987    StackHandleScope<3> hs(soa.Self());
1988    Handle<mirror::ClassLoader> class_loader(
1989        hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
1990    Handle<mirror::Class> klass(
1991        hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
1992    if (klass.Get() == nullptr) {
1993      CHECK(soa.Self()->IsExceptionPending());
1994      soa.Self()->ClearException();
1995    } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
1996      return;
1997    }
1998  }
1999  ClassReference ref(&dex_file, class_def_index);
2000  // Skip compiling classes with generic verifier failures since they will still fail at runtime
2001  if (manager->GetCompiler()->verification_results_->IsClassRejected(ref)) {
2002    return;
2003  }
2004  const byte* class_data = dex_file.GetClassData(class_def);
2005  if (class_data == nullptr) {
2006    // empty class, probably a marker interface
2007    return;
2008  }
2009
2010  // Can we run DEX-to-DEX compiler on this class ?
2011  DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
2012  {
2013    ScopedObjectAccess soa(Thread::Current());
2014    StackHandleScope<1> hs(soa.Self());
2015    Handle<mirror::ClassLoader> class_loader(
2016        hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2017    dex_to_dex_compilation_level = GetDexToDexCompilationlevel(soa.Self(), class_loader, dex_file,
2018                                                               class_def);
2019  }
2020  ClassDataItemIterator it(dex_file, class_data);
2021  // Skip fields
2022  while (it.HasNextStaticField()) {
2023    it.Next();
2024  }
2025  while (it.HasNextInstanceField()) {
2026    it.Next();
2027  }
2028  CompilerDriver* driver = manager->GetCompiler();
2029
2030  bool compilation_enabled = driver->IsClassToCompile(
2031      dex_file.StringByTypeIdx(class_def.class_idx_));
2032
2033  // Compile direct methods
2034  int64_t previous_direct_method_idx = -1;
2035  while (it.HasNextDirectMethod()) {
2036    uint32_t method_idx = it.GetMemberIndex();
2037    if (method_idx == previous_direct_method_idx) {
2038      // smali can create dex files with two encoded_methods sharing the same method_idx
2039      // http://code.google.com/p/smali/issues/detail?id=119
2040      it.Next();
2041      continue;
2042    }
2043    previous_direct_method_idx = method_idx;
2044    driver->CompileMethod(it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
2045                          it.GetMethodInvokeType(class_def), class_def_index,
2046                          method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
2047                          compilation_enabled);
2048    it.Next();
2049  }
2050  // Compile virtual methods
2051  int64_t previous_virtual_method_idx = -1;
2052  while (it.HasNextVirtualMethod()) {
2053    uint32_t method_idx = it.GetMemberIndex();
2054    if (method_idx == previous_virtual_method_idx) {
2055      // smali can create dex files with two encoded_methods sharing the same method_idx
2056      // http://code.google.com/p/smali/issues/detail?id=119
2057      it.Next();
2058      continue;
2059    }
2060    previous_virtual_method_idx = method_idx;
2061    driver->CompileMethod(it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
2062                          it.GetMethodInvokeType(class_def), class_def_index,
2063                          method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
2064                          compilation_enabled);
2065    it.Next();
2066  }
2067  DCHECK(!it.HasNext());
2068}
2069
2070void CompilerDriver::CompileDexFile(jobject class_loader, const DexFile& dex_file,
2071                                    const std::vector<const DexFile*>& dex_files,
2072                                    ThreadPool* thread_pool, TimingLogger* timings) {
2073  TimingLogger::ScopedTiming t("Compile Dex File", timings);
2074  ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
2075                                     &dex_file, dex_files, thread_pool);
2076  context.ForAll(0, dex_file.NumClassDefs(), CompilerDriver::CompileClass, thread_count_);
2077}
2078
2079void CompilerDriver::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
2080                                   InvokeType invoke_type, uint16_t class_def_idx,
2081                                   uint32_t method_idx, jobject class_loader,
2082                                   const DexFile& dex_file,
2083                                   DexToDexCompilationLevel dex_to_dex_compilation_level,
2084                                   bool compilation_enabled) {
2085  CompiledMethod* compiled_method = nullptr;
2086  uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
2087  MethodReference method_ref(&dex_file, method_idx);
2088
2089  if ((access_flags & kAccNative) != 0) {
2090    // Are we interpreting only and have support for generic JNI down calls?
2091    if (!compiler_options_->IsCompilationEnabled() &&
2092        (instruction_set_ == kX86_64 || instruction_set_ == kArm64)) {
2093      // Leaving this empty will trigger the generic JNI version
2094    } else {
2095      compiled_method = compiler_->JniCompile(access_flags, method_idx, dex_file);
2096      CHECK(compiled_method != nullptr);
2097    }
2098  } else if ((access_flags & kAccAbstract) != 0) {
2099  } else {
2100    bool compile = compilation_enabled &&
2101                   verification_results_->IsCandidateForCompilation(method_ref, access_flags);
2102    if (compile) {
2103      // NOTE: if compiler declines to compile this method, it will return nullptr.
2104      compiled_method = compiler_->Compile(code_item, access_flags, invoke_type, class_def_idx,
2105                                           method_idx, class_loader, dex_file);
2106    }
2107    if (compiled_method == nullptr && dex_to_dex_compilation_level != kDontDexToDexCompile) {
2108      // TODO: add a command-line option to disable DEX-to-DEX compilation ?
2109      (*dex_to_dex_compiler_)(*this, code_item, access_flags,
2110                              invoke_type, class_def_idx,
2111                              method_idx, class_loader, dex_file,
2112                              dex_to_dex_compilation_level);
2113    }
2114  }
2115  if (kTimeCompileMethod) {
2116    uint64_t duration_ns = NanoTime() - start_ns;
2117    if (duration_ns > MsToNs(compiler_->GetMaximumCompilationTimeBeforeWarning())) {
2118      LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
2119                   << " took " << PrettyDuration(duration_ns);
2120    }
2121  }
2122
2123  Thread* self = Thread::Current();
2124  if (compiled_method != nullptr) {
2125    DCHECK(GetCompiledMethod(method_ref) == nullptr) << PrettyMethod(method_idx, dex_file);
2126    {
2127      MutexLock mu(self, compiled_methods_lock_);
2128      compiled_methods_.Put(method_ref, compiled_method);
2129    }
2130    DCHECK(GetCompiledMethod(method_ref) != nullptr) << PrettyMethod(method_idx, dex_file);
2131  }
2132
2133  // Done compiling, delete the verified method to reduce native memory usage.
2134  verification_results_->RemoveVerifiedMethod(method_ref);
2135
2136  if (self->IsExceptionPending()) {
2137    ScopedObjectAccess soa(self);
2138    LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
2139        << self->GetException(nullptr)->Dump();
2140  }
2141}
2142
2143CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
2144  MutexLock mu(Thread::Current(), compiled_classes_lock_);
2145  ClassTable::const_iterator it = compiled_classes_.find(ref);
2146  if (it == compiled_classes_.end()) {
2147    return nullptr;
2148  }
2149  CHECK(it->second != nullptr);
2150  return it->second;
2151}
2152
2153void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2154  MutexLock mu(Thread::Current(), compiled_classes_lock_);
2155  auto it = compiled_classes_.find(ref);
2156  if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2157    // An entry doesn't exist or the status is lower than the new status.
2158    if (it != compiled_classes_.end()) {
2159      CHECK_GT(status, it->second->GetStatus());
2160      delete it->second;
2161    }
2162    switch (status) {
2163      case mirror::Class::kStatusNotReady:
2164      case mirror::Class::kStatusError:
2165      case mirror::Class::kStatusRetryVerificationAtRuntime:
2166      case mirror::Class::kStatusVerified:
2167      case mirror::Class::kStatusInitialized:
2168        break;  // Expected states.
2169      default:
2170        LOG(FATAL) << "Unexpected class status for class "
2171            << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2172            << " of " << status;
2173    }
2174    CompiledClass* compiled_class = new CompiledClass(status);
2175    compiled_classes_.Overwrite(ref, compiled_class);
2176  }
2177}
2178
2179CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2180  MutexLock mu(Thread::Current(), compiled_methods_lock_);
2181  MethodTable::const_iterator it = compiled_methods_.find(ref);
2182  if (it == compiled_methods_.end()) {
2183    return nullptr;
2184  }
2185  CHECK(it->second != nullptr);
2186  return it->second;
2187}
2188
2189void CompilerDriver::AddRequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
2190                                                   uint16_t class_def_index) {
2191  WriterMutexLock mu(self, freezing_constructor_lock_);
2192  freezing_constructor_classes_.insert(ClassReference(dex_file, class_def_index));
2193}
2194
2195bool CompilerDriver::RequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
2196                                                uint16_t class_def_index) {
2197  ReaderMutexLock mu(self, freezing_constructor_lock_);
2198  return freezing_constructor_classes_.count(ClassReference(dex_file, class_def_index)) != 0;
2199}
2200
2201bool CompilerDriver::WriteElf(const std::string& android_root,
2202                              bool is_host,
2203                              const std::vector<const art::DexFile*>& dex_files,
2204                              OatWriter* oat_writer,
2205                              art::File* file)
2206    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2207  return compiler_->WriteElf(file, oat_writer, dex_files, android_root, is_host);
2208}
2209void CompilerDriver::InstructionSetToLLVMTarget(InstructionSet instruction_set,
2210                                                std::string* target_triple,
2211                                                std::string* target_cpu,
2212                                                std::string* target_attr) {
2213  switch (instruction_set) {
2214    case kThumb2:
2215      *target_triple = "thumb-none-linux-gnueabi";
2216      *target_cpu = "cortex-a9";
2217      *target_attr = "+thumb2,+neon,+neonfp,+vfp3,+db";
2218      break;
2219
2220    case kArm:
2221      *target_triple = "armv7-none-linux-gnueabi";
2222      // TODO: Fix for Nexus S.
2223      *target_cpu = "cortex-a9";
2224      // TODO: Fix for Xoom.
2225      *target_attr = "+v7,+neon,+neonfp,+vfp3,+db";
2226      break;
2227
2228    case kX86:
2229      *target_triple = "i386-pc-linux-gnu";
2230      *target_attr = "";
2231      break;
2232
2233    case kX86_64:
2234      *target_triple = "x86_64-pc-linux-gnu";
2235      *target_attr = "";
2236      break;
2237
2238    case kMips:
2239      *target_triple = "mipsel-unknown-linux";
2240      *target_attr = "mips32r2";
2241      break;
2242
2243    default:
2244      LOG(FATAL) << "Unknown instruction set: " << instruction_set;
2245    }
2246  }
2247
2248bool CompilerDriver::SkipCompilation(const std::string& method_name) {
2249  if (!profile_present_) {
2250    return false;
2251  }
2252  // First find the method in the profile file.
2253  ProfileFile::ProfileData data;
2254  if (!profile_file_.GetProfileData(&data, method_name)) {
2255    // Not in profile, no information can be determined.
2256    if (kIsDebugBuild) {
2257      VLOG(compiler) << "not compiling " << method_name << " because it's not in the profile";
2258    }
2259    return true;
2260  }
2261
2262  // Methods that comprise top_k_threshold % of the total samples will be compiled.
2263  // Compare against the start of the topK percentage bucket just in case the threshold
2264  // falls inside a bucket.
2265  bool compile = data.GetTopKUsedPercentage() - data.GetUsedPercent()
2266                 <= compiler_options_->GetTopKProfileThreshold();
2267  if (kIsDebugBuild) {
2268    if (compile) {
2269      LOG(INFO) << "compiling method " << method_name << " because its usage is part of top "
2270          << data.GetTopKUsedPercentage() << "% with a percent of " << data.GetUsedPercent() << "%"
2271          << " (topKThreshold=" << compiler_options_->GetTopKProfileThreshold() << ")";
2272    } else {
2273      VLOG(compiler) << "not compiling method " << method_name
2274          << " because it's not part of leading " << compiler_options_->GetTopKProfileThreshold()
2275          << "% samples)";
2276    }
2277  }
2278  return !compile;
2279}
2280
2281std::string CompilerDriver::GetMemoryUsageString() const {
2282  std::ostringstream oss;
2283  const ArenaPool* arena_pool = GetArenaPool();
2284  gc::Heap* heap = Runtime::Current()->GetHeap();
2285  oss << "arena alloc=" << PrettySize(arena_pool->GetBytesAllocated());
2286  oss << " java alloc=" << PrettySize(heap->GetBytesAllocated());
2287#ifdef HAVE_MALLOC_H
2288  struct mallinfo info = mallinfo();
2289  const size_t allocated_space = static_cast<size_t>(info.uordblks);
2290  const size_t free_space = static_cast<size_t>(info.fordblks);
2291  oss << " native alloc=" << PrettySize(allocated_space) << " free="
2292      << PrettySize(free_space);
2293#endif
2294  return oss.str();
2295}
2296
2297}  // namespace art
2298