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