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