• 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 #include "jit.h"
18 
19 #include <dlfcn.h>
20 
21 #include "art_method-inl.h"
22 #include "debugger.h"
23 #include "entrypoints/runtime_asm_entrypoints.h"
24 #include "interpreter/interpreter.h"
25 #include "jit_code_cache.h"
26 #include "oat_file_manager.h"
27 #include "oat_quick_method_header.h"
28 #include "offline_profiling_info.h"
29 #include "profile_saver.h"
30 #include "runtime.h"
31 #include "runtime_options.h"
32 #include "stack_map.h"
33 #include "thread_list.h"
34 #include "utils.h"
35 
36 namespace art {
37 namespace jit {
38 
39 static constexpr bool kEnableOnStackReplacement = true;
40 // At what priority to schedule jit threads. 9 is the lowest foreground priority on device.
41 static constexpr int kJitPoolThreadPthreadPriority = 9;
42 
43 // JIT compiler
44 void* Jit::jit_library_handle_= nullptr;
45 void* Jit::jit_compiler_handle_ = nullptr;
46 void* (*Jit::jit_load_)(bool*) = nullptr;
47 void (*Jit::jit_unload_)(void*) = nullptr;
48 bool (*Jit::jit_compile_method_)(void*, ArtMethod*, Thread*, bool) = nullptr;
49 void (*Jit::jit_types_loaded_)(void*, mirror::Class**, size_t count) = nullptr;
50 bool Jit::generate_debug_info_ = false;
51 
CreateFromRuntimeArguments(const RuntimeArgumentMap & options)52 JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
53   auto* jit_options = new JitOptions;
54   jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
55 
56   jit_options->code_cache_initial_capacity_ =
57       options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
58   jit_options->code_cache_max_capacity_ =
59       options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
60   jit_options->dump_info_on_shutdown_ =
61       options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
62   jit_options->save_profiling_info_ =
63       options.GetOrDefault(RuntimeArgumentMap::JITSaveProfilingInfo);
64 
65   jit_options->compile_threshold_ = options.GetOrDefault(RuntimeArgumentMap::JITCompileThreshold);
66   if (jit_options->compile_threshold_ > std::numeric_limits<uint16_t>::max()) {
67     LOG(FATAL) << "Method compilation threshold is above its internal limit.";
68   }
69 
70   if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
71     jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
72     if (jit_options->warmup_threshold_ > std::numeric_limits<uint16_t>::max()) {
73       LOG(FATAL) << "Method warmup threshold is above its internal limit.";
74     }
75   } else {
76     jit_options->warmup_threshold_ = jit_options->compile_threshold_ / 2;
77   }
78 
79   if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
80     jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
81     if (jit_options->osr_threshold_ > std::numeric_limits<uint16_t>::max()) {
82       LOG(FATAL) << "Method on stack replacement threshold is above its internal limit.";
83     }
84   } else {
85     jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
86     if (jit_options->osr_threshold_ > std::numeric_limits<uint16_t>::max()) {
87       jit_options->osr_threshold_ = std::numeric_limits<uint16_t>::max();
88     }
89   }
90 
91   if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
92     jit_options->priority_thread_weight_ =
93         *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
94     if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
95       LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
96     } else if (jit_options->priority_thread_weight_ == 0) {
97       LOG(FATAL) << "Priority thread weight cannot be 0.";
98     }
99   } else {
100     jit_options->priority_thread_weight_ = std::max(
101         jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
102         static_cast<size_t>(1));
103   }
104 
105   if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
106     jit_options->invoke_transition_weight_ =
107         *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
108     if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
109       LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
110     } else if (jit_options->invoke_transition_weight_  == 0) {
111       LOG(FATAL) << "Invoke transition weight cannot be 0.";
112     }
113   } else {
114     jit_options->invoke_transition_weight_ = std::max(
115         jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
116         static_cast<size_t>(1));;
117   }
118 
119   return jit_options;
120 }
121 
ShouldUsePriorityThreadWeight()122 bool Jit::ShouldUsePriorityThreadWeight() {
123   return Runtime::Current()->InJankPerceptibleProcessState()
124       && Thread::Current()->IsJitSensitiveThread();
125 }
126 
DumpInfo(std::ostream & os)127 void Jit::DumpInfo(std::ostream& os) {
128   code_cache_->Dump(os);
129   cumulative_timings_.Dump(os);
130   MutexLock mu(Thread::Current(), lock_);
131   memory_use_.PrintMemoryUse(os);
132 }
133 
DumpForSigQuit(std::ostream & os)134 void Jit::DumpForSigQuit(std::ostream& os) {
135   DumpInfo(os);
136   ProfileSaver::DumpInstanceInfo(os);
137 }
138 
AddTimingLogger(const TimingLogger & logger)139 void Jit::AddTimingLogger(const TimingLogger& logger) {
140   cumulative_timings_.AddLogger(logger);
141 }
142 
Jit()143 Jit::Jit() : dump_info_on_shutdown_(false),
144              cumulative_timings_("JIT timings"),
145              memory_use_("Memory used for compilation", 16),
146              lock_("JIT memory use lock"),
147              use_jit_compilation_(true),
148              save_profiling_info_(false),
149              hot_method_threshold_(0),
150              warm_method_threshold_(0),
151              osr_method_threshold_(0),
152              priority_thread_weight_(0),
153              invoke_transition_weight_(0) {}
154 
Create(JitOptions * options,std::string * error_msg)155 Jit* Jit::Create(JitOptions* options, std::string* error_msg) {
156   DCHECK(options->UseJitCompilation() || options->GetSaveProfilingInfo());
157   std::unique_ptr<Jit> jit(new Jit);
158   jit->dump_info_on_shutdown_ = options->DumpJitInfoOnShutdown();
159   if (jit_compiler_handle_ == nullptr && !LoadCompiler(error_msg)) {
160     return nullptr;
161   }
162   jit->code_cache_.reset(JitCodeCache::Create(
163       options->GetCodeCacheInitialCapacity(),
164       options->GetCodeCacheMaxCapacity(),
165       jit->generate_debug_info_,
166       error_msg));
167   if (jit->GetCodeCache() == nullptr) {
168     return nullptr;
169   }
170   jit->use_jit_compilation_ = options->UseJitCompilation();
171   jit->save_profiling_info_ = options->GetSaveProfilingInfo();
172   VLOG(jit) << "JIT created with initial_capacity="
173       << PrettySize(options->GetCodeCacheInitialCapacity())
174       << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
175       << ", compile_threshold=" << options->GetCompileThreshold()
176       << ", save_profiling_info=" << options->GetSaveProfilingInfo();
177 
178 
179   jit->hot_method_threshold_ = options->GetCompileThreshold();
180   jit->warm_method_threshold_ = options->GetWarmupThreshold();
181   jit->osr_method_threshold_ = options->GetOsrThreshold();
182   jit->priority_thread_weight_ = options->GetPriorityThreadWeight();
183   jit->invoke_transition_weight_ = options->GetInvokeTransitionWeight();
184 
185   jit->CreateThreadPool();
186 
187   // Notify native debugger about the classes already loaded before the creation of the jit.
188   jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
189   return jit.release();
190 }
191 
LoadCompilerLibrary(std::string * error_msg)192 bool Jit::LoadCompilerLibrary(std::string* error_msg) {
193   jit_library_handle_ = dlopen(
194       kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
195   if (jit_library_handle_ == nullptr) {
196     std::ostringstream oss;
197     oss << "JIT could not load libart-compiler.so: " << dlerror();
198     *error_msg = oss.str();
199     return false;
200   }
201   jit_load_ = reinterpret_cast<void* (*)(bool*)>(dlsym(jit_library_handle_, "jit_load"));
202   if (jit_load_ == nullptr) {
203     dlclose(jit_library_handle_);
204     *error_msg = "JIT couldn't find jit_load entry point";
205     return false;
206   }
207   jit_unload_ = reinterpret_cast<void (*)(void*)>(
208       dlsym(jit_library_handle_, "jit_unload"));
209   if (jit_unload_ == nullptr) {
210     dlclose(jit_library_handle_);
211     *error_msg = "JIT couldn't find jit_unload entry point";
212     return false;
213   }
214   jit_compile_method_ = reinterpret_cast<bool (*)(void*, ArtMethod*, Thread*, bool)>(
215       dlsym(jit_library_handle_, "jit_compile_method"));
216   if (jit_compile_method_ == nullptr) {
217     dlclose(jit_library_handle_);
218     *error_msg = "JIT couldn't find jit_compile_method entry point";
219     return false;
220   }
221   jit_types_loaded_ = reinterpret_cast<void (*)(void*, mirror::Class**, size_t)>(
222       dlsym(jit_library_handle_, "jit_types_loaded"));
223   if (jit_types_loaded_ == nullptr) {
224     dlclose(jit_library_handle_);
225     *error_msg = "JIT couldn't find jit_types_loaded entry point";
226     return false;
227   }
228   return true;
229 }
230 
LoadCompiler(std::string * error_msg)231 bool Jit::LoadCompiler(std::string* error_msg) {
232   if (jit_library_handle_ == nullptr && !LoadCompilerLibrary(error_msg)) {
233     return false;
234   }
235   bool will_generate_debug_symbols = false;
236   VLOG(jit) << "Calling JitLoad interpreter_only="
237       << Runtime::Current()->GetInstrumentation()->InterpretOnly();
238   jit_compiler_handle_ = (jit_load_)(&will_generate_debug_symbols);
239   if (jit_compiler_handle_ == nullptr) {
240     dlclose(jit_library_handle_);
241     *error_msg = "JIT couldn't load compiler";
242     return false;
243   }
244   generate_debug_info_ = will_generate_debug_symbols;
245   return true;
246 }
247 
CompileMethod(ArtMethod * method,Thread * self,bool osr)248 bool Jit::CompileMethod(ArtMethod* method, Thread* self, bool osr) {
249   DCHECK(Runtime::Current()->UseJitCompilation());
250   DCHECK(!method->IsRuntimeMethod());
251 
252   // Don't compile the method if it has breakpoints.
253   if (Dbg::IsDebuggerActive() && Dbg::MethodHasAnyBreakpoints(method)) {
254     VLOG(jit) << "JIT not compiling " << PrettyMethod(method) << " due to breakpoint";
255     return false;
256   }
257 
258   // Don't compile the method if we are supposed to be deoptimized.
259   instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
260   if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
261     VLOG(jit) << "JIT not compiling " << PrettyMethod(method) << " due to deoptimization";
262     return false;
263   }
264 
265   // If we get a request to compile a proxy method, we pass the actual Java method
266   // of that proxy method, as the compiler does not expect a proxy method.
267   ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(sizeof(void*));
268   if (!code_cache_->NotifyCompilationOf(method_to_compile, self, osr)) {
269     return false;
270   }
271 
272   VLOG(jit) << "Compiling method "
273             << PrettyMethod(method_to_compile)
274             << " osr=" << std::boolalpha << osr;
275   bool success = jit_compile_method_(jit_compiler_handle_, method_to_compile, self, osr);
276   code_cache_->DoneCompiling(method_to_compile, self, osr);
277   if (!success) {
278     VLOG(jit) << "Failed to compile method "
279               << PrettyMethod(method_to_compile)
280               << " osr=" << std::boolalpha << osr;
281   }
282   return success;
283 }
284 
CreateThreadPool()285 void Jit::CreateThreadPool() {
286   // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
287   // is not null when we instrument.
288 
289   // We need peers as we may report the JIT thread, e.g., in the debugger.
290   constexpr bool kJitPoolNeedsPeers = true;
291   thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
292 
293   thread_pool_->SetPthreadPriority(kJitPoolThreadPthreadPriority);
294   thread_pool_->StartWorkers(Thread::Current());
295 }
296 
DeleteThreadPool()297 void Jit::DeleteThreadPool() {
298   Thread* self = Thread::Current();
299   DCHECK(Runtime::Current()->IsShuttingDown(self));
300   if (thread_pool_ != nullptr) {
301     ThreadPool* cache = nullptr;
302     {
303       ScopedSuspendAll ssa(__FUNCTION__);
304       // Clear thread_pool_ field while the threads are suspended.
305       // A mutator in the 'AddSamples' method will check against it.
306       cache = thread_pool_.release();
307     }
308     cache->StopWorkers(self);
309     cache->RemoveAllTasks(self);
310     // We could just suspend all threads, but we know those threads
311     // will finish in a short period, so it's not worth adding a suspend logic
312     // here. Besides, this is only done for shutdown.
313     cache->Wait(self, false, false);
314     delete cache;
315   }
316 }
317 
StartProfileSaver(const std::string & filename,const std::vector<std::string> & code_paths,const std::string & foreign_dex_profile_path,const std::string & app_dir)318 void Jit::StartProfileSaver(const std::string& filename,
319                             const std::vector<std::string>& code_paths,
320                             const std::string& foreign_dex_profile_path,
321                             const std::string& app_dir) {
322   if (save_profiling_info_) {
323     ProfileSaver::Start(filename, code_cache_.get(), code_paths, foreign_dex_profile_path, app_dir);
324   }
325 }
326 
StopProfileSaver()327 void Jit::StopProfileSaver() {
328   if (save_profiling_info_ && ProfileSaver::IsStarted()) {
329     ProfileSaver::Stop(dump_info_on_shutdown_);
330   }
331 }
332 
JitAtFirstUse()333 bool Jit::JitAtFirstUse() {
334   return HotMethodThreshold() == 0;
335 }
336 
CanInvokeCompiledCode(ArtMethod * method)337 bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
338   return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
339 }
340 
~Jit()341 Jit::~Jit() {
342   DCHECK(!save_profiling_info_ || !ProfileSaver::IsStarted());
343   if (dump_info_on_shutdown_) {
344     DumpInfo(LOG(INFO));
345   }
346   DeleteThreadPool();
347   if (jit_compiler_handle_ != nullptr) {
348     jit_unload_(jit_compiler_handle_);
349     jit_compiler_handle_ = nullptr;
350   }
351   if (jit_library_handle_ != nullptr) {
352     dlclose(jit_library_handle_);
353     jit_library_handle_ = nullptr;
354   }
355 }
356 
NewTypeLoadedIfUsingJit(mirror::Class * type)357 void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
358   if (!Runtime::Current()->UseJitCompilation()) {
359     // No need to notify if we only use the JIT to save profiles.
360     return;
361   }
362   jit::Jit* jit = Runtime::Current()->GetJit();
363   if (jit->generate_debug_info_) {
364     DCHECK(jit->jit_types_loaded_ != nullptr);
365     jit->jit_types_loaded_(jit->jit_compiler_handle_, &type, 1);
366   }
367 }
368 
DumpTypeInfoForLoadedTypes(ClassLinker * linker)369 void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
370   struct CollectClasses : public ClassVisitor {
371     bool operator()(mirror::Class* klass) override {
372       classes_.push_back(klass);
373       return true;
374     }
375     std::vector<mirror::Class*> classes_;
376   };
377 
378   if (generate_debug_info_) {
379     ScopedObjectAccess so(Thread::Current());
380 
381     CollectClasses visitor;
382     linker->VisitClasses(&visitor);
383     jit_types_loaded_(jit_compiler_handle_, visitor.classes_.data(), visitor.classes_.size());
384   }
385 }
386 
387 extern "C" void art_quick_osr_stub(void** stack,
388                                    uint32_t stack_size_in_bytes,
389                                    const uint8_t* native_pc,
390                                    JValue* result,
391                                    const char* shorty,
392                                    Thread* self);
393 
MaybeDoOnStackReplacement(Thread * thread,ArtMethod * method,uint32_t dex_pc,int32_t dex_pc_offset,JValue * result)394 bool Jit::MaybeDoOnStackReplacement(Thread* thread,
395                                     ArtMethod* method,
396                                     uint32_t dex_pc,
397                                     int32_t dex_pc_offset,
398                                     JValue* result) {
399   if (!kEnableOnStackReplacement) {
400     return false;
401   }
402 
403   Jit* jit = Runtime::Current()->GetJit();
404   if (jit == nullptr) {
405     return false;
406   }
407 
408   if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
409     // Don't attempt to do an OSR if we are close to the stack limit. Since
410     // the interpreter frames are still on stack, OSR has the potential
411     // to stack overflow even for a simple loop.
412     // b/27094810.
413     return false;
414   }
415 
416   // Get the actual Java method if this method is from a proxy class. The compiler
417   // and the JIT code cache do not expect methods from proxy classes.
418   method = method->GetInterfaceMethodIfProxy(sizeof(void*));
419 
420   // Cheap check if the method has been compiled already. That's an indicator that we should
421   // osr into it.
422   if (!jit->GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
423     return false;
424   }
425 
426   // Fetch some data before looking up for an OSR method. We don't want thread
427   // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
428   // method while we are being suspended.
429   const size_t number_of_vregs = method->GetCodeItem()->registers_size_;
430   const char* shorty = method->GetShorty();
431   std::string method_name(VLOG_IS_ON(jit) ? PrettyMethod(method) : "");
432   void** memory = nullptr;
433   size_t frame_size = 0;
434   ShadowFrame* shadow_frame = nullptr;
435   const uint8_t* native_pc = nullptr;
436 
437   {
438     ScopedAssertNoThreadSuspension sts(thread, "Holding OSR method");
439     const OatQuickMethodHeader* osr_method = jit->GetCodeCache()->LookupOsrMethodHeader(method);
440     if (osr_method == nullptr) {
441       // No osr method yet, just return to the interpreter.
442       return false;
443     }
444 
445     CodeInfo code_info = osr_method->GetOptimizedCodeInfo();
446     CodeInfoEncoding encoding = code_info.ExtractEncoding();
447 
448     // Find stack map starting at the target dex_pc.
449     StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc + dex_pc_offset, encoding);
450     if (!stack_map.IsValid()) {
451       // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
452       // hope that the next branch has one.
453       return false;
454     }
455 
456     // Before allowing the jump, make sure the debugger is not active to avoid jumping from
457     // interpreter to OSR while e.g. single stepping. Note that we could selectively disable
458     // OSR when single stepping, but that's currently hard to know at this point.
459     if (Dbg::IsDebuggerActive()) {
460       return false;
461     }
462 
463     // We found a stack map, now fill the frame with dex register values from the interpreter's
464     // shadow frame.
465     DexRegisterMap vreg_map =
466         code_info.GetDexRegisterMapOf(stack_map, encoding, number_of_vregs);
467 
468     frame_size = osr_method->GetFrameSizeInBytes();
469 
470     // Allocate memory to put shadow frame values. The osr stub will copy that memory to
471     // stack.
472     // Note that we could pass the shadow frame to the stub, and let it copy the values there,
473     // but that is engineering complexity not worth the effort for something like OSR.
474     memory = reinterpret_cast<void**>(malloc(frame_size));
475     CHECK(memory != nullptr);
476     memset(memory, 0, frame_size);
477 
478     // Art ABI: ArtMethod is at the bottom of the stack.
479     memory[0] = method;
480 
481     shadow_frame = thread->PopShadowFrame();
482     if (!vreg_map.IsValid()) {
483       // If we don't have a dex register map, then there are no live dex registers at
484       // this dex pc.
485     } else {
486       for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
487         DexRegisterLocation::Kind location =
488             vreg_map.GetLocationKind(vreg, number_of_vregs, code_info, encoding);
489         if (location == DexRegisterLocation::Kind::kNone) {
490           // Dex register is dead or uninitialized.
491           continue;
492         }
493 
494         if (location == DexRegisterLocation::Kind::kConstant) {
495           // We skip constants because the compiled code knows how to handle them.
496           continue;
497         }
498 
499         DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
500 
501         int32_t vreg_value = shadow_frame->GetVReg(vreg);
502         int32_t slot_offset = vreg_map.GetStackOffsetInBytes(vreg,
503                                                              number_of_vregs,
504                                                              code_info,
505                                                              encoding);
506         DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
507         DCHECK_GT(slot_offset, 0);
508         (reinterpret_cast<int32_t*>(memory))[slot_offset / sizeof(int32_t)] = vreg_value;
509       }
510     }
511 
512     native_pc = stack_map.GetNativePcOffset(encoding.stack_map_encoding) +
513         osr_method->GetEntryPoint();
514     VLOG(jit) << "Jumping to "
515               << method_name
516               << "@"
517               << std::hex << reinterpret_cast<uintptr_t>(native_pc);
518   }
519 
520   {
521     ManagedStack fragment;
522     thread->PushManagedStackFragment(&fragment);
523     (*art_quick_osr_stub)(memory,
524                           frame_size,
525                           native_pc,
526                           result,
527                           shorty,
528                           thread);
529 
530     if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
531       thread->DeoptimizeWithDeoptimizationException(result);
532     }
533     thread->PopManagedStackFragment(fragment);
534   }
535   free(memory);
536   thread->PushShadowFrame(shadow_frame);
537   VLOG(jit) << "Done running OSR code for " << method_name;
538   return true;
539 }
540 
AddMemoryUsage(ArtMethod * method,size_t bytes)541 void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
542   if (bytes > 4 * MB) {
543     LOG(INFO) << "Compiler allocated "
544               << PrettySize(bytes)
545               << " to compile "
546               << PrettyMethod(method);
547   }
548   MutexLock mu(Thread::Current(), lock_);
549   memory_use_.AddValue(bytes);
550 }
551 
552 class JitCompileTask FINAL : public Task {
553  public:
554   enum TaskKind {
555     kAllocateProfile,
556     kCompile,
557     kCompileOsr
558   };
559 
JitCompileTask(ArtMethod * method,TaskKind kind)560   JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind) {
561     ScopedObjectAccess soa(Thread::Current());
562     // Add a global ref to the class to prevent class unloading until compilation is done.
563     klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
564     CHECK(klass_ != nullptr);
565   }
566 
~JitCompileTask()567   ~JitCompileTask() {
568     ScopedObjectAccess soa(Thread::Current());
569     soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
570   }
571 
Run(Thread * self)572   void Run(Thread* self) OVERRIDE {
573     ScopedObjectAccess soa(self);
574     if (kind_ == kCompile) {
575       Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ false);
576     } else if (kind_ == kCompileOsr) {
577       Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ true);
578     } else {
579       DCHECK(kind_ == kAllocateProfile);
580       if (ProfilingInfo::Create(self, method_, /* retry_allocation */ true)) {
581         VLOG(jit) << "Start profiling " << PrettyMethod(method_);
582       }
583     }
584     ProfileSaver::NotifyJitActivity();
585   }
586 
Finalize()587   void Finalize() OVERRIDE {
588     delete this;
589   }
590 
591  private:
592   ArtMethod* const method_;
593   const TaskKind kind_;
594   jobject klass_;
595 
596   DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
597 };
598 
AddSamples(Thread * self,ArtMethod * method,uint16_t count,bool with_backedges)599 void Jit::AddSamples(Thread* self, ArtMethod* method, uint16_t count, bool with_backedges) {
600   if (thread_pool_ == nullptr) {
601     // Should only see this when shutting down.
602     DCHECK(Runtime::Current()->IsShuttingDown(self));
603     return;
604   }
605 
606   if (method->IsClassInitializer() || method->IsNative() || !method->IsCompilable()) {
607     // We do not want to compile such methods.
608     return;
609   }
610   DCHECK(thread_pool_ != nullptr);
611   DCHECK_GT(warm_method_threshold_, 0);
612   DCHECK_GT(hot_method_threshold_, warm_method_threshold_);
613   DCHECK_GT(osr_method_threshold_, hot_method_threshold_);
614   DCHECK_GE(priority_thread_weight_, 1);
615   DCHECK_LE(priority_thread_weight_, hot_method_threshold_);
616 
617   int32_t starting_count = method->GetCounter();
618   if (Jit::ShouldUsePriorityThreadWeight()) {
619     count *= priority_thread_weight_;
620   }
621   int32_t new_count = starting_count + count;   // int32 here to avoid wrap-around;
622   if (starting_count < warm_method_threshold_) {
623     if ((new_count >= warm_method_threshold_) &&
624         (method->GetProfilingInfo(sizeof(void*)) == nullptr)) {
625       bool success = ProfilingInfo::Create(self, method, /* retry_allocation */ false);
626       if (success) {
627         VLOG(jit) << "Start profiling " << PrettyMethod(method);
628       }
629 
630       if (thread_pool_ == nullptr) {
631         // Calling ProfilingInfo::Create might put us in a suspended state, which could
632         // lead to the thread pool being deleted when we are shutting down.
633         DCHECK(Runtime::Current()->IsShuttingDown(self));
634         return;
635       }
636 
637       if (!success) {
638         // We failed allocating. Instead of doing the collection on the Java thread, we push
639         // an allocation to a compiler thread, that will do the collection.
640         thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kAllocateProfile));
641       }
642     }
643     // Avoid jumping more than one state at a time.
644     new_count = std::min(new_count, hot_method_threshold_ - 1);
645   } else if (use_jit_compilation_) {
646     if (starting_count < hot_method_threshold_) {
647       if ((new_count >= hot_method_threshold_) &&
648           !code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
649         DCHECK(thread_pool_ != nullptr);
650         thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompile));
651       }
652       // Avoid jumping more than one state at a time.
653       new_count = std::min(new_count, osr_method_threshold_ - 1);
654     } else if (starting_count < osr_method_threshold_) {
655       if (!with_backedges) {
656         // If the samples don't contain any back edge, we don't increment the hotness.
657         return;
658       }
659       if ((new_count >= osr_method_threshold_) &&  !code_cache_->IsOsrCompiled(method)) {
660         DCHECK(thread_pool_ != nullptr);
661         thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompileOsr));
662       }
663     }
664   }
665   // Update hotness counter
666   method->SetCounter(new_count);
667 }
668 
MethodEntered(Thread * thread,ArtMethod * method)669 void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
670   Runtime* runtime = Runtime::Current();
671   if (UNLIKELY(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse())) {
672     // The compiler requires a ProfilingInfo object.
673     ProfilingInfo::Create(thread, method, /* retry_allocation */ true);
674     JitCompileTask compile_task(method, JitCompileTask::kCompile);
675     compile_task.Run(thread);
676     return;
677   }
678 
679   ProfilingInfo* profiling_info = method->GetProfilingInfo(sizeof(void*));
680   // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
681   // instead of interpreting the method.
682   if ((profiling_info != nullptr) && (profiling_info->GetSavedEntryPoint() != nullptr)) {
683     Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
684         method, profiling_info->GetSavedEntryPoint());
685   } else {
686     AddSamples(thread, method, 1, /* with_backedges */false);
687   }
688 }
689 
InvokeVirtualOrInterface(Thread * thread,mirror::Object * this_object,ArtMethod * caller,uint32_t dex_pc,ArtMethod * callee ATTRIBUTE_UNUSED)690 void Jit::InvokeVirtualOrInterface(Thread* thread,
691                                    mirror::Object* this_object,
692                                    ArtMethod* caller,
693                                    uint32_t dex_pc,
694                                    ArtMethod* callee ATTRIBUTE_UNUSED) {
695   ScopedAssertNoThreadSuspension ants(thread, __FUNCTION__);
696   DCHECK(this_object != nullptr);
697   ProfilingInfo* info = caller->GetProfilingInfo(sizeof(void*));
698   if (info != nullptr) {
699     info->AddInvokeInfo(dex_pc, this_object->GetClass());
700   }
701 }
702 
WaitForCompilationToFinish(Thread * self)703 void Jit::WaitForCompilationToFinish(Thread* self) {
704   if (thread_pool_ != nullptr) {
705     thread_pool_->Wait(self, false, false);
706   }
707 }
708 
709 }  // namespace jit
710 }  // namespace art
711