• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 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_RUNTIME_JIT_JIT_H_
18 #define ART_RUNTIME_JIT_JIT_H_
19 
20 #include <android-base/unique_fd.h>
21 
22 #include "base/histogram-inl.h"
23 #include "base/macros.h"
24 #include "base/mutex.h"
25 #include "base/runtime_debug.h"
26 #include "base/timing_logger.h"
27 #include "compilation_kind.h"
28 #include "handle.h"
29 #include "offsets.h"
30 #include "interpreter/mterp/nterp.h"
31 #include "jit/debugger_interface.h"
32 #include "jit/profile_saver_options.h"
33 #include "obj_ptr.h"
34 #include "thread_pool.h"
35 
36 namespace art {
37 
38 class ArtMethod;
39 class ClassLinker;
40 class DexFile;
41 class OatDexFile;
42 struct RuntimeArgumentMap;
43 union JValue;
44 
45 namespace mirror {
46 class Object;
47 class Class;
48 class ClassLoader;
49 class DexCache;
50 class String;
51 }   // namespace mirror
52 
53 namespace jit {
54 
55 class JitCodeCache;
56 class JitCompileTask;
57 class JitMemoryRegion;
58 class JitOptions;
59 
60 static constexpr int16_t kJitCheckForOSR = -1;
61 static constexpr int16_t kJitHotnessDisabled = -2;
62 // At what priority to schedule jit threads. 9 is the lowest foreground priority on device.
63 // See android/os/Process.java.
64 static constexpr int kJitPoolThreadPthreadDefaultPriority = 9;
65 // At what priority to schedule jit zygote threads compiling profiles in the background.
66 // 19 is the lowest background priority on device.
67 // See android/os/Process.java.
68 static constexpr int kJitZygotePoolThreadPthreadDefaultPriority = 19;
69 
70 class JitOptions {
71  public:
72   static JitOptions* CreateFromRuntimeArguments(const RuntimeArgumentMap& options);
73 
GetOptimizeThreshold()74   uint16_t GetOptimizeThreshold() const {
75     return optimize_threshold_;
76   }
77 
GetWarmupThreshold()78   uint16_t GetWarmupThreshold() const {
79     return warmup_threshold_;
80   }
81 
GetPriorityThreadWeight()82   uint16_t GetPriorityThreadWeight() const {
83     return priority_thread_weight_;
84   }
85 
GetInvokeTransitionWeight()86   uint16_t GetInvokeTransitionWeight() const {
87     return invoke_transition_weight_;
88   }
89 
GetCodeCacheInitialCapacity()90   size_t GetCodeCacheInitialCapacity() const {
91     return code_cache_initial_capacity_;
92   }
93 
GetCodeCacheMaxCapacity()94   size_t GetCodeCacheMaxCapacity() const {
95     return code_cache_max_capacity_;
96   }
97 
DumpJitInfoOnShutdown()98   bool DumpJitInfoOnShutdown() const {
99     return dump_info_on_shutdown_;
100   }
101 
GetProfileSaverOptions()102   const ProfileSaverOptions& GetProfileSaverOptions() const {
103     return profile_saver_options_;
104   }
105 
GetSaveProfilingInfo()106   bool GetSaveProfilingInfo() const {
107     return profile_saver_options_.IsEnabled();
108   }
109 
GetThreadPoolPthreadPriority()110   int GetThreadPoolPthreadPriority() const {
111     return thread_pool_pthread_priority_;
112   }
113 
GetZygoteThreadPoolPthreadPriority()114   int GetZygoteThreadPoolPthreadPriority() const {
115     return zygote_thread_pool_pthread_priority_;
116   }
117 
UseJitCompilation()118   bool UseJitCompilation() const {
119     return use_jit_compilation_;
120   }
121 
UseProfiledJitCompilation()122   bool UseProfiledJitCompilation() const {
123     return use_profiled_jit_compilation_;
124   }
125 
SetUseJitCompilation(bool b)126   void SetUseJitCompilation(bool b) {
127     use_jit_compilation_ = b;
128   }
129 
SetSaveProfilingInfo(bool save_profiling_info)130   void SetSaveProfilingInfo(bool save_profiling_info) {
131     profile_saver_options_.SetEnabled(save_profiling_info);
132   }
133 
SetWaitForJitNotificationsToSaveProfile(bool value)134   void SetWaitForJitNotificationsToSaveProfile(bool value) {
135     profile_saver_options_.SetWaitForJitNotificationsToSave(value);
136   }
137 
SetJitAtFirstUse()138   void SetJitAtFirstUse() {
139     use_jit_compilation_ = true;
140     optimize_threshold_ = 0;
141   }
142 
SetUseBaselineCompiler()143   void SetUseBaselineCompiler() {
144     use_baseline_compiler_ = true;
145   }
146 
UseBaselineCompiler()147   bool UseBaselineCompiler() const {
148     return use_baseline_compiler_;
149   }
150 
151  private:
152   // We add the sample in batches of size kJitSamplesBatchSize.
153   // This method rounds the threshold so that it is multiple of the batch size.
154   static uint32_t RoundUpThreshold(uint32_t threshold);
155 
156   bool use_jit_compilation_;
157   bool use_profiled_jit_compilation_;
158   bool use_baseline_compiler_;
159   size_t code_cache_initial_capacity_;
160   size_t code_cache_max_capacity_;
161   uint32_t optimize_threshold_;
162   uint32_t warmup_threshold_;
163   uint16_t priority_thread_weight_;
164   uint16_t invoke_transition_weight_;
165   bool dump_info_on_shutdown_;
166   int thread_pool_pthread_priority_;
167   int zygote_thread_pool_pthread_priority_;
168   ProfileSaverOptions profile_saver_options_;
169 
JitOptions()170   JitOptions()
171       : use_jit_compilation_(false),
172         use_profiled_jit_compilation_(false),
173         use_baseline_compiler_(false),
174         code_cache_initial_capacity_(0),
175         code_cache_max_capacity_(0),
176         optimize_threshold_(0),
177         warmup_threshold_(0),
178         priority_thread_weight_(0),
179         invoke_transition_weight_(0),
180         dump_info_on_shutdown_(false),
181         thread_pool_pthread_priority_(kJitPoolThreadPthreadDefaultPriority),
182         zygote_thread_pool_pthread_priority_(kJitZygotePoolThreadPthreadDefaultPriority) {}
183 
184   DISALLOW_COPY_AND_ASSIGN(JitOptions);
185 };
186 
187 // Implemented and provided by the compiler library.
188 class JitCompilerInterface {
189  public:
~JitCompilerInterface()190   virtual ~JitCompilerInterface() {}
191   virtual bool CompileMethod(
192       Thread* self, JitMemoryRegion* region, ArtMethod* method, CompilationKind compilation_kind)
193       REQUIRES_SHARED(Locks::mutator_lock_) = 0;
194   virtual void TypesLoaded(mirror::Class**, size_t count)
195       REQUIRES_SHARED(Locks::mutator_lock_) = 0;
196   virtual bool GenerateDebugInfo() = 0;
197   virtual void ParseCompilerOptions() = 0;
198   virtual bool IsBaselineCompiler() const = 0;
199   virtual void SetDebuggableCompilerOption(bool value) = 0;
200 
201   virtual std::vector<uint8_t> PackElfFileForJIT(ArrayRef<const JITCodeEntry*> elf_files,
202                                                  ArrayRef<const void*> removed_symbols,
203                                                  bool compress,
204                                                  /*out*/ size_t* num_symbols) = 0;
205 };
206 
207 // Data structure holding information to perform an OSR.
208 struct OsrData {
209   // The native PC to jump to.
210   const uint8_t* native_pc;
211 
212   // The frame size of the compiled code to jump to.
213   size_t frame_size;
214 
215   // The dynamically allocated memory of size `frame_size` to copy to stack.
216   void* memory[0];
217 
NativePcOffsetOsrData218   static constexpr MemberOffset NativePcOffset() {
219     return MemberOffset(OFFSETOF_MEMBER(OsrData, native_pc));
220   }
221 
FrameSizeOffsetOsrData222   static constexpr MemberOffset FrameSizeOffset() {
223     return MemberOffset(OFFSETOF_MEMBER(OsrData, frame_size));
224   }
225 
MemoryOffsetOsrData226   static constexpr MemberOffset MemoryOffset() {
227     return MemberOffset(OFFSETOF_MEMBER(OsrData, memory));
228   }
229 };
230 
231 class Jit {
232  public:
233   static constexpr size_t kDefaultPriorityThreadWeightRatio = 1000;
234   static constexpr size_t kDefaultInvokeTransitionWeightRatio = 500;
235   // How frequently should the interpreter check to see if OSR compilation is ready.
236   static constexpr int16_t kJitRecheckOSRThreshold = 101;  // Prime number to avoid patterns.
237 
238   DECLARE_RUNTIME_DEBUG_FLAG(kSlowMode);
239 
240   virtual ~Jit();
241 
242   // Create JIT itself.
243   static Jit* Create(JitCodeCache* code_cache, JitOptions* options);
244 
245   bool CompileMethod(ArtMethod* method, Thread* self, CompilationKind compilation_kind, bool prejit)
246       REQUIRES_SHARED(Locks::mutator_lock_);
247 
GetCodeCache()248   const JitCodeCache* GetCodeCache() const {
249     return code_cache_;
250   }
251 
GetCodeCache()252   JitCodeCache* GetCodeCache() {
253     return code_cache_;
254   }
255 
GetJitCompiler()256   JitCompilerInterface* GetJitCompiler() const {
257     return jit_compiler_;
258   }
259 
260   void CreateThreadPool();
261   void DeleteThreadPool();
262   void WaitForWorkersToBeCreated();
263 
264   // Dump interesting info: #methods compiled, code vs data size, compile / verify cumulative
265   // loggers.
266   void DumpInfo(std::ostream& os) REQUIRES(!lock_);
267   // Add a timing logger to cumulative_timings_.
268   void AddTimingLogger(const TimingLogger& logger);
269 
270   void AddMemoryUsage(ArtMethod* method, size_t bytes)
271       REQUIRES(!lock_)
272       REQUIRES_SHARED(Locks::mutator_lock_);
273 
GetThreadPoolPthreadPriority()274   int GetThreadPoolPthreadPriority() const {
275     return options_->GetThreadPoolPthreadPriority();
276   }
277 
GetZygoteThreadPoolPthreadPriority()278   int GetZygoteThreadPoolPthreadPriority() const {
279     return options_->GetZygoteThreadPoolPthreadPriority();
280   }
281 
HotMethodThreshold()282   uint16_t HotMethodThreshold() const {
283     return options_->GetOptimizeThreshold();
284   }
285 
WarmMethodThreshold()286   uint16_t WarmMethodThreshold() const {
287     return options_->GetWarmupThreshold();
288   }
289 
PriorityThreadWeight()290   uint16_t PriorityThreadWeight() const {
291     return options_->GetPriorityThreadWeight();
292   }
293 
294   // Return whether we should do JIT compilation. Note this will returns false
295   // if we only need to save profile information and not compile methods.
UseJitCompilation()296   bool UseJitCompilation() const {
297     return options_->UseJitCompilation();
298   }
299 
GetSaveProfilingInfo()300   bool GetSaveProfilingInfo() const {
301     return options_->GetSaveProfilingInfo();
302   }
303 
304   // Wait until there is no more pending compilation tasks.
305   void WaitForCompilationToFinish(Thread* self);
306 
307   // Profiling methods.
308   void MethodEntered(Thread* thread, ArtMethod* method)
309       REQUIRES_SHARED(Locks::mutator_lock_);
310 
311   ALWAYS_INLINE void AddSamples(Thread* self, ArtMethod* method)
312       REQUIRES_SHARED(Locks::mutator_lock_);
313 
NotifyInterpreterToCompiledCodeTransition(Thread * self,ArtMethod * caller)314   void NotifyInterpreterToCompiledCodeTransition(Thread* self, ArtMethod* caller)
315       REQUIRES_SHARED(Locks::mutator_lock_) {
316     AddSamples(self, caller);
317   }
318 
NotifyCompiledCodeToInterpreterTransition(Thread * self,ArtMethod * callee)319   void NotifyCompiledCodeToInterpreterTransition(Thread* self, ArtMethod* callee)
320       REQUIRES_SHARED(Locks::mutator_lock_) {
321     AddSamples(self, callee);
322   }
323 
324   // Starts the profile saver if the config options allow profile recording.
325   // The profile will be stored in the specified `profile_filename` and will contain
326   // information collected from the given `code_paths` (a set of dex locations).
327   //
328   // The `ref_profile_filename` denotes the path to the reference profile which
329   // might be queried to determine if an initial save should be done earlier.
330   // It can be empty indicating there is no reference profile.
331   void StartProfileSaver(const std::string& profile_filename,
332                          const std::vector<std::string>& code_paths,
333                          const std::string& ref_profile_filename);
334   void StopProfileSaver();
335 
336   void DumpForSigQuit(std::ostream& os) REQUIRES(!lock_);
337 
338   static void NewTypeLoadedIfUsingJit(mirror::Class* type)
339       REQUIRES_SHARED(Locks::mutator_lock_);
340 
341   // If debug info generation is turned on then write the type information for types already loaded
342   // into the specified class linker to the jit debug interface,
343   void DumpTypeInfoForLoadedTypes(ClassLinker* linker);
344 
345   // Return whether we should try to JIT compiled code as soon as an ArtMethod is invoked.
346   bool JitAtFirstUse();
347 
348   // Return whether we can invoke JIT code for `method`.
349   bool CanInvokeCompiledCode(ArtMethod* method);
350 
351   // Return the information required to do an OSR jump. Return null if the OSR
352   // cannot be done.
353   OsrData* PrepareForOsr(ArtMethod* method, uint32_t dex_pc, uint32_t* vregs)
354       REQUIRES_SHARED(Locks::mutator_lock_);
355 
356   // If an OSR compiled version is available for `method`,
357   // and `dex_pc + dex_pc_offset` is an entry point of that compiled
358   // version, this method will jump to the compiled code, let it run,
359   // and return true afterwards. Return false otherwise.
360   static bool MaybeDoOnStackReplacement(Thread* thread,
361                                         ArtMethod* method,
362                                         uint32_t dex_pc,
363                                         int32_t dex_pc_offset,
364                                         JValue* result)
365       REQUIRES_SHARED(Locks::mutator_lock_);
366 
367   // Load the compiler library.
368   static bool LoadCompilerLibrary(std::string* error_msg);
369 
GetThreadPool()370   ThreadPool* GetThreadPool() const {
371     return thread_pool_.get();
372   }
373 
374   // Stop the JIT by waiting for all current compilations and enqueued compilations to finish.
375   void Stop();
376 
377   // Start JIT threads.
378   void Start();
379 
380   // Transition to a child state.
381   void PostForkChildAction(bool is_system_server, bool is_zygote);
382 
383   // Prepare for forking.
384   void PreZygoteFork();
385 
386   // Adjust state after forking.
387   void PostZygoteFork();
388 
389   // Add a task to the queue, ensuring it runs after boot is finished.
390   void AddPostBootTask(Thread* self, Task* task);
391 
392   // Called when system finishes booting.
393   void BootCompleted();
394 
395   // Are we in a zygote using JIT compilation?
396   static bool InZygoteUsingJit();
397 
398   // Compile methods from the given profile (.prof extension). If `add_to_queue`
399   // is true, methods in the profile are added to the JIT queue. Otherwise they are compiled
400   // directly.
401   // Return the number of methods added to the queue.
402   uint32_t CompileMethodsFromProfile(Thread* self,
403                                      const std::vector<const DexFile*>& dex_files,
404                                      const std::string& profile_path,
405                                      Handle<mirror::ClassLoader> class_loader,
406                                      bool add_to_queue);
407 
408   // Compile methods from the given boot profile (.bprof extension). If `add_to_queue`
409   // is true, methods in the profile are added to the JIT queue. Otherwise they are compiled
410   // directly.
411   // Return the number of methods added to the queue.
412   uint32_t CompileMethodsFromBootProfile(Thread* self,
413                                          const std::vector<const DexFile*>& dex_files,
414                                          const std::string& profile_path,
415                                          Handle<mirror::ClassLoader> class_loader,
416                                          bool add_to_queue);
417 
418   // Register the dex files to the JIT. This is to perform any compilation/optimization
419   // at the point of loading the dex files.
420   void RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
421                         jobject class_loader);
422 
423   // Called by the compiler to know whether it can directly encode the
424   // method/class/string.
425   bool CanEncodeMethod(ArtMethod* method, bool is_for_shared_region) const
426       REQUIRES_SHARED(Locks::mutator_lock_);
427   bool CanEncodeClass(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const
428       REQUIRES_SHARED(Locks::mutator_lock_);
429   bool CanEncodeString(ObjPtr<mirror::String> string, bool is_for_shared_region) const
430       REQUIRES_SHARED(Locks::mutator_lock_);
431   bool CanAssumeInitialized(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const
432       REQUIRES_SHARED(Locks::mutator_lock_);
433 
434   // Map boot image methods after all compilation in zygote has been done.
435   void MapBootImageMethods() REQUIRES(Locks::mutator_lock_);
436 
437   // Notify to other processes that the zygote is done profile compiling boot
438   // class path methods.
439   void NotifyZygoteCompilationDone();
440 
441   void EnqueueOptimizedCompilation(ArtMethod* method, Thread* self);
442 
443   void MaybeEnqueueCompilation(ArtMethod* method, Thread* self)
444       REQUIRES_SHARED(Locks::mutator_lock_);
445 
446  private:
447   Jit(JitCodeCache* code_cache, JitOptions* options);
448 
449   // Whether we should not add hotness counts for the given method.
450   bool IgnoreSamplesForMethod(ArtMethod* method)
451       REQUIRES_SHARED(Locks::mutator_lock_);
452 
453   // Compile an individual method listed in a profile. If `add_to_queue` is
454   // true and the method was resolved, return true. Otherwise return false.
455   bool CompileMethodFromProfile(Thread* self,
456                                 ClassLinker* linker,
457                                 uint32_t method_idx,
458                                 Handle<mirror::DexCache> dex_cache,
459                                 Handle<mirror::ClassLoader> class_loader,
460                                 bool add_to_queue,
461                                 bool compile_after_boot)
462       REQUIRES_SHARED(Locks::mutator_lock_);
463 
464   static bool BindCompilerMethods(std::string* error_msg);
465 
466   void AddCompileTask(Thread* self,
467                       ArtMethod* method,
468                       CompilationKind compilation_kind,
469                       bool precompile = false);
470 
471   bool CompileMethodInternal(ArtMethod* method,
472                              Thread* self,
473                              CompilationKind compilation_kind,
474                              bool prejit)
475       REQUIRES_SHARED(Locks::mutator_lock_);
476 
477   // JIT compiler
478   static void* jit_library_handle_;
479   static JitCompilerInterface* jit_compiler_;
480   static JitCompilerInterface* (*jit_load_)(void);
481   template <typename T> static bool LoadSymbol(T*, const char* symbol, std::string* error_msg);
482 
483   // JIT resources owned by runtime.
484   jit::JitCodeCache* const code_cache_;
485   const JitOptions* const options_;
486 
487   std::unique_ptr<ThreadPool> thread_pool_;
488   std::vector<std::unique_ptr<OatDexFile>> type_lookup_tables_;
489 
490   Mutex boot_completed_lock_;
491   bool boot_completed_ GUARDED_BY(boot_completed_lock_) = false;
492   std::deque<Task*> tasks_after_boot_ GUARDED_BY(boot_completed_lock_);
493 
494   // Performance monitoring.
495   CumulativeLogger cumulative_timings_;
496   Histogram<uint64_t> memory_use_ GUARDED_BY(lock_);
497   Mutex lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
498 
499   // In the JIT zygote configuration, after all compilation is done, the zygote
500   // will copy its contents of the boot image to the zygote_mapping_methods_,
501   // which will be picked up by processes that will map the memory
502   // in-place within the boot image mapping.
503   //
504   // zygote_mapping_methods_ is shared memory only usable by the zygote and not
505   // inherited by child processes. We create it eagerly to ensure other
506   // processes cannot seal writable the file.
507   MemMap zygote_mapping_methods_;
508 
509   // The file descriptor created through memfd_create pointing to memory holding
510   // boot image methods. Created by the zygote, and inherited by child
511   // processes. The descriptor will be closed in each process (including the
512   // zygote) once they don't need it.
513   android::base::unique_fd fd_methods_;
514 
515   // The size of the memory pointed by `fd_methods_`. Cached here to avoid
516   // recomputing it.
517   size_t fd_methods_size_;
518 
519   // Map of hotness counters for methods which we want to share the memory
520   // between the zygote and apps.
521   std::map<ArtMethod*, uint16_t> shared_method_counters_;
522 
523   friend class art::jit::JitCompileTask;
524 
525   DISALLOW_COPY_AND_ASSIGN(Jit);
526 };
527 
528 // Helper class to stop the JIT for a given scope. This will wait for the JIT to quiesce.
529 class ScopedJitSuspend {
530  public:
531   ScopedJitSuspend();
532   ~ScopedJitSuspend();
533 
534  private:
535   bool was_on_;
536 };
537 
538 }  // namespace jit
539 }  // namespace art
540 
541 #endif  // ART_RUNTIME_JIT_JIT_H_
542