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 "base/enums.h"
23 #include "base/file_utils.h"
24 #include "base/logging.h"  // For VLOG.
25 #include "base/memfd.h"
26 #include "base/memory_tool.h"
27 #include "base/runtime_debug.h"
28 #include "base/scoped_flock.h"
29 #include "base/utils.h"
30 #include "class_root-inl.h"
31 #include "compilation_kind.h"
32 #include "debugger.h"
33 #include "dex/type_lookup_table.h"
34 #include "gc/space/image_space.h"
35 #include "entrypoints/entrypoint_utils-inl.h"
36 #include "entrypoints/runtime_asm_entrypoints.h"
37 #include "image-inl.h"
38 #include "interpreter/interpreter.h"
39 #include "jit-inl.h"
40 #include "jit_code_cache.h"
41 #include "jni/java_vm_ext.h"
42 #include "mirror/method_handle_impl.h"
43 #include "mirror/var_handle.h"
44 #include "oat_file.h"
45 #include "oat_file_manager.h"
46 #include "oat_quick_method_header.h"
47 #include "profile/profile_boot_info.h"
48 #include "profile/profile_compilation_info.h"
49 #include "profile_saver.h"
50 #include "runtime.h"
51 #include "runtime_options.h"
52 #include "stack.h"
53 #include "stack_map.h"
54 #include "thread-inl.h"
55 #include "thread_list.h"
56 
57 using android::base::unique_fd;
58 
59 namespace art {
60 namespace jit {
61 
62 static constexpr bool kEnableOnStackReplacement = true;
63 
64 // Maximum permitted threshold value.
65 static constexpr uint32_t kJitMaxThreshold = std::numeric_limits<uint16_t>::max();
66 
67 // Different compilation threshold constants. These can be overridden on the command line.
68 
69 // Non-debug default
70 static constexpr uint32_t kJitDefaultCompileThreshold = 20 * kJitSamplesBatchSize;
71 // Fast-debug build.
72 static constexpr uint32_t kJitStressDefaultCompileThreshold = 2 * kJitSamplesBatchSize;
73 // Slow-debug build.
74 static constexpr uint32_t kJitSlowStressDefaultCompileThreshold = 2;
75 
76 // Different warm-up threshold constants. These default to the equivalent compile thresholds divided
77 // by 2, but can be overridden at the command-line.
78 static constexpr uint32_t kJitDefaultWarmUpThreshold = kJitDefaultCompileThreshold / 2;
79 static constexpr uint32_t kJitStressDefaultWarmUpThreshold = kJitStressDefaultCompileThreshold / 2;
80 static constexpr uint32_t kJitSlowStressDefaultWarmUpThreshold =
81     kJitSlowStressDefaultCompileThreshold / 2;
82 
83 DEFINE_RUNTIME_DEBUG_FLAG(Jit, kSlowMode);
84 
85 // JIT compiler
86 void* Jit::jit_library_handle_ = nullptr;
87 JitCompilerInterface* Jit::jit_compiler_ = nullptr;
88 JitCompilerInterface* (*Jit::jit_load_)(void) = nullptr;
89 
CreateFromRuntimeArguments(const RuntimeArgumentMap & options)90 JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
91   auto* jit_options = new JitOptions;
92   jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
93   jit_options->use_tiered_jit_compilation_ =
94       options.GetOrDefault(RuntimeArgumentMap::UseTieredJitCompilation);
95 
96   jit_options->code_cache_initial_capacity_ =
97       options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
98   jit_options->code_cache_max_capacity_ =
99       options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
100   jit_options->dump_info_on_shutdown_ =
101       options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
102   jit_options->profile_saver_options_ =
103       options.GetOrDefault(RuntimeArgumentMap::ProfileSaverOpts);
104   jit_options->thread_pool_pthread_priority_ =
105       options.GetOrDefault(RuntimeArgumentMap::JITPoolThreadPthreadPriority);
106 
107   // Set default compile threshold to aid with checking defaults.
108   jit_options->compile_threshold_ =
109       kIsDebugBuild
110       ? (Jit::kSlowMode
111          ? kJitSlowStressDefaultCompileThreshold
112          : kJitStressDefaultCompileThreshold)
113       : kJitDefaultCompileThreshold;
114 
115   // When not running in slow-mode, thresholds are quantized to kJitSamplesbatchsize.
116   const uint32_t kJitThresholdStep = Jit::kSlowMode ? 1u : kJitSamplesBatchSize;
117 
118   // Set default warm-up threshold to aid with checking defaults.
119   jit_options->warmup_threshold_ =
120       kIsDebugBuild ? (Jit::kSlowMode
121                        ? kJitSlowStressDefaultWarmUpThreshold
122                        : kJitStressDefaultWarmUpThreshold)
123       : kJitDefaultWarmUpThreshold;
124 
125   // Warmup threshold should be less than compile threshold (so long as compile threshold is not
126   // zero == JIT-on-first-use).
127   DCHECK_LT(jit_options->warmup_threshold_, jit_options->compile_threshold_);
128   DCHECK_EQ(RoundUp(jit_options->warmup_threshold_, kJitThresholdStep),
129             jit_options->warmup_threshold_);
130 
131   if (options.Exists(RuntimeArgumentMap::JITCompileThreshold)) {
132     jit_options->compile_threshold_ = *options.Get(RuntimeArgumentMap::JITCompileThreshold);
133   }
134   jit_options->compile_threshold_ = RoundUp(jit_options->compile_threshold_, kJitThresholdStep);
135 
136   if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
137     jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
138   }
139   jit_options->warmup_threshold_ = RoundUp(jit_options->warmup_threshold_, kJitThresholdStep);
140 
141   if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
142     jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
143   } else {
144     jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
145     if (jit_options->osr_threshold_ > kJitMaxThreshold) {
146       jit_options->osr_threshold_ =
147           RoundDown(kJitMaxThreshold, kJitThresholdStep);
148     }
149   }
150   jit_options->osr_threshold_ = RoundUp(jit_options->osr_threshold_, kJitThresholdStep);
151 
152   // Enforce ordering constraints between thresholds if not jit-on-first-use (when the compile
153   // threshold is 0).
154   if (jit_options->compile_threshold_ != 0) {
155     // Clamp thresholds such that OSR > compile > warm-up (see Jit::MaybeCompileMethod).
156     jit_options->osr_threshold_ = std::clamp(jit_options->osr_threshold_,
157                                              2u * kJitThresholdStep,
158                                              RoundDown(kJitMaxThreshold, kJitThresholdStep));
159     jit_options->compile_threshold_ = std::clamp(jit_options->compile_threshold_,
160                                                  kJitThresholdStep,
161                                                  jit_options->osr_threshold_ - kJitThresholdStep);
162     jit_options->warmup_threshold_ =
163         std::clamp(jit_options->warmup_threshold_,
164                    0u,
165                    jit_options->compile_threshold_ - kJitThresholdStep);
166   }
167 
168   if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
169     jit_options->priority_thread_weight_ =
170         *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
171     if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
172       LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
173     } else if (jit_options->priority_thread_weight_ == 0) {
174       LOG(FATAL) << "Priority thread weight cannot be 0.";
175     }
176   } else {
177     jit_options->priority_thread_weight_ = std::max(
178         jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
179         static_cast<size_t>(1));
180   }
181 
182   if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
183     jit_options->invoke_transition_weight_ =
184         *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
185     if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
186       LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
187     } else if (jit_options->invoke_transition_weight_  == 0) {
188       LOG(FATAL) << "Invoke transition weight cannot be 0.";
189     }
190   } else {
191     jit_options->invoke_transition_weight_ = std::max(
192         jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
193         static_cast<size_t>(1));
194   }
195 
196   return jit_options;
197 }
198 
DumpInfo(std::ostream & os)199 void Jit::DumpInfo(std::ostream& os) {
200   code_cache_->Dump(os);
201   cumulative_timings_.Dump(os);
202   MutexLock mu(Thread::Current(), lock_);
203   memory_use_.PrintMemoryUse(os);
204 }
205 
DumpForSigQuit(std::ostream & os)206 void Jit::DumpForSigQuit(std::ostream& os) {
207   DumpInfo(os);
208   ProfileSaver::DumpInstanceInfo(os);
209 }
210 
AddTimingLogger(const TimingLogger & logger)211 void Jit::AddTimingLogger(const TimingLogger& logger) {
212   cumulative_timings_.AddLogger(logger);
213 }
214 
Jit(JitCodeCache * code_cache,JitOptions * options)215 Jit::Jit(JitCodeCache* code_cache, JitOptions* options)
216     : code_cache_(code_cache),
217       options_(options),
218       boot_completed_lock_("Jit::boot_completed_lock_"),
219       cumulative_timings_("JIT timings"),
220       memory_use_("Memory used for compilation", 16),
221       lock_("JIT memory use lock"),
222       zygote_mapping_methods_(),
223       fd_methods_(-1),
224       fd_methods_size_(0) {}
225 
Create(JitCodeCache * code_cache,JitOptions * options)226 Jit* Jit::Create(JitCodeCache* code_cache, JitOptions* options) {
227   if (jit_load_ == nullptr) {
228     LOG(WARNING) << "Not creating JIT: library not loaded";
229     return nullptr;
230   }
231   jit_compiler_ = (jit_load_)();
232   if (jit_compiler_ == nullptr) {
233     LOG(WARNING) << "Not creating JIT: failed to allocate a compiler";
234     return nullptr;
235   }
236   std::unique_ptr<Jit> jit(new Jit(code_cache, options));
237 
238   // If the code collector is enabled, check if that still holds:
239   // With 'perf', we want a 1-1 mapping between an address and a method.
240   // We aren't able to keep method pointers live during the instrumentation method entry trampoline
241   // so we will just disable jit-gc if we are doing that.
242   if (code_cache->GetGarbageCollectCode()) {
243     code_cache->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
244         !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
245   }
246 
247   VLOG(jit) << "JIT created with initial_capacity="
248       << PrettySize(options->GetCodeCacheInitialCapacity())
249       << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
250       << ", compile_threshold=" << options->GetCompileThreshold()
251       << ", profile_saver_options=" << options->GetProfileSaverOptions();
252 
253   // We want to know whether the compiler is compiling baseline, as this
254   // affects how we GC ProfilingInfos.
255   for (const std::string& option : Runtime::Current()->GetCompilerOptions()) {
256     if (option == "--baseline") {
257       options->SetUseBaselineCompiler();
258       break;
259     }
260   }
261 
262   // Notify native debugger about the classes already loaded before the creation of the jit.
263   jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
264   return jit.release();
265 }
266 
267 template <typename T>
LoadSymbol(T * address,const char * name,std::string * error_msg)268 bool Jit::LoadSymbol(T* address, const char* name, std::string* error_msg) {
269   *address = reinterpret_cast<T>(dlsym(jit_library_handle_, name));
270   if (*address == nullptr) {
271     *error_msg = std::string("JIT couldn't find ") + name + std::string(" entry point");
272     return false;
273   }
274   return true;
275 }
276 
LoadCompilerLibrary(std::string * error_msg)277 bool Jit::LoadCompilerLibrary(std::string* error_msg) {
278   jit_library_handle_ = dlopen(
279       kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
280   if (jit_library_handle_ == nullptr) {
281     std::ostringstream oss;
282     oss << "JIT could not load libart-compiler.so: " << dlerror();
283     *error_msg = oss.str();
284     return false;
285   }
286   if (!LoadSymbol(&jit_load_, "jit_load", error_msg)) {
287     dlclose(jit_library_handle_);
288     return false;
289   }
290   return true;
291 }
292 
CompileMethod(ArtMethod * method,Thread * self,CompilationKind compilation_kind,bool prejit)293 bool Jit::CompileMethod(ArtMethod* method,
294                         Thread* self,
295                         CompilationKind compilation_kind,
296                         bool prejit) {
297   DCHECK(Runtime::Current()->UseJitCompilation());
298   DCHECK(!method->IsRuntimeMethod());
299 
300   RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
301   // Don't compile the method if it has breakpoints.
302   if (cb->IsMethodBeingInspected(method) && !cb->IsMethodSafeToJit(method)) {
303     VLOG(jit) << "JIT not compiling " << method->PrettyMethod()
304               << " due to not being safe to jit according to runtime-callbacks. For example, there"
305               << " could be breakpoints in this method.";
306     return false;
307   }
308 
309   if (!method->IsCompilable()) {
310     DCHECK(method->GetDeclaringClass()->IsObsoleteObject() ||
311            method->IsProxyMethod()) << method->PrettyMethod();
312     VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to method being made "
313               << "obsolete while waiting for JIT task to run. This probably happened due to "
314               << "concurrent structural class redefinition.";
315     return false;
316   }
317 
318   // Don't compile the method if we are supposed to be deoptimized.
319   instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
320   if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
321     VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to deoptimization";
322     return false;
323   }
324 
325   JitMemoryRegion* region = GetCodeCache()->GetCurrentRegion();
326   if ((compilation_kind == CompilationKind::kOsr) && GetCodeCache()->IsSharedRegion(*region)) {
327     VLOG(jit) << "JIT not osr compiling "
328               << method->PrettyMethod()
329               << " due to using shared region";
330     return false;
331   }
332 
333   // If we get a request to compile a proxy method, we pass the actual Java method
334   // of that proxy method, as the compiler does not expect a proxy method.
335   ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
336   if (!code_cache_->NotifyCompilationOf(
337           method_to_compile, self, compilation_kind, prejit, region)) {
338     return false;
339   }
340 
341   VLOG(jit) << "Compiling method "
342             << ArtMethod::PrettyMethod(method_to_compile)
343             << " kind=" << compilation_kind;
344   bool success = jit_compiler_->CompileMethod(self, region, method_to_compile, compilation_kind);
345   code_cache_->DoneCompiling(method_to_compile, self, compilation_kind);
346   if (!success) {
347     VLOG(jit) << "Failed to compile method "
348               << ArtMethod::PrettyMethod(method_to_compile)
349               << " kind=" << compilation_kind;
350   }
351   if (kIsDebugBuild) {
352     if (self->IsExceptionPending()) {
353       mirror::Throwable* exception = self->GetException();
354       LOG(FATAL) << "No pending exception expected after compiling "
355                  << ArtMethod::PrettyMethod(method)
356                  << ": "
357                  << exception->Dump();
358     }
359   }
360   return success;
361 }
362 
WaitForWorkersToBeCreated()363 void Jit::WaitForWorkersToBeCreated() {
364   if (thread_pool_ != nullptr) {
365     thread_pool_->WaitForWorkersToBeCreated();
366   }
367 }
368 
DeleteThreadPool()369 void Jit::DeleteThreadPool() {
370   Thread* self = Thread::Current();
371   if (thread_pool_ != nullptr) {
372     std::unique_ptr<ThreadPool> pool;
373     {
374       ScopedSuspendAll ssa(__FUNCTION__);
375       // Clear thread_pool_ field while the threads are suspended.
376       // A mutator in the 'AddSamples' method will check against it.
377       pool = std::move(thread_pool_);
378     }
379 
380     // When running sanitized, let all tasks finish to not leak. Otherwise just clear the queue.
381     if (!kRunningOnMemoryTool) {
382       pool->StopWorkers(self);
383       pool->RemoveAllTasks(self);
384     }
385     // We could just suspend all threads, but we know those threads
386     // will finish in a short period, so it's not worth adding a suspend logic
387     // here. Besides, this is only done for shutdown.
388     pool->Wait(self, false, false);
389   }
390 }
391 
StartProfileSaver(const std::string & filename,const std::vector<std::string> & code_paths)392 void Jit::StartProfileSaver(const std::string& filename,
393                             const std::vector<std::string>& code_paths) {
394   if (options_->GetSaveProfilingInfo()) {
395     ProfileSaver::Start(options_->GetProfileSaverOptions(), filename, code_cache_, code_paths);
396   }
397 }
398 
StopProfileSaver()399 void Jit::StopProfileSaver() {
400   if (options_->GetSaveProfilingInfo() && ProfileSaver::IsStarted()) {
401     ProfileSaver::Stop(options_->DumpJitInfoOnShutdown());
402   }
403 }
404 
JitAtFirstUse()405 bool Jit::JitAtFirstUse() {
406   return HotMethodThreshold() == 0;
407 }
408 
CanInvokeCompiledCode(ArtMethod * method)409 bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
410   return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
411 }
412 
~Jit()413 Jit::~Jit() {
414   DCHECK(!options_->GetSaveProfilingInfo() || !ProfileSaver::IsStarted());
415   if (options_->DumpJitInfoOnShutdown()) {
416     DumpInfo(LOG_STREAM(INFO));
417     Runtime::Current()->DumpDeoptimizations(LOG_STREAM(INFO));
418   }
419   DeleteThreadPool();
420   if (jit_compiler_ != nullptr) {
421     delete jit_compiler_;
422     jit_compiler_ = nullptr;
423   }
424   if (jit_library_handle_ != nullptr) {
425     dlclose(jit_library_handle_);
426     jit_library_handle_ = nullptr;
427   }
428 }
429 
NewTypeLoadedIfUsingJit(mirror::Class * type)430 void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
431   if (!Runtime::Current()->UseJitCompilation()) {
432     // No need to notify if we only use the JIT to save profiles.
433     return;
434   }
435   jit::Jit* jit = Runtime::Current()->GetJit();
436   if (jit->jit_compiler_->GenerateDebugInfo()) {
437     jit_compiler_->TypesLoaded(&type, 1);
438   }
439 }
440 
DumpTypeInfoForLoadedTypes(ClassLinker * linker)441 void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
442   struct CollectClasses : public ClassVisitor {
443     bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
444       classes_.push_back(klass.Ptr());
445       return true;
446     }
447     std::vector<mirror::Class*> classes_;
448   };
449 
450   if (jit_compiler_->GenerateDebugInfo()) {
451     ScopedObjectAccess so(Thread::Current());
452 
453     CollectClasses visitor;
454     linker->VisitClasses(&visitor);
455     jit_compiler_->TypesLoaded(visitor.classes_.data(), visitor.classes_.size());
456   }
457 }
458 
459 extern "C" void art_quick_osr_stub(void** stack,
460                                    size_t stack_size_in_bytes,
461                                    const uint8_t* native_pc,
462                                    JValue* result,
463                                    const char* shorty,
464                                    Thread* self);
465 
PrepareForOsr(ArtMethod * method,uint32_t dex_pc,uint32_t * vregs)466 OsrData* Jit::PrepareForOsr(ArtMethod* method, uint32_t dex_pc, uint32_t* vregs) {
467   if (!kEnableOnStackReplacement) {
468     return nullptr;
469   }
470 
471   // Cheap check if the method has been compiled already. That's an indicator that we should
472   // osr into it.
473   if (!GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
474     return nullptr;
475   }
476 
477   // Fetch some data before looking up for an OSR method. We don't want thread
478   // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
479   // method while we are being suspended.
480   CodeItemDataAccessor accessor(method->DexInstructionData());
481   const size_t number_of_vregs = accessor.RegistersSize();
482   std::string method_name(VLOG_IS_ON(jit) ? method->PrettyMethod() : "");
483   OsrData* osr_data = nullptr;
484 
485   {
486     ScopedAssertNoThreadSuspension sts("Holding OSR method");
487     const OatQuickMethodHeader* osr_method = GetCodeCache()->LookupOsrMethodHeader(method);
488     if (osr_method == nullptr) {
489       // No osr method yet, just return to the interpreter.
490       return nullptr;
491     }
492 
493     CodeInfo code_info(osr_method);
494 
495     // Find stack map starting at the target dex_pc.
496     StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc);
497     if (!stack_map.IsValid()) {
498       // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
499       // hope that the next branch has one.
500       return nullptr;
501     }
502 
503     // We found a stack map, now fill the frame with dex register values from the interpreter's
504     // shadow frame.
505     DexRegisterMap vreg_map = code_info.GetDexRegisterMapOf(stack_map);
506     DCHECK_EQ(vreg_map.size(), number_of_vregs);
507 
508     size_t frame_size = osr_method->GetFrameSizeInBytes();
509 
510     // Allocate memory to put shadow frame values. The osr stub will copy that memory to
511     // stack.
512     // Note that we could pass the shadow frame to the stub, and let it copy the values there,
513     // but that is engineering complexity not worth the effort for something like OSR.
514     osr_data = reinterpret_cast<OsrData*>(malloc(sizeof(OsrData) + frame_size));
515     if (osr_data == nullptr) {
516       return nullptr;
517     }
518     memset(osr_data, 0, sizeof(OsrData) + frame_size);
519     osr_data->frame_size = frame_size;
520 
521     // Art ABI: ArtMethod is at the bottom of the stack.
522     osr_data->memory[0] = method;
523 
524     if (vreg_map.empty()) {
525       // If we don't have a dex register map, then there are no live dex registers at
526       // this dex pc.
527     } else {
528       for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
529         DexRegisterLocation::Kind location = vreg_map[vreg].GetKind();
530         if (location == DexRegisterLocation::Kind::kNone) {
531           // Dex register is dead or uninitialized.
532           continue;
533         }
534 
535         if (location == DexRegisterLocation::Kind::kConstant) {
536           // We skip constants because the compiled code knows how to handle them.
537           continue;
538         }
539 
540         DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
541 
542         int32_t vreg_value = vregs[vreg];
543         int32_t slot_offset = vreg_map[vreg].GetStackOffsetInBytes();
544         DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
545         DCHECK_GT(slot_offset, 0);
546         (reinterpret_cast<int32_t*>(osr_data->memory))[slot_offset / sizeof(int32_t)] = vreg_value;
547       }
548     }
549 
550     osr_data->native_pc = stack_map.GetNativePcOffset(kRuntimeISA) +
551         osr_method->GetEntryPoint();
552     VLOG(jit) << "Jumping to "
553               << method_name
554               << "@"
555               << std::hex << reinterpret_cast<uintptr_t>(osr_data->native_pc);
556   }
557   return osr_data;
558 }
559 
MaybeDoOnStackReplacement(Thread * thread,ArtMethod * method,uint32_t dex_pc,int32_t dex_pc_offset,JValue * result)560 bool Jit::MaybeDoOnStackReplacement(Thread* thread,
561                                     ArtMethod* method,
562                                     uint32_t dex_pc,
563                                     int32_t dex_pc_offset,
564                                     JValue* result) {
565   Jit* jit = Runtime::Current()->GetJit();
566   if (jit == nullptr) {
567     return false;
568   }
569 
570   if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
571     // Don't attempt to do an OSR if we are close to the stack limit. Since
572     // the interpreter frames are still on stack, OSR has the potential
573     // to stack overflow even for a simple loop.
574     // b/27094810.
575     return false;
576   }
577 
578   // Get the actual Java method if this method is from a proxy class. The compiler
579   // and the JIT code cache do not expect methods from proxy classes.
580   method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
581 
582   // Before allowing the jump, make sure no code is actively inspecting the method to avoid
583   // jumping from interpreter to OSR while e.g. single stepping. Note that we could selectively
584   // disable OSR when single stepping, but that's currently hard to know at this point.
585   if (Runtime::Current()->GetRuntimeCallbacks()->IsMethodBeingInspected(method)) {
586     return false;
587   }
588 
589   ShadowFrame* shadow_frame = thread->GetManagedStack()->GetTopShadowFrame();
590   OsrData* osr_data = jit->PrepareForOsr(method,
591                                          dex_pc + dex_pc_offset,
592                                          shadow_frame->GetVRegArgs(0));
593 
594   if (osr_data == nullptr) {
595     return false;
596   }
597 
598   {
599     thread->PopShadowFrame();
600     ManagedStack fragment;
601     thread->PushManagedStackFragment(&fragment);
602     (*art_quick_osr_stub)(osr_data->memory,
603                           osr_data->frame_size,
604                           osr_data->native_pc,
605                           result,
606                           method->GetShorty(),
607                           thread);
608 
609     if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
610       thread->DeoptimizeWithDeoptimizationException(result);
611     }
612     thread->PopManagedStackFragment(fragment);
613   }
614   free(osr_data);
615   thread->PushShadowFrame(shadow_frame);
616   VLOG(jit) << "Done running OSR code for " << method->PrettyMethod();
617   return true;
618 }
619 
AddMemoryUsage(ArtMethod * method,size_t bytes)620 void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
621   if (bytes > 4 * MB) {
622     LOG(INFO) << "Compiler allocated "
623               << PrettySize(bytes)
624               << " to compile "
625               << ArtMethod::PrettyMethod(method);
626   }
627   MutexLock mu(Thread::Current(), lock_);
628   memory_use_.AddValue(bytes);
629 }
630 
NotifyZygoteCompilationDone()631 void Jit::NotifyZygoteCompilationDone() {
632   if (fd_methods_ == -1) {
633     return;
634   }
635 
636   size_t offset = 0;
637   for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
638     const ImageHeader& header = space->GetImageHeader();
639     const ImageSection& section = header.GetMethodsSection();
640     // Because mremap works at page boundaries, we can only handle methods
641     // within a page range. For methods that falls above or below the range,
642     // the child processes will copy their contents to their private mapping
643     // in `child_mapping_methods`. See `MapBootImageMethods`.
644     uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
645     uint8_t* page_end =
646         AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
647     if (page_end > page_start) {
648       uint64_t capacity = page_end - page_start;
649       memcpy(zygote_mapping_methods_.Begin() + offset, page_start, capacity);
650       offset += capacity;
651     }
652   }
653 
654   // Do an msync to ensure we are not affected by writes still being in caches.
655   if (msync(zygote_mapping_methods_.Begin(), fd_methods_size_, MS_SYNC) != 0) {
656     PLOG(WARNING) << "Failed to sync boot image methods memory";
657     code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
658     return;
659   }
660 
661   // We don't need the shared mapping anymore, and we need to drop it in case
662   // the file hasn't been sealed writable.
663   zygote_mapping_methods_ = MemMap::Invalid();
664 
665   // Seal writes now. Zygote and children will map the memory private in order
666   // to write to it.
667   if (fcntl(fd_methods_, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_WRITE) == -1) {
668     PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
669     code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
670     return;
671   }
672 
673   std::string error_str;
674   MemMap child_mapping_methods = MemMap::MapFile(
675       fd_methods_size_,
676       PROT_READ | PROT_WRITE,
677       MAP_PRIVATE,
678       fd_methods_,
679       /* start= */ 0,
680       /* low_4gb= */ false,
681       "boot-image-methods",
682       &error_str);
683 
684   if (!child_mapping_methods.IsValid()) {
685     LOG(WARNING) << "Failed to create child mapping of boot image methods: " << error_str;
686     code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
687     return;
688   }
689 
690   // Ensure the contents are the same as before: there was a window between
691   // the memcpy and the sealing where other processes could have changed the
692   // contents.
693   // Note this would not be needed if we could have used F_SEAL_FUTURE_WRITE,
694   // see b/143833776.
695   offset = 0;
696   for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
697     const ImageHeader& header = space->GetImageHeader();
698     const ImageSection& section = header.GetMethodsSection();
699     // Because mremap works at page boundaries, we can only handle methods
700     // within a page range. For methods that falls above or below the range,
701     // the child processes will copy their contents to their private mapping
702     // in `child_mapping_methods`. See `MapBootImageMethods`.
703     uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
704     uint8_t* page_end =
705         AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
706     if (page_end > page_start) {
707       uint64_t capacity = page_end - page_start;
708       if (memcmp(child_mapping_methods.Begin() + offset, page_start, capacity) != 0) {
709         LOG(WARNING) << "Contents differ in boot image methods data";
710         code_cache_->GetZygoteMap()->SetCompilationState(
711             ZygoteCompilationState::kNotifiedFailure);
712         return;
713       }
714       offset += capacity;
715     }
716   }
717 
718   // Future spawned processes don't need the fd anymore.
719   fd_methods_.reset();
720 
721   // In order to have the zygote and children share the memory, we also remap
722   // the memory into the zygote process.
723   offset = 0;
724   for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
725     const ImageHeader& header = space->GetImageHeader();
726     const ImageSection& section = header.GetMethodsSection();
727     // Because mremap works at page boundaries, we can only handle methods
728     // within a page range. For methods that falls above or below the range,
729     // the child processes will copy their contents to their private mapping
730     // in `child_mapping_methods`. See `MapBootImageMethods`.
731     uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
732     uint8_t* page_end =
733         AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
734     if (page_end > page_start) {
735       uint64_t capacity = page_end - page_start;
736       if (mremap(child_mapping_methods.Begin() + offset,
737                  capacity,
738                  capacity,
739                  MREMAP_FIXED | MREMAP_MAYMOVE,
740                  page_start) == MAP_FAILED) {
741         // Failing to remap is safe as the process will just use the old
742         // contents.
743         PLOG(WARNING) << "Failed mremap of boot image methods of " << space->GetImageFilename();
744       }
745       offset += capacity;
746     }
747   }
748 
749   LOG(INFO) << "Successfully notified child processes on sharing boot image methods";
750 
751   // Mark that compilation of boot classpath is done, and memory can now be
752   // shared. Other processes will pick up this information.
753   code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedOk);
754 
755   // The private mapping created for this process has been mremaped. We can
756   // reset it.
757   child_mapping_methods.Reset();
758 }
759 
760 class JitCompileTask final : public Task {
761  public:
762   enum class TaskKind {
763     kAllocateProfile,
764     kCompile,
765     kPreCompile,
766   };
767 
JitCompileTask(ArtMethod * method,TaskKind task_kind,CompilationKind compilation_kind)768   JitCompileTask(ArtMethod* method, TaskKind task_kind, CompilationKind compilation_kind)
769       : method_(method), kind_(task_kind), compilation_kind_(compilation_kind), klass_(nullptr) {
770     ScopedObjectAccess soa(Thread::Current());
771     // For a non-bootclasspath class, add a global ref to the class to prevent class unloading
772     // until compilation is done.
773     // When we precompile, this is either with boot classpath methods, or main
774     // class loader methods, so we don't need to keep a global reference.
775     if (method->GetDeclaringClass()->GetClassLoader() != nullptr &&
776         kind_ != TaskKind::kPreCompile) {
777       klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
778       CHECK(klass_ != nullptr);
779     }
780   }
781 
~JitCompileTask()782   ~JitCompileTask() {
783     if (klass_ != nullptr) {
784       ScopedObjectAccess soa(Thread::Current());
785       soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
786     }
787   }
788 
Run(Thread * self)789   void Run(Thread* self) override {
790     {
791       ScopedObjectAccess soa(self);
792       switch (kind_) {
793         case TaskKind::kCompile:
794         case TaskKind::kPreCompile: {
795           Runtime::Current()->GetJit()->CompileMethod(
796               method_,
797               self,
798               compilation_kind_,
799               /* prejit= */ (kind_ == TaskKind::kPreCompile));
800           break;
801         }
802         case TaskKind::kAllocateProfile: {
803           if (ProfilingInfo::Create(self, method_, /* retry_allocation= */ true)) {
804             VLOG(jit) << "Start profiling " << ArtMethod::PrettyMethod(method_);
805           }
806           break;
807         }
808       }
809     }
810     ProfileSaver::NotifyJitActivity();
811   }
812 
Finalize()813   void Finalize() override {
814     delete this;
815   }
816 
817  private:
818   ArtMethod* const method_;
819   const TaskKind kind_;
820   const CompilationKind compilation_kind_;
821   jobject klass_;
822 
823   DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
824 };
825 
GetProfileFile(const std::string & dex_location)826 static std::string GetProfileFile(const std::string& dex_location) {
827   // Hardcoded assumption where the profile file is.
828   // TODO(ngeoffray): this is brittle and we would need to change change if we
829   // wanted to do more eager JITting of methods in a profile. This is
830   // currently only for system server.
831   return dex_location + ".prof";
832 }
833 
GetBootProfileFile(const std::string & profile)834 static std::string GetBootProfileFile(const std::string& profile) {
835   // The boot profile can be found next to the compilation profile, with a
836   // different extension.
837   return ReplaceFileExtension(profile, "bprof");
838 }
839 
840 /**
841  * A JIT task to run after all profile compilation is done.
842  */
843 class JitDoneCompilingProfileTask final : public SelfDeletingTask {
844  public:
JitDoneCompilingProfileTask(const std::vector<const DexFile * > & dex_files)845   explicit JitDoneCompilingProfileTask(const std::vector<const DexFile*>& dex_files)
846       : dex_files_(dex_files) {}
847 
Run(Thread * self ATTRIBUTE_UNUSED)848   void Run(Thread* self ATTRIBUTE_UNUSED) override {
849     // Madvise DONTNEED dex files now that we're done compiling methods.
850     for (const DexFile* dex_file : dex_files_) {
851       if (IsAddressKnownBackedByFileOrShared(dex_file->Begin())) {
852         int result = madvise(const_cast<uint8_t*>(AlignDown(dex_file->Begin(), kPageSize)),
853                              RoundUp(dex_file->Size(), kPageSize),
854                              MADV_DONTNEED);
855         if (result == -1) {
856           PLOG(WARNING) << "Madvise failed";
857         }
858       }
859     }
860 
861     if (Runtime::Current()->IsZygote()) {
862       // Record that we are done compiling the profile.
863       Runtime::Current()->GetJit()->GetCodeCache()->GetZygoteMap()->SetCompilationState(
864           ZygoteCompilationState::kDone);
865     }
866   }
867 
868  private:
869   std::vector<const DexFile*> dex_files_;
870 
871   DISALLOW_COPY_AND_ASSIGN(JitDoneCompilingProfileTask);
872 };
873 
874 /**
875  * A JIT task to run Java verification of boot classpath classes that were not
876  * verified at compile-time.
877  */
878 class ZygoteVerificationTask final : public Task {
879  public:
ZygoteVerificationTask()880   ZygoteVerificationTask() {}
881 
Run(Thread * self)882   void Run(Thread* self) override {
883     // We are going to load class and run verification, which may also need to load
884     // classes. If the thread cannot load classes (typically when the runtime is
885     // debuggable), then just return.
886     if (!self->CanLoadClasses()) {
887       return;
888     }
889     Runtime* runtime = Runtime::Current();
890     ClassLinker* linker = runtime->GetClassLinker();
891     const std::vector<const DexFile*>& boot_class_path =
892         runtime->GetClassLinker()->GetBootClassPath();
893     ScopedObjectAccess soa(self);
894     StackHandleScope<1> hs(self);
895     MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
896     uint64_t start_ns = ThreadCpuNanoTime();
897     uint64_t number_of_classes = 0;
898     for (const DexFile* dex_file : boot_class_path) {
899       if (dex_file->GetOatDexFile() != nullptr &&
900           dex_file->GetOatDexFile()->GetOatFile() != nullptr) {
901         // If backed by an .oat file, we have already run verification at
902         // compile-time. Note that some classes may still have failed
903         // verification there if they reference updatable mainline module
904         // classes.
905         continue;
906       }
907       for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
908         const dex::ClassDef& class_def = dex_file->GetClassDef(i);
909         const char* descriptor = dex_file->GetClassDescriptor(class_def);
910         ScopedNullHandle<mirror::ClassLoader> null_loader;
911         klass.Assign(linker->FindClass(self, descriptor, null_loader));
912         if (klass == nullptr) {
913           self->ClearException();
914           LOG(WARNING) << "Could not find " << descriptor;
915           continue;
916         }
917         ++number_of_classes;
918         if (linker->VerifyClass(self, klass) == verifier::FailureKind::kHardFailure) {
919           DCHECK(self->IsExceptionPending());
920           LOG(FATAL) << "Methods in the boot classpath failed to verify: "
921                      << self->GetException()->Dump();
922         }
923         CHECK(!self->IsExceptionPending());
924       }
925     }
926     LOG(INFO) << "Verified "
927               << number_of_classes
928               << " classes from mainline modules in "
929               << PrettyDuration(ThreadCpuNanoTime() - start_ns);
930   }
931 };
932 
933 class ZygoteTask final : public Task {
934  public:
ZygoteTask()935   ZygoteTask() {}
936 
Run(Thread * self)937   void Run(Thread* self) override {
938     Runtime* runtime = Runtime::Current();
939     uint32_t added_to_queue = 0;
940     for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
941       const std::string& profile_file = space->GetProfileFile();
942       if (profile_file.empty()) {
943         continue;
944       }
945       LOG(INFO) << "JIT Zygote looking at profile " << profile_file;
946 
947       const std::vector<const DexFile*>& boot_class_path =
948           runtime->GetClassLinker()->GetBootClassPath();
949       ScopedNullHandle<mirror::ClassLoader> null_handle;
950       // We add to the queue for zygote so that we can fork processes in-between
951       // compilations.
952       if (Runtime::Current()->IsPrimaryZygote()) {
953         std::string boot_profile = GetBootProfileFile(profile_file);
954         // We avoid doing compilation at boot for the secondary zygote, as apps
955         // forked from it are not critical for boot.
956         added_to_queue += runtime->GetJit()->CompileMethodsFromBootProfile(
957             self, boot_class_path, boot_profile, null_handle, /* add_to_queue= */ true);
958       }
959       added_to_queue += runtime->GetJit()->CompileMethodsFromProfile(
960           self, boot_class_path, profile_file, null_handle, /* add_to_queue= */ true);
961     }
962 
963     JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
964     code_cache->GetZygoteMap()->Initialize(added_to_queue);
965   }
966 
Finalize()967   void Finalize() override {
968     delete this;
969   }
970 
971  private:
972   DISALLOW_COPY_AND_ASSIGN(ZygoteTask);
973 };
974 
975 class JitProfileTask final : public Task {
976  public:
JitProfileTask(const std::vector<std::unique_ptr<const DexFile>> & dex_files,jobject class_loader)977   JitProfileTask(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
978                  jobject class_loader) {
979     ScopedObjectAccess soa(Thread::Current());
980     StackHandleScope<1> hs(soa.Self());
981     Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
982         soa.Decode<mirror::ClassLoader>(class_loader)));
983     ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
984     for (const auto& dex_file : dex_files) {
985       dex_files_.push_back(dex_file.get());
986       // Register the dex file so that we can guarantee it doesn't get deleted
987       // while reading it during the task.
988       class_linker->RegisterDexFile(*dex_file.get(), h_loader.Get());
989     }
990     // We also create our own global ref to use this class loader later.
991     class_loader_ = soa.Vm()->AddGlobalRef(soa.Self(), h_loader.Get());
992   }
993 
Run(Thread * self)994   void Run(Thread* self) override {
995     ScopedObjectAccess soa(self);
996     StackHandleScope<1> hs(self);
997     Handle<mirror::ClassLoader> loader = hs.NewHandle<mirror::ClassLoader>(
998         soa.Decode<mirror::ClassLoader>(class_loader_));
999 
1000     std::string profile = GetProfileFile(dex_files_[0]->GetLocation());
1001     std::string boot_profile = GetBootProfileFile(profile);
1002 
1003     Jit* jit = Runtime::Current()->GetJit();
1004 
1005     jit->CompileMethodsFromBootProfile(
1006         self,
1007         dex_files_,
1008         boot_profile,
1009         loader,
1010         /* add_to_queue= */ false);
1011 
1012     jit->CompileMethodsFromProfile(
1013         self,
1014         dex_files_,
1015         profile,
1016         loader,
1017         /* add_to_queue= */ true);
1018   }
1019 
Finalize()1020   void Finalize() override {
1021     delete this;
1022   }
1023 
~JitProfileTask()1024   ~JitProfileTask() {
1025     ScopedObjectAccess soa(Thread::Current());
1026     soa.Vm()->DeleteGlobalRef(soa.Self(), class_loader_);
1027   }
1028 
1029  private:
1030   std::vector<const DexFile*> dex_files_;
1031   jobject class_loader_;
1032 
1033   DISALLOW_COPY_AND_ASSIGN(JitProfileTask);
1034 };
1035 
CopyIfDifferent(void * s1,const void * s2,size_t n)1036 static void CopyIfDifferent(void* s1, const void* s2, size_t n) {
1037   if (memcmp(s1, s2, n) != 0) {
1038     memcpy(s1, s2, n);
1039   }
1040 }
1041 
MapBootImageMethods()1042 void Jit::MapBootImageMethods() {
1043   if (Runtime::Current()->IsJavaDebuggable()) {
1044     LOG(INFO) << "Not mapping boot image methods due to process being debuggable";
1045     return;
1046   }
1047   CHECK_NE(fd_methods_.get(), -1);
1048   if (!code_cache_->GetZygoteMap()->CanMapBootImageMethods()) {
1049     LOG(WARNING) << "Not mapping boot image methods due to error from zygote";
1050     // We don't need the fd anymore.
1051     fd_methods_.reset();
1052     return;
1053   }
1054 
1055   std::string error_str;
1056   MemMap child_mapping_methods = MemMap::MapFile(
1057       fd_methods_size_,
1058       PROT_READ | PROT_WRITE,
1059       MAP_PRIVATE,
1060       fd_methods_,
1061       /* start= */ 0,
1062       /* low_4gb= */ false,
1063       "boot-image-methods",
1064       &error_str);
1065 
1066   // We don't need the fd anymore.
1067   fd_methods_.reset();
1068 
1069   if (!child_mapping_methods.IsValid()) {
1070     LOG(WARNING) << "Failed to create child mapping of boot image methods: " << error_str;
1071     return;
1072   }
1073   size_t offset = 0;
1074   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1075   for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1076     const ImageHeader& header = space->GetImageHeader();
1077     const ImageSection& section = header.GetMethodsSection();
1078     uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
1079     uint8_t* page_end =
1080         AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
1081     if (page_end <= page_start) {
1082       // Section doesn't contain one aligned entire page.
1083       continue;
1084     }
1085     uint64_t capacity = page_end - page_start;
1086     // Walk over methods in the boot image, and check for ones whose class is
1087     // not initialized in the process, but are in the zygote process. For
1088     // such methods, we need their entrypoints to be stubs that do the
1089     // initialization check.
1090     header.VisitPackedArtMethods([&](ArtMethod& method) NO_THREAD_SAFETY_ANALYSIS {
1091       // Methods in the boot image should never have their single
1092       // implementation flag set (and therefore never have a `data_` pointing
1093       // to an ArtMethod for single implementation).
1094       CHECK(method.IsIntrinsic() || !method.HasSingleImplementationFlag());
1095       if (method.IsRuntimeMethod()) {
1096         return;
1097       }
1098       if (method.GetDeclaringClassUnchecked()->IsVisiblyInitialized() ||
1099           !method.IsStatic() ||
1100           method.IsConstructor()) {
1101         // Method does not need any stub.
1102         return;
1103       }
1104 
1105       //  We are going to mremap the child mapping into the image:
1106       //
1107       //                            ImageSection       ChildMappingMethods
1108       //
1109       //         section start -->  -----------
1110       //                            |         |
1111       //                            |         |
1112       //            page_start -->  |         |   <-----   -----------
1113       //                            |         |            |         |
1114       //                            |         |            |         |
1115       //                            |         |            |         |
1116       //                            |         |            |         |
1117       //                            |         |            |         |
1118       //                            |         |            |         |
1119       //                            |         |            |         |
1120       //             page_end  -->  |         |   <-----   -----------
1121       //                            |         |
1122       //         section end   -->  -----------
1123 
1124 
1125       uint8_t* pointer = reinterpret_cast<uint8_t*>(&method);
1126       // Note: We could refactor this to only check if the ArtMethod entrypoint is inside the
1127       // page region. This would remove the need for the edge case handling below.
1128       if (pointer >= page_start && pointer + sizeof(ArtMethod) < page_end) {
1129         // For all the methods in the mapping, put the entrypoint to the
1130         // resolution stub.
1131         ArtMethod* new_method = reinterpret_cast<ArtMethod*>(
1132             child_mapping_methods.Begin() + offset + (pointer - page_start));
1133         const void* code = new_method->GetEntryPointFromQuickCompiledCode();
1134         if (!class_linker->IsQuickGenericJniStub(code) &&
1135             !class_linker->IsQuickToInterpreterBridge(code) &&
1136             !class_linker->IsQuickResolutionStub(code)) {
1137           LOG(INFO) << "Putting back the resolution stub to an ArtMethod";
1138           new_method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
1139         }
1140       } else if (pointer < page_start && (pointer + sizeof(ArtMethod)) > page_start) {
1141         LOG(INFO) << "Copying parts of the contents of an ArtMethod spanning page_start";
1142         // If the method spans `page_start`, copy the contents of the child
1143         // into the pages we are going to remap into the image.
1144         //
1145         //         section start -->  -----------
1146         //                            |         |
1147         //                            |         |
1148         //            page_start -->  |/////////|            -----------
1149         //                            |/////////| -> copy -> |/////////|
1150         //                            |         |            |         |
1151         //
1152         CopyIfDifferent(child_mapping_methods.Begin() + offset,
1153                         page_start,
1154                         pointer + sizeof(ArtMethod) - page_start);
1155       } else if (pointer < page_end && (pointer + sizeof(ArtMethod)) > page_end) {
1156         LOG(INFO) << "Copying parts of the contents of an ArtMethod spanning page_end";
1157         // If the method spans `page_end`, copy the contents of the child
1158         // into the pages we are going to remap into the image.
1159         //
1160         //                            |         |            |         |
1161         //                            |/////////| -> copy -> |/////////|
1162         //             page_end  -->  |/////////|            -----------
1163         //                            |         |
1164         //         section end   -->  -----------
1165         //
1166         size_t bytes_to_copy = (page_end - pointer);
1167         CopyIfDifferent(child_mapping_methods.Begin() + offset + capacity - bytes_to_copy,
1168                         page_end - bytes_to_copy,
1169                         bytes_to_copy);
1170       }
1171     }, space->Begin(), kRuntimePointerSize);
1172 
1173     // Map the memory in the boot image range.
1174     if (mremap(child_mapping_methods.Begin() + offset,
1175                capacity,
1176                capacity,
1177                MREMAP_FIXED | MREMAP_MAYMOVE,
1178                page_start) == MAP_FAILED) {
1179       PLOG(WARNING) << "Fail to mremap boot image methods for " << space->GetImageFilename();
1180     }
1181     offset += capacity;
1182   }
1183 
1184   // The private mapping created for this process has been mremaped. We can
1185   // reset it.
1186   child_mapping_methods.Reset();
1187   LOG(INFO) << "Successfully mapped boot image methods";
1188 }
1189 
1190 // Return whether a boot image has a profile. This means we'll need to pre-JIT
1191 // methods in that profile for performance.
HasImageWithProfile()1192 static bool HasImageWithProfile() {
1193   for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1194     if (!space->GetProfileFile().empty()) {
1195       return true;
1196     }
1197   }
1198   return false;
1199 }
1200 
CreateThreadPool()1201 void Jit::CreateThreadPool() {
1202   // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
1203   // is not null when we instrument.
1204 
1205   // We need peers as we may report the JIT thread, e.g., in the debugger.
1206   constexpr bool kJitPoolNeedsPeers = true;
1207   thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
1208 
1209   thread_pool_->SetPthreadPriority(options_->GetThreadPoolPthreadPriority());
1210   Start();
1211 
1212   Runtime* runtime = Runtime::Current();
1213   if (runtime->IsZygote()) {
1214     // To speed up class lookups, generate a type lookup table for
1215     // dex files not backed by oat file.
1216     for (const DexFile* dex_file : runtime->GetClassLinker()->GetBootClassPath()) {
1217       if (dex_file->GetOatDexFile() == nullptr) {
1218         TypeLookupTable type_lookup_table = TypeLookupTable::Create(*dex_file);
1219         type_lookup_tables_.push_back(
1220             std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
1221         dex_file->SetOatDexFile(type_lookup_tables_.back().get());
1222       }
1223     }
1224 
1225     // Add a task that will verify boot classpath jars that were not
1226     // pre-compiled.
1227     thread_pool_->AddTask(Thread::Current(), new ZygoteVerificationTask());
1228   }
1229 
1230   if (runtime->IsZygote() && HasImageWithProfile() && UseJitCompilation()) {
1231     // If we have an image with a profile, request a JIT task to
1232     // compile all methods in that profile.
1233     thread_pool_->AddTask(Thread::Current(), new ZygoteTask());
1234 
1235     // And create mappings to share boot image methods memory from the zygote to
1236     // child processes.
1237 
1238     // Compute the total capacity required for the boot image methods.
1239     uint64_t total_capacity = 0;
1240     for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1241       const ImageHeader& header = space->GetImageHeader();
1242       const ImageSection& section = header.GetMethodsSection();
1243       // Mappings need to be at the page level.
1244       uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
1245       uint8_t* page_end =
1246           AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
1247       if (page_end > page_start) {
1248         total_capacity += (page_end - page_start);
1249       }
1250     }
1251 
1252     // Create the child and zygote mappings to the boot image methods.
1253     if (total_capacity > 0) {
1254       // Start with '/boot' and end with '.art' to match the pattern recognized
1255       // by android_os_Debug.cpp for boot images.
1256       const char* name = "/boot-image-methods.art";
1257       unique_fd mem_fd = unique_fd(art::memfd_create(name, /* flags= */ MFD_ALLOW_SEALING));
1258       if (mem_fd.get() == -1) {
1259         PLOG(WARNING) << "Could not create boot image methods file descriptor";
1260         return;
1261       }
1262       if (ftruncate(mem_fd.get(), total_capacity) != 0) {
1263         PLOG(WARNING) << "Failed to truncate boot image methods file to " << total_capacity;
1264         return;
1265       }
1266       std::string error_str;
1267 
1268       // Create the shared mapping eagerly, as this prevents other processes
1269       // from adding the writable seal.
1270       zygote_mapping_methods_ = MemMap::MapFile(
1271         total_capacity,
1272         PROT_READ | PROT_WRITE,
1273         MAP_SHARED,
1274         mem_fd,
1275         /* start= */ 0,
1276         /* low_4gb= */ false,
1277         "boot-image-methods",
1278         &error_str);
1279 
1280       if (!zygote_mapping_methods_.IsValid()) {
1281         LOG(WARNING) << "Failed to create zygote mapping of boot image methods:  " << error_str;
1282         return;
1283       }
1284       if (zygote_mapping_methods_.MadviseDontFork() != 0) {
1285         LOG(WARNING) << "Failed to madvise dont fork boot image methods";
1286         zygote_mapping_methods_ = MemMap();
1287         return;
1288       }
1289 
1290       // We should use the F_SEAL_FUTURE_WRITE flag, but this has unexpected
1291       // behavior on private mappings after fork (the mapping becomes shared between
1292       // parent and children), see b/143833776.
1293       // We will seal the write once we are done writing to the shared mapping.
1294       if (fcntl(mem_fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW) == -1) {
1295         PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
1296         zygote_mapping_methods_ = MemMap();
1297         return;
1298       }
1299       fd_methods_ = unique_fd(mem_fd.release());
1300       fd_methods_size_ = total_capacity;
1301     }
1302   }
1303 }
1304 
RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>> & dex_files,jobject class_loader)1305 void Jit::RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
1306                            jobject class_loader) {
1307   if (dex_files.empty()) {
1308     return;
1309   }
1310   Runtime* runtime = Runtime::Current();
1311   // If the runtime is debuggable, no need to precompile methods.
1312   if (runtime->IsSystemServer() &&
1313       UseJitCompilation() && HasImageWithProfile() &&
1314       !runtime->IsJavaDebuggable()) {
1315     thread_pool_->AddTask(Thread::Current(), new JitProfileTask(dex_files, class_loader));
1316   }
1317 }
1318 
CompileMethodFromProfile(Thread * self,ClassLinker * class_linker,uint32_t method_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,bool add_to_queue,bool compile_after_boot)1319 bool Jit::CompileMethodFromProfile(Thread* self,
1320                                    ClassLinker* class_linker,
1321                                    uint32_t method_idx,
1322                                    Handle<mirror::DexCache> dex_cache,
1323                                    Handle<mirror::ClassLoader> class_loader,
1324                                    bool add_to_queue,
1325                                    bool compile_after_boot) {
1326   ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
1327       method_idx, dex_cache, class_loader);
1328   if (method == nullptr) {
1329     self->ClearException();
1330     return false;
1331   }
1332   if (!method->IsCompilable() || !method->IsInvokable()) {
1333     return false;
1334   }
1335   if (method->IsPreCompiled()) {
1336     // Already seen by another profile.
1337     return false;
1338   }
1339   const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1340   if (class_linker->IsQuickToInterpreterBridge(entry_point) ||
1341       class_linker->IsQuickGenericJniStub(entry_point) ||
1342       // We explicitly check for the stub. The trampoline is for methods backed by
1343       // a .oat file that has a compiled version of the method.
1344       (entry_point == GetQuickResolutionStub())) {
1345     method->SetPreCompiled();
1346     if (!add_to_queue) {
1347       CompileMethod(method, self, CompilationKind::kOptimized, /* prejit= */ true);
1348     } else {
1349       Task* task = new JitCompileTask(
1350           method, JitCompileTask::TaskKind::kPreCompile, CompilationKind::kOptimized);
1351       if (compile_after_boot) {
1352         MutexLock mu(Thread::Current(), boot_completed_lock_);
1353         if (!boot_completed_) {
1354           tasks_after_boot_.push_back(task);
1355           return true;
1356         }
1357         DCHECK(tasks_after_boot_.empty());
1358       }
1359       thread_pool_->AddTask(self, task);
1360       return true;
1361     }
1362   }
1363   return false;
1364 }
1365 
CompileMethodsFromBootProfile(Thread * self,const std::vector<const DexFile * > & dex_files,const std::string & profile_file,Handle<mirror::ClassLoader> class_loader,bool add_to_queue)1366 uint32_t Jit::CompileMethodsFromBootProfile(
1367     Thread* self,
1368     const std::vector<const DexFile*>& dex_files,
1369     const std::string& profile_file,
1370     Handle<mirror::ClassLoader> class_loader,
1371     bool add_to_queue) {
1372   unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
1373 
1374   if (profile.Fd() == -1) {
1375     PLOG(WARNING) << "No boot profile: " << profile_file;
1376     return 0u;
1377   }
1378 
1379   ProfileBootInfo profile_info;
1380   if (!profile_info.Load(profile.Fd(), dex_files)) {
1381     LOG(ERROR) << "Could not load profile file: " << profile_file;
1382     return 0u;
1383   }
1384 
1385   ScopedObjectAccess soa(self);
1386   VariableSizedHandleScope handles(self);
1387   std::vector<Handle<mirror::DexCache>> dex_caches;
1388   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1389   for (const DexFile* dex_file : profile_info.GetDexFiles()) {
1390     dex_caches.push_back(handles.NewHandle(class_linker->FindDexCache(self, *dex_file)));
1391   }
1392 
1393   uint32_t added_to_queue = 0;
1394   for (const std::pair<uint32_t, uint32_t>& pair : profile_info.GetMethods()) {
1395     if (CompileMethodFromProfile(self,
1396                                  class_linker,
1397                                  pair.second,
1398                                  dex_caches[pair.first],
1399                                  class_loader,
1400                                  add_to_queue,
1401                                  /*compile_after_boot=*/false)) {
1402       ++added_to_queue;
1403     }
1404   }
1405   return added_to_queue;
1406 }
1407 
CompileMethodsFromProfile(Thread * self,const std::vector<const DexFile * > & dex_files,const std::string & profile_file,Handle<mirror::ClassLoader> class_loader,bool add_to_queue)1408 uint32_t Jit::CompileMethodsFromProfile(
1409     Thread* self,
1410     const std::vector<const DexFile*>& dex_files,
1411     const std::string& profile_file,
1412     Handle<mirror::ClassLoader> class_loader,
1413     bool add_to_queue) {
1414 
1415   if (profile_file.empty()) {
1416     LOG(WARNING) << "Expected a profile file in JIT zygote mode";
1417     return 0u;
1418   }
1419 
1420   // We don't generate boot profiles on device, therefore we don't
1421   // need to lock the file.
1422   unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
1423 
1424   if (profile.Fd() == -1) {
1425     PLOG(WARNING) << "No profile: " << profile_file;
1426     return 0u;
1427   }
1428 
1429   ProfileCompilationInfo profile_info;
1430   if (!profile_info.Load(profile.Fd())) {
1431     LOG(ERROR) << "Could not load profile file";
1432     return 0u;
1433   }
1434   ScopedObjectAccess soa(self);
1435   StackHandleScope<1> hs(self);
1436   MutableHandle<mirror::DexCache> dex_cache = hs.NewHandle<mirror::DexCache>(nullptr);
1437   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1438   uint32_t added_to_queue = 0u;
1439   for (const DexFile* dex_file : dex_files) {
1440     if (LocationIsOnArtModule(dex_file->GetLocation().c_str())) {
1441       // The ART module jars are already preopted.
1442       continue;
1443     }
1444 
1445     std::set<dex::TypeIndex> class_types;
1446     std::set<uint16_t> all_methods;
1447     if (!profile_info.GetClassesAndMethods(*dex_file,
1448                                            &class_types,
1449                                            &all_methods,
1450                                            &all_methods,
1451                                            &all_methods)) {
1452       // This means the profile file did not reference the dex file, which is the case
1453       // if there's no classes and methods of that dex file in the profile.
1454       continue;
1455     }
1456     dex_cache.Assign(class_linker->FindDexCache(self, *dex_file));
1457     CHECK(dex_cache != nullptr) << "Could not find dex cache for " << dex_file->GetLocation();
1458 
1459     for (uint16_t method_idx : all_methods) {
1460       if (CompileMethodFromProfile(self,
1461                                    class_linker,
1462                                    method_idx,
1463                                    dex_cache,
1464                                    class_loader,
1465                                    add_to_queue,
1466                                    /*compile_after_boot=*/true)) {
1467         ++added_to_queue;
1468       }
1469     }
1470   }
1471 
1472   // Add a task to run when all compilation is done.
1473   JitDoneCompilingProfileTask* task = new JitDoneCompilingProfileTask(dex_files);
1474   MutexLock mu(Thread::Current(), boot_completed_lock_);
1475   if (!boot_completed_) {
1476     tasks_after_boot_.push_back(task);
1477   } else {
1478     DCHECK(tasks_after_boot_.empty());
1479     thread_pool_->AddTask(self, task);
1480   }
1481   return added_to_queue;
1482 }
1483 
IgnoreSamplesForMethod(ArtMethod * method)1484 bool Jit::IgnoreSamplesForMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1485   if (method->IsClassInitializer() || !method->IsCompilable() || method->IsPreCompiled()) {
1486     // We do not want to compile such methods.
1487     return true;
1488   }
1489   if (method->IsNative()) {
1490     ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1491     if (klass == GetClassRoot<mirror::MethodHandle>() ||
1492         klass == GetClassRoot<mirror::VarHandle>()) {
1493       // MethodHandle and VarHandle invocation methods are required to throw an
1494       // UnsupportedOperationException if invoked reflectively. We achieve this by having native
1495       // implementations that raise the exception. We need to disable JIT compilation of these JNI
1496       // methods as it can lead to transitioning between JIT compiled JNI stubs and generic JNI
1497       // stubs. Since these stubs have different stack representations we can then crash in stack
1498       // walking (b/78151261).
1499       return true;
1500     }
1501   }
1502   return false;
1503 }
1504 
MaybeCompileMethod(Thread * self,ArtMethod * method,uint32_t old_count,uint32_t new_count,bool with_backedges)1505 bool Jit::MaybeCompileMethod(Thread* self,
1506                              ArtMethod* method,
1507                              uint32_t old_count,
1508                              uint32_t new_count,
1509                              bool with_backedges) {
1510   if (thread_pool_ == nullptr) {
1511     return false;
1512   }
1513   if (UNLIKELY(method->IsPreCompiled()) && !with_backedges /* don't check for OSR */) {
1514     if (!NeedsClinitCheckBeforeCall(method) ||
1515         method->GetDeclaringClass()->IsVisiblyInitialized()) {
1516       const void* entry_point = code_cache_->GetSavedEntryPointOfPreCompiledMethod(method);
1517       if (entry_point != nullptr) {
1518         Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(method, entry_point);
1519         return true;
1520       }
1521     }
1522   }
1523 
1524   if (IgnoreSamplesForMethod(method)) {
1525     return false;
1526   }
1527   if (HotMethodThreshold() == 0) {
1528     // Tests might request JIT on first use (compiled synchronously in the interpreter).
1529     return false;
1530   }
1531   DCHECK_GT(WarmMethodThreshold(), 0);
1532   DCHECK_GT(HotMethodThreshold(), WarmMethodThreshold());
1533   DCHECK_GT(OSRMethodThreshold(), HotMethodThreshold());
1534   DCHECK_GE(PriorityThreadWeight(), 1);
1535   DCHECK_LE(PriorityThreadWeight(), HotMethodThreshold());
1536 
1537   if (old_count < WarmMethodThreshold() && new_count >= WarmMethodThreshold()) {
1538     // Note: Native method have no "warm" state or profiling info.
1539     if (!method->IsNative() &&
1540         (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) &&
1541         code_cache_->CanAllocateProfilingInfo() &&
1542         !options_->UseTieredJitCompilation()) {
1543       bool success = ProfilingInfo::Create(self, method, /* retry_allocation= */ false);
1544       if (success) {
1545         VLOG(jit) << "Start profiling " << method->PrettyMethod();
1546       }
1547 
1548       if (thread_pool_ == nullptr) {
1549         // Calling ProfilingInfo::Create might put us in a suspended state, which could
1550         // lead to the thread pool being deleted when we are shutting down.
1551         return false;
1552       }
1553 
1554       if (!success) {
1555         // We failed allocating. Instead of doing the collection on the Java thread, we push
1556         // an allocation to a compiler thread, that will do the collection.
1557         thread_pool_->AddTask(
1558             self,
1559             new JitCompileTask(method,
1560                                JitCompileTask::TaskKind::kAllocateProfile,
1561                                CompilationKind::kOptimized));  // Arbitrary compilation kind.
1562       }
1563     }
1564   }
1565   if (UseJitCompilation()) {
1566     if (old_count < HotMethodThreshold() && new_count >= HotMethodThreshold()) {
1567       if (!code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
1568         DCHECK(thread_pool_ != nullptr);
1569         CompilationKind compilation_kind =
1570             (options_->UseTieredJitCompilation() || options_->UseBaselineCompiler())
1571                 ? CompilationKind::kBaseline
1572                 : CompilationKind::kOptimized;
1573         thread_pool_->AddTask(
1574             self,
1575             new JitCompileTask(method, JitCompileTask::TaskKind::kCompile, compilation_kind));
1576       }
1577     }
1578     if (old_count < OSRMethodThreshold() && new_count >= OSRMethodThreshold()) {
1579       if (!with_backedges) {
1580         return false;
1581       }
1582       DCHECK(!method->IsNative());  // No back edges reported for native methods.
1583       if (!code_cache_->IsOsrCompiled(method)) {
1584         DCHECK(thread_pool_ != nullptr);
1585         thread_pool_->AddTask(
1586             self,
1587             new JitCompileTask(method, JitCompileTask::TaskKind::kCompile, CompilationKind::kOsr));
1588       }
1589     }
1590   }
1591   return true;
1592 }
1593 
EnqueueOptimizedCompilation(ArtMethod * method,Thread * self)1594 void Jit::EnqueueOptimizedCompilation(ArtMethod* method, Thread* self) {
1595   if (thread_pool_ == nullptr) {
1596     return;
1597   }
1598   // We arrive here after a baseline compiled code has reached its baseline
1599   // hotness threshold. If tiered compilation is enabled, enqueue a compilation
1600   // task that will compile optimize the method.
1601   if (options_->UseTieredJitCompilation()) {
1602     thread_pool_->AddTask(
1603         self,
1604         new JitCompileTask(method,
1605                            JitCompileTask::TaskKind::kCompile,
1606                            CompilationKind::kOptimized));
1607   }
1608 }
1609 
1610 class ScopedSetRuntimeThread {
1611  public:
ScopedSetRuntimeThread(Thread * self)1612   explicit ScopedSetRuntimeThread(Thread* self)
1613       : self_(self), was_runtime_thread_(self_->IsRuntimeThread()) {
1614     self_->SetIsRuntimeThread(true);
1615   }
1616 
~ScopedSetRuntimeThread()1617   ~ScopedSetRuntimeThread() {
1618     self_->SetIsRuntimeThread(was_runtime_thread_);
1619   }
1620 
1621  private:
1622   Thread* self_;
1623   bool was_runtime_thread_;
1624 };
1625 
MethodEntered(Thread * thread,ArtMethod * method)1626 void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
1627   Runtime* runtime = Runtime::Current();
1628   if (UNLIKELY(runtime->UseJitCompilation() && JitAtFirstUse())) {
1629     ArtMethod* np_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
1630     if (np_method->IsCompilable()) {
1631       if (!np_method->IsNative() && GetCodeCache()->CanAllocateProfilingInfo()) {
1632         // The compiler requires a ProfilingInfo object for non-native methods.
1633         ProfilingInfo::Create(thread, np_method, /* retry_allocation= */ true);
1634       }
1635       // TODO(ngeoffray): For JIT at first use, use kPreCompile. Currently we don't due to
1636       // conflicts with jitzygote optimizations.
1637       JitCompileTask compile_task(
1638           method, JitCompileTask::TaskKind::kCompile, CompilationKind::kOptimized);
1639       // Fake being in a runtime thread so that class-load behavior will be the same as normal jit.
1640       ScopedSetRuntimeThread ssrt(thread);
1641       compile_task.Run(thread);
1642     }
1643     return;
1644   }
1645 
1646   ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
1647   // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
1648   // instead of interpreting the method. We don't update it for instrumentation as the entrypoint
1649   // must remain the instrumentation entrypoint.
1650   if ((profiling_info != nullptr) &&
1651       (profiling_info->GetSavedEntryPoint() != nullptr) &&
1652       (method->GetEntryPointFromQuickCompiledCode() != GetQuickInstrumentationEntryPoint())) {
1653     Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1654         method, profiling_info->GetSavedEntryPoint());
1655   } else {
1656     AddSamples(thread, method, 1, /* with_backedges= */false);
1657   }
1658 }
1659 
InvokeVirtualOrInterface(ObjPtr<mirror::Object> this_object,ArtMethod * caller,uint32_t dex_pc,ArtMethod * callee ATTRIBUTE_UNUSED)1660 void Jit::InvokeVirtualOrInterface(ObjPtr<mirror::Object> this_object,
1661                                    ArtMethod* caller,
1662                                    uint32_t dex_pc,
1663                                    ArtMethod* callee ATTRIBUTE_UNUSED) {
1664   ScopedAssertNoThreadSuspension ants(__FUNCTION__);
1665   DCHECK(this_object != nullptr);
1666   ProfilingInfo* info = caller->GetProfilingInfo(kRuntimePointerSize);
1667   if (info != nullptr) {
1668     info->AddInvokeInfo(dex_pc, this_object->GetClass());
1669   }
1670 }
1671 
WaitForCompilationToFinish(Thread * self)1672 void Jit::WaitForCompilationToFinish(Thread* self) {
1673   if (thread_pool_ != nullptr) {
1674     thread_pool_->Wait(self, false, false);
1675   }
1676 }
1677 
Stop()1678 void Jit::Stop() {
1679   Thread* self = Thread::Current();
1680   // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
1681   WaitForCompilationToFinish(self);
1682   GetThreadPool()->StopWorkers(self);
1683   WaitForCompilationToFinish(self);
1684 }
1685 
Start()1686 void Jit::Start() {
1687   GetThreadPool()->StartWorkers(Thread::Current());
1688 }
1689 
ScopedJitSuspend()1690 ScopedJitSuspend::ScopedJitSuspend() {
1691   jit::Jit* jit = Runtime::Current()->GetJit();
1692   was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
1693   if (was_on_) {
1694     jit->Stop();
1695   }
1696 }
1697 
~ScopedJitSuspend()1698 ScopedJitSuspend::~ScopedJitSuspend() {
1699   if (was_on_) {
1700     DCHECK(Runtime::Current()->GetJit() != nullptr);
1701     DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
1702     Runtime::Current()->GetJit()->Start();
1703   }
1704 }
1705 
RunPollingThread(void * arg)1706 static void* RunPollingThread(void* arg) {
1707   Jit* jit = reinterpret_cast<Jit*>(arg);
1708   do {
1709     sleep(10);
1710   } while (!jit->GetCodeCache()->GetZygoteMap()->IsCompilationNotified());
1711 
1712   // We will suspend other threads: we can only do that if we're attached to the
1713   // runtime.
1714   Runtime* runtime = Runtime::Current();
1715   bool thread_attached = runtime->AttachCurrentThread(
1716       "BootImagePollingThread",
1717       /* as_daemon= */ true,
1718       /* thread_group= */ nullptr,
1719       /* create_peer= */ false);
1720   CHECK(thread_attached);
1721 
1722   {
1723     // Prevent other threads from running while we are remapping the boot image
1724     // ArtMethod's. Native threads might still be running, but they cannot
1725     // change the contents of ArtMethod's.
1726     ScopedSuspendAll ssa(__FUNCTION__);
1727     runtime->GetJit()->MapBootImageMethods();
1728   }
1729 
1730   Runtime::Current()->DetachCurrentThread();
1731   return nullptr;
1732 }
1733 
PostForkChildAction(bool is_system_server,bool is_zygote)1734 void Jit::PostForkChildAction(bool is_system_server, bool is_zygote) {
1735   // Clear the potential boot tasks inherited from the zygote.
1736   {
1737     MutexLock mu(Thread::Current(), boot_completed_lock_);
1738     tasks_after_boot_.clear();
1739   }
1740 
1741   Runtime* const runtime = Runtime::Current();
1742   // Check if we'll need to remap the boot image methods.
1743   if (!is_zygote && fd_methods_ != -1) {
1744     // Create a thread that will poll the status of zygote compilation, and map
1745     // the private mapping of boot image methods.
1746     // For child zygote, we instead query IsCompilationNotified() post zygote fork.
1747     zygote_mapping_methods_.ResetInForkedProcess();
1748     pthread_t polling_thread;
1749     pthread_attr_t attr;
1750     CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
1751     CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED),
1752                        "PTHREAD_CREATE_DETACHED");
1753     CHECK_PTHREAD_CALL(
1754         pthread_create,
1755         (&polling_thread, &attr, RunPollingThread, reinterpret_cast<void*>(this)),
1756         "Methods maps thread");
1757   }
1758 
1759   if (is_zygote || runtime->IsSafeMode()) {
1760     // Delete the thread pool, we are not going to JIT.
1761     thread_pool_.reset(nullptr);
1762     return;
1763   }
1764   // At this point, the compiler options have been adjusted to the particular configuration
1765   // of the forked child. Parse them again.
1766   jit_compiler_->ParseCompilerOptions();
1767 
1768   // Adjust the status of code cache collection: the status from zygote was to not collect.
1769   code_cache_->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
1770       !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
1771 
1772   if (is_system_server && HasImageWithProfile()) {
1773     // Disable garbage collection: we don't want it to delete methods we're compiling
1774     // through boot and system server profiles.
1775     // TODO(ngeoffray): Fix this so we still collect deoptimized and unused code.
1776     code_cache_->SetGarbageCollectCode(false);
1777   }
1778 
1779   // We do this here instead of PostZygoteFork, as NativeDebugInfoPostFork only
1780   // applies to a child.
1781   NativeDebugInfoPostFork();
1782 }
1783 
PreZygoteFork()1784 void Jit::PreZygoteFork() {
1785   if (thread_pool_ == nullptr) {
1786     return;
1787   }
1788   thread_pool_->DeleteThreads();
1789 
1790   NativeDebugInfoPreFork();
1791 }
1792 
PostZygoteFork()1793 void Jit::PostZygoteFork() {
1794   if (thread_pool_ == nullptr) {
1795     // If this is a child zygote, check if we need to remap the boot image
1796     // methods.
1797     if (Runtime::Current()->IsZygote() &&
1798         fd_methods_ != -1 &&
1799         code_cache_->GetZygoteMap()->IsCompilationNotified()) {
1800       ScopedSuspendAll ssa(__FUNCTION__);
1801       MapBootImageMethods();
1802     }
1803     return;
1804   }
1805   if (Runtime::Current()->IsZygote() &&
1806       code_cache_->GetZygoteMap()->IsCompilationDoneButNotNotified()) {
1807     // Copy the boot image methods data to the mappings we created to share
1808     // with the children. We do this here as we are the only thread running and
1809     // we don't risk other threads concurrently updating the ArtMethod's.
1810     CHECK_EQ(GetTaskCount(), 1);
1811     NotifyZygoteCompilationDone();
1812     CHECK(code_cache_->GetZygoteMap()->IsCompilationNotified());
1813   }
1814   thread_pool_->CreateThreads();
1815 }
1816 
BootCompleted()1817 void Jit::BootCompleted() {
1818   Thread* self = Thread::Current();
1819   std::deque<Task*> tasks;
1820   {
1821     MutexLock mu(self, boot_completed_lock_);
1822     tasks = std::move(tasks_after_boot_);
1823     boot_completed_ = true;
1824   }
1825   for (Task* task : tasks) {
1826     thread_pool_->AddTask(self, task);
1827   }
1828 }
1829 
CanEncodeMethod(ArtMethod * method,bool is_for_shared_region) const1830 bool Jit::CanEncodeMethod(ArtMethod* method, bool is_for_shared_region) const {
1831   return !is_for_shared_region ||
1832       Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(method->GetDeclaringClass());
1833 }
1834 
CanEncodeClass(ObjPtr<mirror::Class> cls,bool is_for_shared_region) const1835 bool Jit::CanEncodeClass(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
1836   return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(cls);
1837 }
1838 
CanEncodeString(ObjPtr<mirror::String> string,bool is_for_shared_region) const1839 bool Jit::CanEncodeString(ObjPtr<mirror::String> string, bool is_for_shared_region) const {
1840   return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string);
1841 }
1842 
CanAssumeInitialized(ObjPtr<mirror::Class> cls,bool is_for_shared_region) const1843 bool Jit::CanAssumeInitialized(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
1844   if (!is_for_shared_region) {
1845     return cls->IsInitialized();
1846   } else {
1847     // Look up the class status in the oat file.
1848     const DexFile& dex_file = *cls->GetDexCache()->GetDexFile();
1849     const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1850     // In case we run without an image there won't be a backing oat file.
1851     if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
1852       return false;
1853     }
1854     uint16_t class_def_index = cls->GetDexClassDefIndex();
1855     return oat_dex_file->GetOatClass(class_def_index).GetStatus() >= ClassStatus::kInitialized;
1856   }
1857 }
1858 
EnqueueCompilationFromNterp(ArtMethod * method,Thread * self)1859 void Jit::EnqueueCompilationFromNterp(ArtMethod* method, Thread* self) {
1860   if (thread_pool_ == nullptr) {
1861     return;
1862   }
1863   if (GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
1864     // If we already have compiled code for it, nterp may be stuck in a loop.
1865     // Compile OSR.
1866     thread_pool_->AddTask(
1867         self,
1868         new JitCompileTask(method, JitCompileTask::TaskKind::kCompile, CompilationKind::kOsr));
1869     return;
1870   }
1871   if (GetCodeCache()->CanAllocateProfilingInfo()) {
1872     ProfilingInfo::Create(self, method, /* retry_allocation= */ false);
1873     thread_pool_->AddTask(
1874         self,
1875         new JitCompileTask(method, JitCompileTask::TaskKind::kCompile, CompilationKind::kBaseline));
1876   } else {
1877     thread_pool_->AddTask(
1878         self,
1879         new JitCompileTask(method,
1880                            JitCompileTask::TaskKind::kCompile,
1881                            CompilationKind::kOptimized));
1882   }
1883 }
1884 
1885 }  // namespace jit
1886 }  // namespace art
1887