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#ifndef ART_COMPILER_DRIVER_COMPILER_DRIVER_H_
18#define ART_COMPILER_DRIVER_COMPILER_DRIVER_H_
19
20#include <set>
21#include <string>
22#include <unordered_set>
23#include <vector>
24
25#include "arch/instruction_set.h"
26#include "base/arena_allocator.h"
27#include "base/bit_utils.h"
28#include "base/mutex.h"
29#include "base/timing_logger.h"
30#include "class_reference.h"
31#include "compiler.h"
32#include "dex_file.h"
33#include "driver/compiled_method_storage.h"
34#include "jit/offline_profiling_info.h"
35#include "invoke_type.h"
36#include "method_reference.h"
37#include "mirror/class.h"  // For mirror::Class::Status.
38#include "os.h"
39#include "runtime.h"
40#include "safe_map.h"
41#include "thread_pool.h"
42#include "utils/array_ref.h"
43#include "utils/dex_cache_arrays_layout.h"
44
45namespace art {
46
47namespace mirror {
48class DexCache;
49}  // namespace mirror
50
51namespace verifier {
52class MethodVerifier;
53}  // namespace verifier
54
55class BitVector;
56class CompiledClass;
57class CompiledMethod;
58class CompilerOptions;
59class DexCompilationUnit;
60class DexFileToMethodInlinerMap;
61struct InlineIGetIPutData;
62class InstructionSetFeatures;
63class ParallelCompilationManager;
64class ScopedObjectAccess;
65template <class Allocator> class SrcMap;
66class SrcMapElem;
67using SwapSrcMap = SrcMap<SwapAllocator<SrcMapElem>>;
68template<class T> class Handle;
69class TimingLogger;
70class VerificationResults;
71class VerifiedMethod;
72
73enum EntryPointCallingConvention {
74  // ABI of invocations to a method's interpreter entry point.
75  kInterpreterAbi,
76  // ABI of calls to a method's native code, only used for native methods.
77  kJniAbi,
78  // ABI of calls to a method's quick code entry point.
79  kQuickAbi
80};
81
82class CompilerDriver {
83 public:
84  // Create a compiler targeting the requested "instruction_set".
85  // "image" should be true if image specific optimizations should be
86  // enabled.  "image_classes" lets the compiler know what classes it
87  // can assume will be in the image, with null implying all available
88  // classes.
89  CompilerDriver(const CompilerOptions* compiler_options,
90                 VerificationResults* verification_results,
91                 DexFileToMethodInlinerMap* method_inliner_map,
92                 Compiler::Kind compiler_kind,
93                 InstructionSet instruction_set,
94                 const InstructionSetFeatures* instruction_set_features,
95                 bool boot_image,
96                 bool app_image,
97                 std::unordered_set<std::string>* image_classes,
98                 std::unordered_set<std::string>* compiled_classes,
99                 std::unordered_set<std::string>* compiled_methods,
100                 size_t thread_count,
101                 bool dump_stats,
102                 bool dump_passes,
103                 CumulativeLogger* timer,
104                 int swap_fd,
105                 const ProfileCompilationInfo* profile_compilation_info);
106
107  ~CompilerDriver();
108
109  // Set dex files that will be stored in the oat file after being compiled.
110  void SetDexFilesForOatFile(const std::vector<const DexFile*>& dex_files) {
111    dex_files_for_oat_file_ = &dex_files;
112  }
113
114  // Get dex file that will be stored in the oat file after being compiled.
115  ArrayRef<const DexFile* const> GetDexFilesForOatFile() const {
116    return (dex_files_for_oat_file_ != nullptr)
117        ? ArrayRef<const DexFile* const>(*dex_files_for_oat_file_)
118        : ArrayRef<const DexFile* const>();
119  }
120
121  void CompileAll(jobject class_loader,
122                  const std::vector<const DexFile*>& dex_files,
123                  TimingLogger* timings)
124      REQUIRES(!Locks::mutator_lock_, !compiled_classes_lock_, !dex_to_dex_references_lock_);
125
126  // Compile a single Method.
127  void CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings)
128      SHARED_REQUIRES(Locks::mutator_lock_)
129      REQUIRES(!compiled_methods_lock_, !compiled_classes_lock_, !dex_to_dex_references_lock_);
130
131  VerificationResults* GetVerificationResults() const {
132    DCHECK(Runtime::Current()->IsAotCompiler());
133    return verification_results_;
134  }
135
136  DexFileToMethodInlinerMap* GetMethodInlinerMap() const {
137    return method_inliner_map_;
138  }
139
140  InstructionSet GetInstructionSet() const {
141    return instruction_set_;
142  }
143
144  const InstructionSetFeatures* GetInstructionSetFeatures() const {
145    return instruction_set_features_;
146  }
147
148  const CompilerOptions& GetCompilerOptions() const {
149    return *compiler_options_;
150  }
151
152  Compiler* GetCompiler() const {
153    return compiler_.get();
154  }
155
156  // Are we compiling and creating an image file?
157  bool IsBootImage() const {
158    return boot_image_;
159  }
160
161  const std::unordered_set<std::string>* GetImageClasses() const {
162    return image_classes_.get();
163  }
164
165  // Generate the trampolines that are invoked by unresolved direct methods.
166  std::unique_ptr<const std::vector<uint8_t>> CreateJniDlsymLookup() const;
167  std::unique_ptr<const std::vector<uint8_t>> CreateQuickGenericJniTrampoline() const;
168  std::unique_ptr<const std::vector<uint8_t>> CreateQuickImtConflictTrampoline() const;
169  std::unique_ptr<const std::vector<uint8_t>> CreateQuickResolutionTrampoline() const;
170  std::unique_ptr<const std::vector<uint8_t>> CreateQuickToInterpreterBridge() const;
171
172  CompiledClass* GetCompiledClass(ClassReference ref) const
173      REQUIRES(!compiled_classes_lock_);
174
175  CompiledMethod* GetCompiledMethod(MethodReference ref) const
176      REQUIRES(!compiled_methods_lock_);
177  size_t GetNonRelativeLinkerPatchCount() const
178      REQUIRES(!compiled_methods_lock_);
179
180  // Add a compiled method.
181  void AddCompiledMethod(const MethodReference& method_ref,
182                         CompiledMethod* const compiled_method,
183                         size_t non_relative_linker_patch_count)
184      REQUIRES(!compiled_methods_lock_);
185  // Remove and delete a compiled method.
186  void RemoveCompiledMethod(const MethodReference& method_ref) REQUIRES(!compiled_methods_lock_);
187
188  void SetRequiresConstructorBarrier(Thread* self,
189                                     const DexFile* dex_file,
190                                     uint16_t class_def_index,
191                                     bool requires)
192      REQUIRES(!requires_constructor_barrier_lock_);
193  bool RequiresConstructorBarrier(Thread* self,
194                                  const DexFile* dex_file,
195                                  uint16_t class_def_index)
196      REQUIRES(!requires_constructor_barrier_lock_);
197
198  // Callbacks from compiler to see what runtime checks must be generated.
199
200  bool CanAssumeTypeIsPresentInDexCache(Handle<mirror::DexCache> dex_cache,
201                                        uint32_t type_idx)
202      SHARED_REQUIRES(Locks::mutator_lock_);
203
204  bool CanAssumeStringIsPresentInDexCache(const DexFile& dex_file, uint32_t string_idx)
205      REQUIRES(!Locks::mutator_lock_);
206
207  // Are runtime access checks necessary in the compiled code?
208  bool CanAccessTypeWithoutChecks(uint32_t referrer_idx,
209                                  Handle<mirror::DexCache> dex_cache,
210                                  uint32_t type_idx)
211      SHARED_REQUIRES(Locks::mutator_lock_);
212
213  // Are runtime access and instantiable checks necessary in the code?
214  // out_is_finalizable is set to whether the type is finalizable.
215  bool CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
216                                              Handle<mirror::DexCache> dex_cache,
217                                              uint32_t type_idx,
218                                              bool* out_is_finalizable)
219      SHARED_REQUIRES(Locks::mutator_lock_);
220
221  bool CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
222                          bool* is_type_initialized, bool* use_direct_type_ptr,
223                          uintptr_t* direct_type_ptr, bool* out_is_finalizable);
224
225  // Query methods for the java.lang.ref.Reference class.
226  bool CanEmbedReferenceTypeInCode(ClassReference* ref,
227                                   bool* use_direct_type_ptr, uintptr_t* direct_type_ptr);
228  uint32_t GetReferenceSlowFlagOffset() const;
229  uint32_t GetReferenceDisableFlagOffset() const;
230
231  // Get the DexCache for the
232  mirror::DexCache* GetDexCache(const DexCompilationUnit* mUnit)
233    SHARED_REQUIRES(Locks::mutator_lock_);
234
235  mirror::ClassLoader* GetClassLoader(const ScopedObjectAccess& soa,
236                                      const DexCompilationUnit* mUnit)
237    SHARED_REQUIRES(Locks::mutator_lock_);
238
239  // Resolve compiling method's class. Returns null on failure.
240  mirror::Class* ResolveCompilingMethodsClass(
241      const ScopedObjectAccess& soa, Handle<mirror::DexCache> dex_cache,
242      Handle<mirror::ClassLoader> class_loader, const DexCompilationUnit* mUnit)
243      SHARED_REQUIRES(Locks::mutator_lock_);
244
245  mirror::Class* ResolveClass(
246      const ScopedObjectAccess& soa, Handle<mirror::DexCache> dex_cache,
247      Handle<mirror::ClassLoader> class_loader, uint16_t type_index,
248      const DexCompilationUnit* mUnit)
249      SHARED_REQUIRES(Locks::mutator_lock_);
250
251  // Resolve a field. Returns null on failure, including incompatible class change.
252  // NOTE: Unlike ClassLinker's ResolveField(), this method enforces is_static.
253  ArtField* ResolveField(
254      const ScopedObjectAccess& soa, Handle<mirror::DexCache> dex_cache,
255      Handle<mirror::ClassLoader> class_loader, const DexCompilationUnit* mUnit,
256      uint32_t field_idx, bool is_static)
257      SHARED_REQUIRES(Locks::mutator_lock_);
258
259  // Resolve a field with a given dex file.
260  ArtField* ResolveFieldWithDexFile(
261      const ScopedObjectAccess& soa, Handle<mirror::DexCache> dex_cache,
262      Handle<mirror::ClassLoader> class_loader, const DexFile* dex_file,
263      uint32_t field_idx, bool is_static)
264      SHARED_REQUIRES(Locks::mutator_lock_);
265
266  // Get declaration location of a resolved field.
267  void GetResolvedFieldDexFileLocation(
268      ArtField* resolved_field, const DexFile** declaring_dex_file,
269      uint16_t* declaring_class_idx, uint16_t* declaring_field_idx)
270      SHARED_REQUIRES(Locks::mutator_lock_);
271
272  bool IsFieldVolatile(ArtField* field) SHARED_REQUIRES(Locks::mutator_lock_);
273  MemberOffset GetFieldOffset(ArtField* field) SHARED_REQUIRES(Locks::mutator_lock_);
274
275  // Find a dex cache for a dex file.
276  inline mirror::DexCache* FindDexCache(const DexFile* dex_file)
277      SHARED_REQUIRES(Locks::mutator_lock_);
278
279  // Can we fast-path an IGET/IPUT access to an instance field? If yes, compute the field offset.
280  std::pair<bool, bool> IsFastInstanceField(
281      mirror::DexCache* dex_cache, mirror::Class* referrer_class,
282      ArtField* resolved_field, uint16_t field_idx)
283      SHARED_REQUIRES(Locks::mutator_lock_);
284
285  // Can we fast-path an SGET/SPUT access to a static field? If yes, compute the type index
286  // of the declaring class in the referrer's dex file.
287  std::pair<bool, bool> IsFastStaticField(
288      mirror::DexCache* dex_cache, mirror::Class* referrer_class,
289      ArtField* resolved_field, uint16_t field_idx, uint32_t* storage_index)
290      SHARED_REQUIRES(Locks::mutator_lock_);
291
292  // Return whether the declaring class of `resolved_method` is
293  // available to `referrer_class`. If this is true, compute the type
294  // index of the declaring class in the referrer's dex file and
295  // return it through the out argument `storage_index`; otherwise
296  // return DexFile::kDexNoIndex through `storage_index`.
297  bool IsClassOfStaticMethodAvailableToReferrer(mirror::DexCache* dex_cache,
298                                                mirror::Class* referrer_class,
299                                                ArtMethod* resolved_method,
300                                                uint16_t method_idx,
301                                                uint32_t* storage_index)
302      SHARED_REQUIRES(Locks::mutator_lock_);
303
304  // Is static field's in referrer's class?
305  bool IsStaticFieldInReferrerClass(mirror::Class* referrer_class, ArtField* resolved_field)
306      SHARED_REQUIRES(Locks::mutator_lock_);
307
308  // Is static field's class initialized?
309  bool IsStaticFieldsClassInitialized(mirror::Class* referrer_class,
310                                      ArtField* resolved_field)
311      SHARED_REQUIRES(Locks::mutator_lock_);
312
313  // Resolve a method. Returns null on failure, including incompatible class change.
314  ArtMethod* ResolveMethod(
315      ScopedObjectAccess& soa, Handle<mirror::DexCache> dex_cache,
316      Handle<mirror::ClassLoader> class_loader, const DexCompilationUnit* mUnit,
317      uint32_t method_idx, InvokeType invoke_type, bool check_incompatible_class_change = true)
318      SHARED_REQUIRES(Locks::mutator_lock_);
319
320  // Get declaration location of a resolved field.
321  void GetResolvedMethodDexFileLocation(
322      ArtMethod* resolved_method, const DexFile** declaring_dex_file,
323      uint16_t* declaring_class_idx, uint16_t* declaring_method_idx)
324      SHARED_REQUIRES(Locks::mutator_lock_);
325
326  // Get the index in the vtable of the method.
327  uint16_t GetResolvedMethodVTableIndex(
328      ArtMethod* resolved_method, InvokeType type)
329      SHARED_REQUIRES(Locks::mutator_lock_);
330
331  // Can we fast-path an INVOKE? If no, returns 0. If yes, returns a non-zero opaque flags value
332  // for ProcessedInvoke() and computes the necessary lowering info.
333  int IsFastInvoke(
334      ScopedObjectAccess& soa, Handle<mirror::DexCache> dex_cache,
335      Handle<mirror::ClassLoader> class_loader, const DexCompilationUnit* mUnit,
336      mirror::Class* referrer_class, ArtMethod* resolved_method, InvokeType* invoke_type,
337      MethodReference* target_method, const MethodReference* devirt_target,
338      uintptr_t* direct_code, uintptr_t* direct_method)
339      SHARED_REQUIRES(Locks::mutator_lock_);
340
341  // Is method's class initialized for an invoke?
342  // For static invokes to determine whether we need to consider potential call to <clinit>().
343  // For non-static invokes, assuming a non-null reference, the class is always initialized.
344  bool IsMethodsClassInitialized(mirror::Class* referrer_class, ArtMethod* resolved_method)
345      SHARED_REQUIRES(Locks::mutator_lock_);
346
347  // Get the layout of dex cache arrays for a dex file. Returns invalid layout if the
348  // dex cache arrays don't have a fixed layout.
349  DexCacheArraysLayout GetDexCacheArraysLayout(const DexFile* dex_file);
350
351  void ProcessedInstanceField(bool resolved);
352  void ProcessedStaticField(bool resolved, bool local);
353  void ProcessedInvoke(InvokeType invoke_type, int flags);
354
355  void ComputeFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
356                        const ScopedObjectAccess& soa, bool is_static,
357                        ArtField** resolved_field,
358                        mirror::Class** referrer_class,
359                        mirror::DexCache** dex_cache)
360      SHARED_REQUIRES(Locks::mutator_lock_);
361
362  // Can we fast path instance field access? Computes field's offset and volatility.
363  bool ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit, bool is_put,
364                                MemberOffset* field_offset, bool* is_volatile)
365      REQUIRES(!Locks::mutator_lock_);
366
367  ArtField* ComputeInstanceFieldInfo(uint32_t field_idx,
368                                             const DexCompilationUnit* mUnit,
369                                             bool is_put,
370                                             const ScopedObjectAccess& soa)
371      SHARED_REQUIRES(Locks::mutator_lock_);
372
373
374  // Can we fastpath a interface, super class or virtual method call? Computes method's vtable
375  // index.
376  bool ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
377                         bool update_stats, bool enable_devirtualization,
378                         InvokeType* type, MethodReference* target_method, int* vtable_idx,
379                         uintptr_t* direct_code, uintptr_t* direct_method)
380      REQUIRES(!Locks::mutator_lock_);
381
382  const VerifiedMethod* GetVerifiedMethod(const DexFile* dex_file, uint32_t method_idx) const;
383  bool IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc);
384
385  bool GetSupportBootImageFixup() const {
386    return support_boot_image_fixup_;
387  }
388
389  void SetSupportBootImageFixup(bool support_boot_image_fixup) {
390    support_boot_image_fixup_ = support_boot_image_fixup;
391  }
392
393  void SetCompilerContext(void* compiler_context) {
394    compiler_context_ = compiler_context;
395  }
396
397  void* GetCompilerContext() const {
398    return compiler_context_;
399  }
400
401  size_t GetThreadCount() const {
402    return parallel_thread_count_;
403  }
404
405  bool GetDumpStats() const {
406    return dump_stats_;
407  }
408
409  bool GetDumpPasses() const {
410    return dump_passes_;
411  }
412
413  CumulativeLogger* GetTimingsLogger() const {
414    return timings_logger_;
415  }
416
417  void SetDedupeEnabled(bool dedupe_enabled) {
418    compiled_method_storage_.SetDedupeEnabled(dedupe_enabled);
419  }
420  bool DedupeEnabled() const {
421    return compiled_method_storage_.DedupeEnabled();
422  }
423
424  // Checks if class specified by type_idx is one of the image_classes_
425  bool IsImageClass(const char* descriptor) const;
426
427  // Checks whether the provided class should be compiled, i.e., is in classes_to_compile_.
428  bool IsClassToCompile(const char* descriptor) const;
429
430  // Checks whether the provided method should be compiled, i.e., is in method_to_compile_.
431  bool IsMethodToCompile(const MethodReference& method_ref) const;
432
433  // Checks whether profile guided compilation is enabled and if the method should be compiled
434  // according to the profile file.
435  bool ShouldCompileBasedOnProfile(const MethodReference& method_ref) const;
436
437  // Checks whether profile guided verification is enabled and if the method should be verified
438  // according to the profile file.
439  bool ShouldVerifyClassBasedOnProfile(const DexFile& dex_file, uint16_t class_idx) const;
440
441  void RecordClassStatus(ClassReference ref, mirror::Class::Status status)
442      REQUIRES(!compiled_classes_lock_);
443
444  // Checks if the specified method has been verified without failures. Returns
445  // false if the method is not in the verification results (GetVerificationResults).
446  bool IsMethodVerifiedWithoutFailures(uint32_t method_idx,
447                                       uint16_t class_def_idx,
448                                       const DexFile& dex_file) const;
449
450  // Get memory usage during compilation.
451  std::string GetMemoryUsageString(bool extended) const;
452
453  bool IsStringTypeIndex(uint16_t type_index, const DexFile* dex_file);
454  bool IsStringInit(uint32_t method_index, const DexFile* dex_file, int32_t* offset);
455
456  void SetHadHardVerifierFailure() {
457    had_hard_verifier_failure_ = true;
458  }
459
460  Compiler::Kind GetCompilerKind() {
461    return compiler_kind_;
462  }
463
464  CompiledMethodStorage* GetCompiledMethodStorage() {
465    return &compiled_method_storage_;
466  }
467
468  // Can we assume that the klass is loaded?
469  bool CanAssumeClassIsLoaded(mirror::Class* klass)
470      SHARED_REQUIRES(Locks::mutator_lock_);
471
472  bool MayInline(const DexFile* inlined_from, const DexFile* inlined_into) const {
473    if (!kIsTargetBuild) {
474      return MayInlineInternal(inlined_from, inlined_into);
475    }
476    return true;
477  }
478
479  void MarkForDexToDexCompilation(Thread* self, const MethodReference& method_ref)
480      REQUIRES(!dex_to_dex_references_lock_);
481
482  const BitVector* GetCurrentDexToDexMethods() const {
483    return current_dex_to_dex_methods_;
484  }
485
486 private:
487  // Return whether the declaring class of `resolved_member` is
488  // available to `referrer_class` for read or write access using two
489  // Boolean values returned as a pair. If is true at least for read
490  // access, compute the type index of the declaring class in the
491  // referrer's dex file and return it through the out argument
492  // `storage_index`; otherwise return DexFile::kDexNoIndex through
493  // `storage_index`.
494  template <typename ArtMember>
495  std::pair<bool, bool> IsClassOfStaticMemberAvailableToReferrer(mirror::DexCache* dex_cache,
496                                                                 mirror::Class* referrer_class,
497                                                                 ArtMember* resolved_member,
498                                                                 uint16_t member_idx,
499                                                                 uint32_t* storage_index)
500      SHARED_REQUIRES(Locks::mutator_lock_);
501
502  // Can `referrer_class` access the resolved `member`?
503  // Dispatch call to mirror::Class::CanAccessResolvedField or
504  // mirror::Class::CanAccessResolvedMember depending on the value of
505  // ArtMember.
506  template <typename ArtMember>
507  static bool CanAccessResolvedMember(mirror::Class* referrer_class,
508                                      mirror::Class* access_to,
509                                      ArtMember* member,
510                                      mirror::DexCache* dex_cache,
511                                      uint32_t field_idx)
512      SHARED_REQUIRES(Locks::mutator_lock_);
513
514  // Can we assume that the klass is initialized?
515  bool CanAssumeClassIsInitialized(mirror::Class* klass)
516      SHARED_REQUIRES(Locks::mutator_lock_);
517  bool CanReferrerAssumeClassIsInitialized(mirror::Class* referrer_class, mirror::Class* klass)
518      SHARED_REQUIRES(Locks::mutator_lock_);
519
520  // These flags are internal to CompilerDriver for collecting INVOKE resolution statistics.
521  // The only external contract is that unresolved method has flags 0 and resolved non-0.
522  enum {
523    kBitMethodResolved = 0,
524    kBitVirtualMadeDirect,
525    kBitPreciseTypeDevirtualization,
526    kBitDirectCallToBoot,
527    kBitDirectMethodToBoot
528  };
529  static constexpr int kFlagMethodResolved              = 1 << kBitMethodResolved;
530  static constexpr int kFlagVirtualMadeDirect           = 1 << kBitVirtualMadeDirect;
531  static constexpr int kFlagPreciseTypeDevirtualization = 1 << kBitPreciseTypeDevirtualization;
532  static constexpr int kFlagDirectCallToBoot            = 1 << kBitDirectCallToBoot;
533  static constexpr int kFlagDirectMethodToBoot          = 1 << kBitDirectMethodToBoot;
534  static constexpr int kFlagsMethodResolvedVirtualMadeDirect =
535      kFlagMethodResolved | kFlagVirtualMadeDirect;
536  static constexpr int kFlagsMethodResolvedPreciseTypeDevirtualization =
537      kFlagsMethodResolvedVirtualMadeDirect | kFlagPreciseTypeDevirtualization;
538
539 public:  // TODO make private or eliminate.
540  // Compute constant code and method pointers when possible.
541  void GetCodeAndMethodForDirectCall(/*out*/InvokeType* type,
542                                     InvokeType sharp_type,
543                                     bool no_guarantee_of_dex_cache_entry,
544                                     const mirror::Class* referrer_class,
545                                     ArtMethod* method,
546                                     /*out*/int* stats_flags,
547                                     MethodReference* target_method,
548                                     uintptr_t* direct_code, uintptr_t* direct_method)
549      SHARED_REQUIRES(Locks::mutator_lock_);
550
551 private:
552  void PreCompile(jobject class_loader,
553                  const std::vector<const DexFile*>& dex_files,
554                  TimingLogger* timings)
555      REQUIRES(!Locks::mutator_lock_, !compiled_classes_lock_);
556
557  void LoadImageClasses(TimingLogger* timings) REQUIRES(!Locks::mutator_lock_);
558
559  // Attempt to resolve all type, methods, fields, and strings
560  // referenced from code in the dex file following PathClassLoader
561  // ordering semantics.
562  void Resolve(jobject class_loader,
563               const std::vector<const DexFile*>& dex_files,
564               TimingLogger* timings)
565      REQUIRES(!Locks::mutator_lock_);
566  void ResolveDexFile(jobject class_loader,
567                      const DexFile& dex_file,
568                      const std::vector<const DexFile*>& dex_files,
569                      ThreadPool* thread_pool,
570                      size_t thread_count,
571                      TimingLogger* timings)
572      REQUIRES(!Locks::mutator_lock_);
573
574  void Verify(jobject class_loader,
575              const std::vector<const DexFile*>& dex_files,
576              TimingLogger* timings);
577  void VerifyDexFile(jobject class_loader,
578                     const DexFile& dex_file,
579                     const std::vector<const DexFile*>& dex_files,
580                     ThreadPool* thread_pool,
581                     size_t thread_count,
582                     TimingLogger* timings)
583      REQUIRES(!Locks::mutator_lock_);
584
585  void SetVerified(jobject class_loader,
586                   const std::vector<const DexFile*>& dex_files,
587                   TimingLogger* timings);
588  void SetVerifiedDexFile(jobject class_loader,
589                          const DexFile& dex_file,
590                          const std::vector<const DexFile*>& dex_files,
591                          ThreadPool* thread_pool,
592                          size_t thread_count,
593                          TimingLogger* timings)
594      REQUIRES(!Locks::mutator_lock_);
595
596  void InitializeClasses(jobject class_loader,
597                         const std::vector<const DexFile*>& dex_files,
598                         TimingLogger* timings)
599      REQUIRES(!Locks::mutator_lock_, !compiled_classes_lock_);
600  void InitializeClasses(jobject class_loader,
601                         const DexFile& dex_file,
602                         const std::vector<const DexFile*>& dex_files,
603                         TimingLogger* timings)
604      REQUIRES(!Locks::mutator_lock_, !compiled_classes_lock_);
605
606  void UpdateImageClasses(TimingLogger* timings) REQUIRES(!Locks::mutator_lock_);
607  static void FindClinitImageClassesCallback(mirror::Object* object, void* arg)
608      SHARED_REQUIRES(Locks::mutator_lock_);
609
610  void Compile(jobject class_loader,
611               const std::vector<const DexFile*>& dex_files,
612               TimingLogger* timings) REQUIRES(!dex_to_dex_references_lock_);
613  void CompileDexFile(jobject class_loader,
614                      const DexFile& dex_file,
615                      const std::vector<const DexFile*>& dex_files,
616                      ThreadPool* thread_pool,
617                      size_t thread_count,
618                      TimingLogger* timings)
619      REQUIRES(!Locks::mutator_lock_);
620
621  bool MayInlineInternal(const DexFile* inlined_from, const DexFile* inlined_into) const;
622
623  void InitializeThreadPools();
624  void FreeThreadPools();
625  void CheckThreadPools();
626
627  bool RequiresConstructorBarrier(const DexFile& dex_file, uint16_t class_def_idx) const;
628
629  const CompilerOptions* const compiler_options_;
630  VerificationResults* const verification_results_;
631  DexFileToMethodInlinerMap* const method_inliner_map_;
632
633  std::unique_ptr<Compiler> compiler_;
634  Compiler::Kind compiler_kind_;
635
636  const InstructionSet instruction_set_;
637  const InstructionSetFeatures* const instruction_set_features_;
638
639  // All class references that require constructor barriers. If the class reference is not in the
640  // set then the result has not yet been computed.
641  mutable ReaderWriterMutex requires_constructor_barrier_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
642  std::map<ClassReference, bool> requires_constructor_barrier_
643      GUARDED_BY(requires_constructor_barrier_lock_);
644
645  typedef SafeMap<const ClassReference, CompiledClass*> ClassTable;
646  // All class references that this compiler has compiled.
647  mutable Mutex compiled_classes_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
648  ClassTable compiled_classes_ GUARDED_BY(compiled_classes_lock_);
649
650  typedef SafeMap<const MethodReference, CompiledMethod*, MethodReferenceComparator> MethodTable;
651
652 public:
653  // Lock is public so that non-members can have lock annotations.
654  mutable Mutex compiled_methods_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
655
656 private:
657  // All method references that this compiler has compiled.
658  MethodTable compiled_methods_ GUARDED_BY(compiled_methods_lock_);
659  // Number of non-relative patches in all compiled methods. These patches need space
660  // in the .oat_patches ELF section if requested in the compiler options.
661  size_t non_relative_linker_patch_count_ GUARDED_BY(compiled_methods_lock_);
662
663  const bool boot_image_;
664  const bool app_image_;
665
666  // If image_ is true, specifies the classes that will be included in the image.
667  // Note if image_classes_ is null, all classes are included in the image.
668  std::unique_ptr<std::unordered_set<std::string>> image_classes_;
669
670  // Specifies the classes that will be compiled. Note that if classes_to_compile_ is null,
671  // all classes are eligible for compilation (duplication filters etc. will still apply).
672  // This option may be restricted to the boot image, depending on a flag in the implementation.
673  std::unique_ptr<std::unordered_set<std::string>> classes_to_compile_;
674
675  // Specifies the methods that will be compiled. Note that if methods_to_compile_ is null,
676  // all methods are eligible for compilation (compilation filters etc. will still apply).
677  // This option may be restricted to the boot image, depending on a flag in the implementation.
678  std::unique_ptr<std::unordered_set<std::string>> methods_to_compile_;
679
680  bool had_hard_verifier_failure_;
681
682  // A thread pool that can (potentially) run tasks in parallel.
683  std::unique_ptr<ThreadPool> parallel_thread_pool_;
684  size_t parallel_thread_count_;
685
686  // A thread pool that guarantees running single-threaded on the main thread.
687  std::unique_ptr<ThreadPool> single_thread_pool_;
688
689  class AOTCompilationStats;
690  std::unique_ptr<AOTCompilationStats> stats_;
691
692  bool dump_stats_;
693  const bool dump_passes_;
694
695  CumulativeLogger* const timings_logger_;
696
697  typedef void (*CompilerCallbackFn)(CompilerDriver& driver);
698  typedef MutexLock* (*CompilerMutexLockFn)(CompilerDriver& driver);
699
700  void* compiler_context_;
701
702  bool support_boot_image_fixup_;
703
704  // List of dex files that will be stored in the oat file.
705  const std::vector<const DexFile*>* dex_files_for_oat_file_;
706
707  CompiledMethodStorage compiled_method_storage_;
708
709  // Info for profile guided compilation.
710  const ProfileCompilationInfo* const profile_compilation_info_;
711
712  size_t max_arena_alloc_;
713
714  // Data for delaying dex-to-dex compilation.
715  Mutex dex_to_dex_references_lock_;
716  // In the first phase, dex_to_dex_references_ collects methods for dex-to-dex compilation.
717  class DexFileMethodSet;
718  std::vector<DexFileMethodSet> dex_to_dex_references_ GUARDED_BY(dex_to_dex_references_lock_);
719  // In the second phase, current_dex_to_dex_methods_ points to the BitVector with method
720  // indexes for dex-to-dex compilation in the current dex file.
721  const BitVector* current_dex_to_dex_methods_;
722
723  friend class CompileClassVisitor;
724  DISALLOW_COPY_AND_ASSIGN(CompilerDriver);
725};
726
727}  // namespace art
728
729#endif  // ART_COMPILER_DRIVER_COMPILER_DRIVER_H_
730