blob: b596ea7ea2b5f191b46aeeb3dd17b6682eff4506 [file] [log] [blame]
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001/*
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
Mathieu Chartiere401d142015-04-22 13:56:20 -070021#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070022#include "base/enums.h"
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +000023#include "base/file_utils.h"
Andreas Gampe57943812017-12-06 21:39:13 -080024#include "base/logging.h" // For VLOG.
Andreas Gampe0897e1c2017-05-16 08:36:56 -070025#include "base/memory_tool.h"
Andreas Gampedcc528d2017-12-07 13:37:10 -080026#include "base/runtime_debug.h"
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +000027#include "base/scoped_flock.h"
David Sehrc431b9d2018-03-02 12:01:51 -080028#include "base/utils.h"
Vladimir Markoc7aa87e2018-05-24 15:19:52 +010029#include "class_root.h"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070030#include "debugger.h"
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +010031#include "dex/type_lookup_table.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080032#include "entrypoints/runtime_asm_entrypoints.h"
33#include "interpreter/interpreter.h"
David Srbeckye3fc2d12018-11-30 13:41:14 +000034#include "jit-inl.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080035#include "jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010036#include "jni/java_vm_ext.h"
Orion Hodson52f5a1f2018-05-02 11:05:44 +010037#include "mirror/method_handle_impl.h"
38#include "mirror/var_handle.h"
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +010039#include "oat_file.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010040#include "oat_file_manager.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000041#include "oat_quick_method_header.h"
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +010042#include "profile/profile_boot_info.h"
David Sehr82d046e2018-04-23 08:14:19 -070043#include "profile/profile_compilation_info.h"
Calin Juravle4d77b6a2015-12-01 18:38:09 +000044#include "profile_saver.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080045#include "runtime.h"
46#include "runtime_options.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070047#include "stack.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000048#include "stack_map.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070049#include "thread-inl.h"
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +010050#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080051
52namespace art {
53namespace jit {
54
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +000055static constexpr bool kEnableOnStackReplacement = true;
Nicolas Geoffraye8662132016-02-15 10:00:42 +000056
Andreas Gampe7897cec2017-07-19 16:28:59 -070057// Different compilation threshold constants. These can be overridden on the command line.
58static constexpr size_t kJitDefaultCompileThreshold = 10000; // Non-debug default.
59static constexpr size_t kJitStressDefaultCompileThreshold = 100; // Fast-debug build.
60static constexpr size_t kJitSlowStressDefaultCompileThreshold = 2; // Slow-debug build.
61
David Srbecky21821472019-07-29 15:10:31 +010062DEFINE_RUNTIME_DEBUG_FLAG(Jit, kSlowMode);
63
Mathieu Chartier72918ea2016-03-24 11:07:06 -070064// JIT compiler
Igor Murashkin2ffb7032017-11-08 13:35:21 -080065void* Jit::jit_library_handle_ = nullptr;
David Srbecky46b53532019-08-06 13:39:05 +010066JitCompilerInterface* Jit::jit_compiler_ = nullptr;
67JitCompilerInterface* (*Jit::jit_load_)(void) = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070068
David Srbeckye3fc2d12018-11-30 13:41:14 +000069uint32_t JitOptions::RoundUpThreshold(uint32_t threshold) {
David Srbecky21821472019-07-29 15:10:31 +010070 if (!Jit::kSlowMode) {
David Srbeckye3fc2d12018-11-30 13:41:14 +000071 threshold = RoundUp(threshold, kJitSamplesBatchSize);
72 }
73 CHECK_LE(threshold, std::numeric_limits<uint16_t>::max());
74 return threshold;
75}
76
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080077JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080078 auto* jit_options = new JitOptions;
Calin Juravleffc87072016-04-20 14:22:09 +010079 jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000080
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000081 jit_options->code_cache_initial_capacity_ =
82 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
83 jit_options->code_cache_max_capacity_ =
84 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -070085 jit_options->dump_info_on_shutdown_ =
86 options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
Calin Juravle138dbff2016-06-28 19:36:58 +010087 jit_options->profile_saver_options_ =
88 options.GetOrDefault(RuntimeArgumentMap::ProfileSaverOpts);
Nicolas Geoffray47b95802018-05-16 15:42:17 +010089 jit_options->thread_pool_pthread_priority_ =
90 options.GetOrDefault(RuntimeArgumentMap::JITPoolThreadPthreadPriority);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000091
Andreas Gampe7897cec2017-07-19 16:28:59 -070092 if (options.Exists(RuntimeArgumentMap::JITCompileThreshold)) {
93 jit_options->compile_threshold_ = *options.Get(RuntimeArgumentMap::JITCompileThreshold);
94 } else {
95 jit_options->compile_threshold_ =
96 kIsDebugBuild
David Srbecky21821472019-07-29 15:10:31 +010097 ? (Jit::kSlowMode
Andreas Gampe7897cec2017-07-19 16:28:59 -070098 ? kJitSlowStressDefaultCompileThreshold
99 : kJitStressDefaultCompileThreshold)
100 : kJitDefaultCompileThreshold;
101 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000102 jit_options->compile_threshold_ = RoundUpThreshold(jit_options->compile_threshold_);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000103
104 if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
105 jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000106 } else {
107 jit_options->warmup_threshold_ = jit_options->compile_threshold_ / 2;
108 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000109 jit_options->warmup_threshold_ = RoundUpThreshold(jit_options->warmup_threshold_);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000110
111 if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
112 jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000113 } else {
114 jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
115 if (jit_options->osr_threshold_ > std::numeric_limits<uint16_t>::max()) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000116 jit_options->osr_threshold_ =
117 RoundDown(std::numeric_limits<uint16_t>::max(), kJitSamplesBatchSize);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000118 }
119 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000120 jit_options->osr_threshold_ = RoundUpThreshold(jit_options->osr_threshold_);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000121
Calin Juravleb2771b42016-04-07 17:09:25 +0100122 if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
123 jit_options->priority_thread_weight_ =
124 *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
125 if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
126 LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
127 } else if (jit_options->priority_thread_weight_ == 0) {
128 LOG(FATAL) << "Priority thread weight cannot be 0.";
129 }
130 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100131 jit_options->priority_thread_weight_ = std::max(
132 jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
133 static_cast<size_t>(1));
Calin Juravleb2771b42016-04-07 17:09:25 +0100134 }
135
Calin Juravle155ff3d2016-04-27 14:14:58 +0100136 if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100137 jit_options->invoke_transition_weight_ =
138 *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
Calin Juravle155ff3d2016-04-27 14:14:58 +0100139 if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
140 LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
141 } else if (jit_options->invoke_transition_weight_ == 0) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100142 LOG(FATAL) << "Invoke transition weight cannot be 0.";
Calin Juravle155ff3d2016-04-27 14:14:58 +0100143 }
Calin Juravle155ff3d2016-04-27 14:14:58 +0100144 } else {
145 jit_options->invoke_transition_weight_ = std::max(
146 jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
Mathieu Chartier6beced42016-11-15 15:51:31 -0800147 static_cast<size_t>(1));
Calin Juravle155ff3d2016-04-27 14:14:58 +0100148 }
149
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800150 return jit_options;
151}
152
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700153void Jit::DumpInfo(std::ostream& os) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000154 code_cache_->Dump(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700155 cumulative_timings_.Dump(os);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000156 MutexLock mu(Thread::Current(), lock_);
157 memory_use_.PrintMemoryUse(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700158}
159
Calin Juravleb8e69992016-03-09 15:37:48 +0000160void Jit::DumpForSigQuit(std::ostream& os) {
161 DumpInfo(os);
162 ProfileSaver::DumpInstanceInfo(os);
163}
164
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700165void Jit::AddTimingLogger(const TimingLogger& logger) {
166 cumulative_timings_.AddLogger(logger);
167}
168
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100169Jit::Jit(JitCodeCache* code_cache, JitOptions* options)
170 : code_cache_(code_cache),
171 options_(options),
David Srbeckybfcea3d2019-08-05 15:44:00 +0100172 boot_completed_lock_("Jit::boot_completed_lock_"),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100173 cumulative_timings_("JIT timings"),
174 memory_use_("Memory used for compilation", 16),
175 lock_("JIT memory use lock") {}
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800176
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100177Jit* Jit::Create(JitCodeCache* code_cache, JitOptions* options) {
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000178 if (jit_load_ == nullptr) {
179 LOG(WARNING) << "Not creating JIT: library not loaded";
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800180 return nullptr;
181 }
David Srbecky46b53532019-08-06 13:39:05 +0100182 jit_compiler_ = (jit_load_)();
183 if (jit_compiler_ == nullptr) {
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000184 LOG(WARNING) << "Not creating JIT: failed to allocate a compiler";
185 return nullptr;
186 }
187 std::unique_ptr<Jit> jit(new Jit(code_cache, options));
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000188
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000189 // If the code collector is enabled, check if that still holds:
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000190 // With 'perf', we want a 1-1 mapping between an address and a method.
191 // We aren't able to keep method pointers live during the instrumentation method entry trampoline
192 // so we will just disable jit-gc if we are doing that.
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000193 if (code_cache->GetGarbageCollectCode()) {
David Srbecky46b53532019-08-06 13:39:05 +0100194 code_cache->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000195 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
196 }
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100197
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000198 VLOG(jit) << "JIT created with initial_capacity="
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000199 << PrettySize(options->GetCodeCacheInitialCapacity())
200 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000201 << ", compile_threshold=" << options->GetCompileThreshold()
Calin Juravle138dbff2016-06-28 19:36:58 +0100202 << ", profile_saver_options=" << options->GetProfileSaverOptions();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100203
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100204 // Notify native debugger about the classes already loaded before the creation of the jit.
205 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800206 return jit.release();
207}
208
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000209template <typename T>
210bool Jit::LoadSymbol(T* address, const char* name, std::string* error_msg) {
211 *address = reinterpret_cast<T>(dlsym(jit_library_handle_, name));
212 if (*address == nullptr) {
213 *error_msg = std::string("JIT couldn't find ") + name + std::string(" entry point");
214 return false;
215 }
216 return true;
217}
218
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000219bool Jit::LoadCompilerLibrary(std::string* error_msg) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800220 jit_library_handle_ = dlopen(
221 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
222 if (jit_library_handle_ == nullptr) {
223 std::ostringstream oss;
224 oss << "JIT could not load libart-compiler.so: " << dlerror();
225 *error_msg = oss.str();
226 return false;
227 }
David Srbecky46b53532019-08-06 13:39:05 +0100228 if (!LoadSymbol(&jit_load_, "jit_load", error_msg)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800229 dlclose(jit_library_handle_);
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000230 return false;
231 }
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700232 return true;
233}
234
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100235bool Jit::CompileMethod(ArtMethod* method, Thread* self, bool baseline, bool osr, bool prejit) {
Calin Juravleffc87072016-04-20 14:22:09 +0100236 DCHECK(Runtime::Current()->UseJitCompilation());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800237 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000238
Alex Light0fa17862017-10-24 13:43:05 -0700239 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100240 // Don't compile the method if it has breakpoints.
Alex Light0fa17862017-10-24 13:43:05 -0700241 if (cb->IsMethodBeingInspected(method) && !cb->IsMethodSafeToJit(method)) {
242 VLOG(jit) << "JIT not compiling " << method->PrettyMethod()
243 << " due to not being safe to jit according to runtime-callbacks. For example, there"
244 << " could be breakpoints in this method.";
Mathieu Chartierd8565452015-03-26 09:41:50 -0700245 return false;
246 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100247
248 // Don't compile the method if we are supposed to be deoptimized.
249 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
250 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
David Sehr709b0702016-10-13 09:12:37 -0700251 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to deoptimization";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100252 return false;
253 }
254
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000255 JitMemoryRegion* region = GetCodeCache()->GetCurrentRegion();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100256 if (osr && GetCodeCache()->IsSharedRegion(*region)) {
257 VLOG(jit) << "JIT not osr compiling "
258 << method->PrettyMethod()
259 << " due to using shared region";
260 return false;
261 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000262
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000263 // If we get a request to compile a proxy method, we pass the actual Java method
264 // of that proxy method, as the compiler does not expect a proxy method.
Andreas Gampe542451c2016-07-26 09:02:02 -0700265 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000266 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, osr, prejit, region)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100267 return false;
268 }
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100269
270 VLOG(jit) << "Compiling method "
David Sehr709b0702016-10-13 09:12:37 -0700271 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100272 << " osr=" << std::boolalpha << osr;
David Srbecky46b53532019-08-06 13:39:05 +0100273 bool success = jit_compiler_->CompileMethod(self, region, method_to_compile, baseline, osr);
buzbee454b3b62016-04-07 14:42:47 -0700274 code_cache_->DoneCompiling(method_to_compile, self, osr);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100275 if (!success) {
276 VLOG(jit) << "Failed to compile method "
David Sehr709b0702016-10-13 09:12:37 -0700277 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100278 << " osr=" << std::boolalpha << osr;
279 }
Andreas Gampe320ba912016-11-18 17:39:45 -0800280 if (kIsDebugBuild) {
281 if (self->IsExceptionPending()) {
282 mirror::Throwable* exception = self->GetException();
283 LOG(FATAL) << "No pending exception expected after compiling "
284 << ArtMethod::PrettyMethod(method)
285 << ": "
286 << exception->Dump();
287 }
288 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100289 return success;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800290}
291
Mathieu Chartier93c21ba2018-12-10 13:08:30 -0800292void Jit::WaitForWorkersToBeCreated() {
293 if (thread_pool_ != nullptr) {
294 thread_pool_->WaitForWorkersToBeCreated();
295 }
296}
297
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800298void Jit::DeleteThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100299 Thread* self = Thread::Current();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100300 if (thread_pool_ != nullptr) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700301 std::unique_ptr<ThreadPool> pool;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100302 {
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.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700306 pool = std::move(thread_pool_);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100307 }
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700308
309 // When running sanitized, let all tasks finish to not leak. Otherwise just clear the queue.
Roland Levillain05e34f42018-05-24 13:19:05 +0000310 if (!kRunningOnMemoryTool) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700311 pool->StopWorkers(self);
312 pool->RemoveAllTasks(self);
313 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100314 // We could just suspend all threads, but we know those threads
315 // will finish in a short period, so it's not worth adding a suspend logic
316 // here. Besides, this is only done for shutdown.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700317 pool->Wait(self, false, false);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800318 }
319}
320
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000321void Jit::StartProfileSaver(const std::string& filename,
Calin Juravle77651c42017-03-03 18:04:02 -0800322 const std::vector<std::string>& code_paths) {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100323 if (options_->GetSaveProfilingInfo()) {
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100324 ProfileSaver::Start(options_->GetProfileSaverOptions(), filename, code_cache_, code_paths);
Calin Juravle31f2c152015-10-23 17:56:15 +0100325 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000326}
327
328void Jit::StopProfileSaver() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100329 if (options_->GetSaveProfilingInfo() && ProfileSaver::IsStarted()) {
330 ProfileSaver::Stop(options_->DumpJitInfoOnShutdown());
Calin Juravle31f2c152015-10-23 17:56:15 +0100331 }
332}
333
Siva Chandra05d24152016-01-05 17:43:17 -0800334bool Jit::JitAtFirstUse() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100335 return HotMethodThreshold() == 0;
Siva Chandra05d24152016-01-05 17:43:17 -0800336}
337
Nicolas Geoffray35122442016-03-02 12:05:30 +0000338bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
339 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
340}
341
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800342Jit::~Jit() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100343 DCHECK(!options_->GetSaveProfilingInfo() || !ProfileSaver::IsStarted());
344 if (options_->DumpJitInfoOnShutdown()) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700345 DumpInfo(LOG_STREAM(INFO));
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100346 Runtime::Current()->DumpDeoptimizations(LOG_STREAM(INFO));
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700347 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800348 DeleteThreadPool();
David Srbecky46b53532019-08-06 13:39:05 +0100349 if (jit_compiler_ != nullptr) {
350 delete jit_compiler_;
351 jit_compiler_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800352 }
353 if (jit_library_handle_ != nullptr) {
354 dlclose(jit_library_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700355 jit_library_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800356 }
357}
358
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000359void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
Calin Juravleffc87072016-04-20 14:22:09 +0100360 if (!Runtime::Current()->UseJitCompilation()) {
361 // No need to notify if we only use the JIT to save profiles.
362 return;
363 }
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000364 jit::Jit* jit = Runtime::Current()->GetJit();
David Srbecky46b53532019-08-06 13:39:05 +0100365 if (jit->jit_compiler_->GenerateDebugInfo()) {
366 jit_compiler_->TypesLoaded(&type, 1);
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000367 }
368}
369
370void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
371 struct CollectClasses : public ClassVisitor {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100372 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700373 classes_.push_back(klass.Ptr());
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000374 return true;
375 }
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800376 std::vector<mirror::Class*> classes_;
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000377 };
378
David Srbecky46b53532019-08-06 13:39:05 +0100379 if (jit_compiler_->GenerateDebugInfo()) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000380 ScopedObjectAccess so(Thread::Current());
381
382 CollectClasses visitor;
383 linker->VisitClasses(&visitor);
David Srbecky46b53532019-08-06 13:39:05 +0100384 jit_compiler_->TypesLoaded(visitor.classes_.data(), visitor.classes_.size());
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000385 }
386}
387
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000388extern "C" void art_quick_osr_stub(void** stack,
Evgenii Stepanov6d90fde2018-09-04 17:50:38 -0700389 size_t stack_size_in_bytes,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000390 const uint8_t* native_pc,
391 JValue* result,
392 const char* shorty,
393 Thread* self);
394
395bool Jit::MaybeDoOnStackReplacement(Thread* thread,
396 ArtMethod* method,
397 uint32_t dex_pc,
398 int32_t dex_pc_offset,
399 JValue* result) {
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000400 if (!kEnableOnStackReplacement) {
401 return false;
402 }
403
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000404 Jit* jit = Runtime::Current()->GetJit();
405 if (jit == nullptr) {
406 return false;
407 }
408
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000409 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
410 // Don't attempt to do an OSR if we are close to the stack limit. Since
411 // the interpreter frames are still on stack, OSR has the potential
412 // to stack overflow even for a simple loop.
413 // b/27094810.
414 return false;
415 }
416
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000417 // Get the actual Java method if this method is from a proxy class. The compiler
418 // and the JIT code cache do not expect methods from proxy classes.
Andreas Gampe542451c2016-07-26 09:02:02 -0700419 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000420
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000421 // Cheap check if the method has been compiled already. That's an indicator that we should
422 // osr into it.
423 if (!jit->GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
424 return false;
425 }
426
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000427 // Fetch some data before looking up for an OSR method. We don't want thread
428 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
429 // method while we are being suspended.
David Sehr0225f8e2018-01-31 08:52:24 +0000430 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800431 const size_t number_of_vregs = accessor.RegistersSize();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000432 const char* shorty = method->GetShorty();
David Sehr709b0702016-10-13 09:12:37 -0700433 std::string method_name(VLOG_IS_ON(jit) ? method->PrettyMethod() : "");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000434 void** memory = nullptr;
435 size_t frame_size = 0;
436 ShadowFrame* shadow_frame = nullptr;
437 const uint8_t* native_pc = nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000438
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000439 {
Mathieu Chartier268764d2016-09-13 12:09:38 -0700440 ScopedAssertNoThreadSuspension sts("Holding OSR method");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000441 const OatQuickMethodHeader* osr_method = jit->GetCodeCache()->LookupOsrMethodHeader(method);
442 if (osr_method == nullptr) {
443 // No osr method yet, just return to the interpreter.
444 return false;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000445 }
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000446
David Srbecky052f8ca2018-04-26 15:42:54 +0100447 CodeInfo code_info(osr_method);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000448
449 // Find stack map starting at the target dex_pc.
David Srbecky052f8ca2018-04-26 15:42:54 +0100450 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc + dex_pc_offset);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000451 if (!stack_map.IsValid()) {
452 // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
453 // hope that the next branch has one.
454 return false;
455 }
456
Alex Light21611932017-09-26 13:07:39 -0700457 // Before allowing the jump, make sure no code is actively inspecting the method to avoid
458 // jumping from interpreter to OSR while e.g. single stepping. Note that we could selectively
459 // disable OSR when single stepping, but that's currently hard to know at this point.
460 if (Runtime::Current()->GetRuntimeCallbacks()->IsMethodBeingInspected(method)) {
Aart Bik29bdaee2016-05-18 15:44:07 -0700461 return false;
462 }
463
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000464 // We found a stack map, now fill the frame with dex register values from the interpreter's
465 // shadow frame.
David Srbeckyfd89b072018-06-03 12:00:22 +0100466 DexRegisterMap vreg_map = code_info.GetDexRegisterMapOf(stack_map);
Artem Serov2808be82018-12-20 19:15:11 +0000467 DCHECK_EQ(vreg_map.size(), number_of_vregs);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000468
469 frame_size = osr_method->GetFrameSizeInBytes();
470
471 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
472 // stack.
473 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
474 // but that is engineering complexity not worth the effort for something like OSR.
475 memory = reinterpret_cast<void**>(malloc(frame_size));
476 CHECK(memory != nullptr);
477 memset(memory, 0, frame_size);
478
479 // Art ABI: ArtMethod is at the bottom of the stack.
480 memory[0] = method;
481
482 shadow_frame = thread->PopShadowFrame();
David Srbeckyfd89b072018-06-03 12:00:22 +0100483 if (vreg_map.empty()) {
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000484 // If we don't have a dex register map, then there are no live dex registers at
485 // this dex pc.
486 } else {
487 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
David Srbeckye1402122018-06-13 18:20:45 +0100488 DexRegisterLocation::Kind location = vreg_map[vreg].GetKind();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000489 if (location == DexRegisterLocation::Kind::kNone) {
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000490 // Dex register is dead or uninitialized.
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000491 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
David Srbecky7dc11782016-02-25 13:23:56 +0000499 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000500
501 int32_t vreg_value = shadow_frame->GetVReg(vreg);
David Srbeckye1402122018-06-13 18:20:45 +0100502 int32_t slot_offset = vreg_map[vreg].GetStackOffsetInBytes();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000503 DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
504 DCHECK_GT(slot_offset, 0);
505 (reinterpret_cast<int32_t*>(memory))[slot_offset / sizeof(int32_t)] = vreg_value;
506 }
507 }
508
David Srbecky052f8ca2018-04-26 15:42:54 +0100509 native_pc = stack_map.GetNativePcOffset(kRuntimeISA) +
David Srbecky09ed0982016-02-12 21:58:43 +0000510 osr_method->GetEntryPoint();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000511 VLOG(jit) << "Jumping to "
512 << method_name
513 << "@"
514 << std::hex << reinterpret_cast<uintptr_t>(native_pc);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000515 }
516
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000517 {
518 ManagedStack fragment;
519 thread->PushManagedStackFragment(&fragment);
520 (*art_quick_osr_stub)(memory,
521 frame_size,
522 native_pc,
523 result,
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000524 shorty,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000525 thread);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000526
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000527 if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
528 thread->DeoptimizeWithDeoptimizationException(result);
529 }
530 thread->PopManagedStackFragment(fragment);
531 }
532 free(memory);
533 thread->PushShadowFrame(shadow_frame);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000534 VLOG(jit) << "Done running OSR code for " << method_name;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000535 return true;
536}
537
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000538void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
539 if (bytes > 4 * MB) {
540 LOG(INFO) << "Compiler allocated "
541 << PrettySize(bytes)
542 << " to compile "
David Sehr709b0702016-10-13 09:12:37 -0700543 << ArtMethod::PrettyMethod(method);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000544 }
545 MutexLock mu(Thread::Current(), lock_);
546 memory_use_.AddValue(bytes);
547}
548
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100549class JitCompileTask final : public Task {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100550 public:
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000551 enum class TaskKind {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100552 kAllocateProfile,
553 kCompile,
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000554 kCompileBaseline,
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000555 kCompileOsr,
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100556 kPreCompile,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100557 };
558
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000559 JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind), klass_(nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100560 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000561 // For a non-bootclasspath class, add a global ref to the class to prevent class unloading
562 // until compilation is done.
563 if (method->GetDeclaringClass()->GetClassLoader() != nullptr) {
564 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
565 CHECK(klass_ != nullptr);
566 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100567 }
568
569 ~JitCompileTask() {
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000570 if (klass_ != nullptr) {
571 ScopedObjectAccess soa(Thread::Current());
572 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
573 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100574 }
575
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100576 void Run(Thread* self) override {
Andreas Gampe4bd52342019-07-15 15:09:04 -0700577 {
578 ScopedObjectAccess soa(self);
579 switch (kind_) {
580 case TaskKind::kPreCompile:
581 case TaskKind::kCompile:
582 case TaskKind::kCompileBaseline:
583 case TaskKind::kCompileOsr: {
584 Runtime::Current()->GetJit()->CompileMethod(
585 method_,
586 self,
587 /* baseline= */ (kind_ == TaskKind::kCompileBaseline),
588 /* osr= */ (kind_ == TaskKind::kCompileOsr),
589 /* prejit= */ (kind_ == TaskKind::kPreCompile));
590 break;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000591 }
Andreas Gampe4bd52342019-07-15 15:09:04 -0700592 case TaskKind::kAllocateProfile: {
593 if (ProfilingInfo::Create(self, method_, /* retry_allocation= */ true)) {
594 VLOG(jit) << "Start profiling " << ArtMethod::PrettyMethod(method_);
595 }
596 break;
597 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100598 }
599 }
Calin Juravlea2638922016-04-29 16:44:11 +0100600 ProfileSaver::NotifyJitActivity();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100601 }
602
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100603 void Finalize() override {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100604 delete this;
605 }
606
607 private:
608 ArtMethod* const method_;
609 const TaskKind kind_;
610 jobject klass_;
611
612 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
613};
614
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100615static std::string GetProfileFile(const std::string& dex_location) {
616 // Hardcoded assumption where the profile file is.
617 // TODO(ngeoffray): this is brittle and we would need to change change if we
618 // wanted to do more eager JITting of methods in a profile. This is
619 // currently only for system server.
620 return dex_location + ".prof";
621}
622
623static std::string GetBootProfileFile(const std::string& profile) {
624 // The boot profile can be found next to the compilation profile, with a
625 // different extension.
626 return ReplaceFileExtension(profile, "bprof");
627}
628
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000629class ZygoteTask final : public Task {
630 public:
631 ZygoteTask() {}
632
633 void Run(Thread* self) override {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100634 Runtime* runtime = Runtime::Current();
635 std::string profile_file;
636 for (const std::string& option : runtime->GetImageCompilerOptions()) {
637 if (android::base::StartsWith(option, "--profile-file=")) {
638 profile_file = option.substr(strlen("--profile-file="));
639 break;
640 }
641 }
642
643 const std::vector<const DexFile*>& boot_class_path =
644 runtime->GetClassLinker()->GetBootClassPath();
645 ScopedNullHandle<mirror::ClassLoader> null_handle;
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100646 std::string boot_profile = GetBootProfileFile(profile_file);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100647 // We add to the queue for zygote so that we can fork processes in-between
648 // compilations.
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100649 uint32_t added_to_queue = runtime->GetJit()->CompileMethodsFromBootProfile(
650 self, boot_class_path, boot_profile, null_handle, /* add_to_queue= */ true);
651 added_to_queue += runtime->GetJit()->CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100652 self, boot_class_path, profile_file, null_handle, /* add_to_queue= */ true);
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100653
654 JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
655 code_cache->GetZygoteMap()->Initialize(added_to_queue);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100656 }
657
658 void Finalize() override {
659 delete this;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000660 }
661
662 private:
663 DISALLOW_COPY_AND_ASSIGN(ZygoteTask);
664};
665
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100666class JitProfileTask final : public Task {
667 public:
668 JitProfileTask(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100669 jobject class_loader) {
670 ScopedObjectAccess soa(Thread::Current());
671 StackHandleScope<1> hs(soa.Self());
672 Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
673 soa.Decode<mirror::ClassLoader>(class_loader)));
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100674 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
675 for (const auto& dex_file : dex_files) {
676 dex_files_.push_back(dex_file.get());
677 // Register the dex file so that we can guarantee it doesn't get deleted
678 // while reading it during the task.
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100679 class_linker->RegisterDexFile(*dex_file.get(), h_loader.Get());
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100680 }
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100681 // We also create our own global ref to use this class loader later.
682 class_loader_ = soa.Vm()->AddGlobalRef(soa.Self(), h_loader.Get());
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100683 }
684
685 void Run(Thread* self) override {
686 ScopedObjectAccess soa(self);
687 StackHandleScope<1> hs(self);
688 Handle<mirror::ClassLoader> loader = hs.NewHandle<mirror::ClassLoader>(
689 soa.Decode<mirror::ClassLoader>(class_loader_));
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100690
691 std::string profile = GetProfileFile(dex_files_[0]->GetLocation());
692 std::string boot_profile = GetBootProfileFile(profile);
693
694 Runtime::Current()->GetJit()->CompileMethodsFromBootProfile(
695 self,
696 dex_files_,
697 boot_profile,
698 loader,
699 /* add_to_queue= */ false);
700
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100701 Runtime::Current()->GetJit()->CompileMethodsFromProfile(
702 self,
703 dex_files_,
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100704 profile,
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100705 loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +0100706 /* add_to_queue= */ true);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100707 }
708
709 void Finalize() override {
710 delete this;
711 }
712
Nicolas Geoffrayf5a07ae2019-06-20 14:59:07 +0100713 ~JitProfileTask() {
714 ScopedObjectAccess soa(Thread::Current());
715 soa.Vm()->DeleteGlobalRef(soa.Self(), class_loader_);
716 }
717
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100718 private:
719 std::vector<const DexFile*> dex_files_;
720 jobject class_loader_;
721
722 DISALLOW_COPY_AND_ASSIGN(JitProfileTask);
723};
724
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000725void Jit::CreateThreadPool() {
726 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
727 // is not null when we instrument.
728
729 // We need peers as we may report the JIT thread, e.g., in the debugger.
730 constexpr bool kJitPoolNeedsPeers = true;
731 thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
732
733 thread_pool_->SetPthreadPriority(options_->GetThreadPoolPthreadPriority());
734 Start();
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000735
736 // If we're not using the default boot image location, request a JIT task to
737 // compile all methods in the boot image profile.
738 Runtime* runtime = Runtime::Current();
David Srbecky3db3d372019-04-17 18:19:17 +0100739 if (runtime->IsZygote() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000740 thread_pool_->AddTask(Thread::Current(), new ZygoteTask());
741 }
742}
743
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100744void Jit::RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100745 jobject class_loader) {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100746 if (dex_files.empty()) {
747 return;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000748 }
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100749 Runtime* runtime = Runtime::Current();
750 if (runtime->IsSystemServer() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
751 thread_pool_->AddTask(Thread::Current(), new JitProfileTask(dex_files, class_loader));
752 }
753}
754
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100755bool Jit::CompileMethodFromProfile(Thread* self,
756 ClassLinker* class_linker,
757 uint32_t method_idx,
758 Handle<mirror::DexCache> dex_cache,
759 Handle<mirror::ClassLoader> class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +0100760 bool add_to_queue,
761 bool compile_after_boot) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100762 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
763 method_idx, dex_cache, class_loader);
764 if (method == nullptr) {
765 self->ClearException();
766 return false;
767 }
768 if (!method->IsCompilable() || !method->IsInvokable()) {
769 return false;
770 }
771 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
772 if (class_linker->IsQuickToInterpreterBridge(entry_point) ||
773 class_linker->IsQuickGenericJniStub(entry_point) ||
774 class_linker->IsQuickResolutionStub(entry_point)) {
775 // Special case ZygoteServer class so that it gets compiled before the
776 // zygote enters it. This avoids needing to do OSR during app startup.
777 // TODO: have a profile instead.
778 method->SetPreCompiled();
779 if (!add_to_queue || method->GetDeclaringClass()->DescriptorEquals(
780 "Lcom/android/internal/os/ZygoteServer;")) {
781 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ true);
782 } else {
David Srbeckybfcea3d2019-08-05 15:44:00 +0100783 Task* task = new JitCompileTask(method, JitCompileTask::TaskKind::kPreCompile);
784 if (compile_after_boot) {
785 MutexLock mu(Thread::Current(), boot_completed_lock_);
786 if (!boot_completed_) {
787 tasks_after_boot_.push_back(task);
788 return true;
789 }
790 DCHECK(tasks_after_boot_.empty());
791 }
792 thread_pool_->AddTask(self, task);
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100793 return true;
794 }
795 }
796 return false;
797}
798
799uint32_t Jit::CompileMethodsFromBootProfile(
800 Thread* self,
801 const std::vector<const DexFile*>& dex_files,
802 const std::string& profile_file,
803 Handle<mirror::ClassLoader> class_loader,
804 bool add_to_queue) {
805 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
806
807 if (profile.Fd() == -1) {
808 PLOG(WARNING) << "No boot profile: " << profile_file;
809 return 0u;
810 }
811
812 ProfileBootInfo profile_info;
813 if (!profile_info.Load(profile.Fd(), dex_files)) {
814 LOG(ERROR) << "Could not load profile file: " << profile_file;
815 return 0u;
816 }
817
818 ScopedObjectAccess soa(self);
819 VariableSizedHandleScope handles(self);
820 std::vector<Handle<mirror::DexCache>> dex_caches;
821 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
822 for (const DexFile* dex_file : profile_info.GetDexFiles()) {
823 dex_caches.push_back(handles.NewHandle(class_linker->FindDexCache(self, *dex_file)));
824 }
825
826 uint32_t added_to_queue = 0;
827 for (const std::pair<uint32_t, uint32_t>& pair : profile_info.GetMethods()) {
828 if (CompileMethodFromProfile(self,
829 class_linker,
830 pair.second,
831 dex_caches[pair.first],
832 class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +0100833 add_to_queue,
834 /*compile_after_boot=*/false)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100835 ++added_to_queue;
836 }
837 }
838 return added_to_queue;
839}
840
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100841uint32_t Jit::CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100842 Thread* self,
843 const std::vector<const DexFile*>& dex_files,
844 const std::string& profile_file,
845 Handle<mirror::ClassLoader> class_loader,
846 bool add_to_queue) {
847
848 if (profile_file.empty()) {
849 LOG(WARNING) << "Expected a profile file in JIT zygote mode";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100850 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000851 }
852
853 std::string error_msg;
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100854 ScopedFlock profile = LockedFile::Open(
855 profile_file.c_str(), O_RDONLY, /* block= */ false, &error_msg);
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000856
857 // Return early if we're unable to obtain a lock on the profile.
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100858 if (profile.get() == nullptr) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000859 LOG(ERROR) << "Cannot lock profile: " << error_msg;
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100860 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000861 }
862
863 ProfileCompilationInfo profile_info;
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100864 if (!profile_info.Load(profile->Fd())) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000865 LOG(ERROR) << "Could not load profile file";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100866 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000867 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000868 ScopedObjectAccess soa(self);
869 StackHandleScope<1> hs(self);
870 MutableHandle<mirror::DexCache> dex_cache = hs.NewHandle<mirror::DexCache>(nullptr);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100871 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100872 uint32_t added_to_queue = 0u;
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100873 for (const DexFile* dex_file : dex_files) {
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +0100874 if (LocationIsOnRuntimeModule(dex_file->GetLocation().c_str())) {
875 // The runtime module jars are already preopted.
876 continue;
877 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +0100878 // To speed up class lookups, generate a type lookup table for
879 // the dex file.
Nicolas Geoffrayc5e3a522019-04-30 09:47:55 +0100880 if (dex_file->GetOatDexFile() == nullptr) {
881 TypeLookupTable type_lookup_table = TypeLookupTable::Create(*dex_file);
882 type_lookup_tables_.push_back(
883 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
884 dex_file->SetOatDexFile(type_lookup_tables_.back().get());
885 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +0100886
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000887 std::set<dex::TypeIndex> class_types;
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000888 std::set<uint16_t> all_methods;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000889 if (!profile_info.GetClassesAndMethods(*dex_file,
890 &class_types,
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000891 &all_methods,
892 &all_methods,
893 &all_methods)) {
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +0100894 // This means the profile file did not reference the dex file, which is the case
895 // if there's no classes and methods of that dex file in the profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000896 continue;
897 }
898 dex_cache.Assign(class_linker->FindDexCache(self, *dex_file));
899 CHECK(dex_cache != nullptr) << "Could not find dex cache for " << dex_file->GetLocation();
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000900
901 for (uint16_t method_idx : all_methods) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100902 if (CompileMethodFromProfile(self,
903 class_linker,
904 method_idx,
905 dex_cache,
906 class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +0100907 add_to_queue,
908 /*compile_after_boot=*/true)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100909 ++added_to_queue;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000910 }
911 }
912 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100913 return added_to_queue;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000914}
915
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100916static bool IgnoreSamplesForMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray32384402019-07-17 20:06:44 +0100917 if (method->IsClassInitializer() || !method->IsCompilable() || method->IsPreCompiled()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100918 // We do not want to compile such methods.
919 return true;
920 }
921 if (method->IsNative()) {
922 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100923 if (klass == GetClassRoot<mirror::MethodHandle>() ||
924 klass == GetClassRoot<mirror::VarHandle>()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100925 // MethodHandle and VarHandle invocation methods are required to throw an
926 // UnsupportedOperationException if invoked reflectively. We achieve this by having native
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000927 // implementations that raise the exception. We need to disable JIT compilation of these JNI
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100928 // methods as it can lead to transitioning between JIT compiled JNI stubs and generic JNI
929 // stubs. Since these stubs have different stack representations we can then crash in stack
930 // walking (b/78151261).
931 return true;
932 }
933 }
934 return false;
935}
936
David Srbeckye3fc2d12018-11-30 13:41:14 +0000937bool Jit::MaybeCompileMethod(Thread* self,
938 ArtMethod* method,
939 uint32_t old_count,
940 uint32_t new_count,
941 bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100942 if (thread_pool_ == nullptr) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000943 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100944 }
David Srbecky1fc4d422019-07-23 16:55:19 +0100945 if (UNLIKELY(method->IsPreCompiled()) && !with_backedges /* don't check for OSR */) {
946 const void* code_ptr = code_cache_->GetZygoteMap()->GetCodeFor(method);
947 if (code_ptr != nullptr) {
948 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(method, code_ptr);
949 return true;
950 }
951 }
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100952 if (IgnoreSamplesForMethod(method)) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000953 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100954 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100955 if (HotMethodThreshold() == 0) {
David Srbeckyf4886df2017-12-11 16:06:29 +0000956 // Tests might request JIT on first use (compiled synchronously in the interpreter).
David Srbeckye3fc2d12018-11-30 13:41:14 +0000957 return false;
David Srbeckyf4886df2017-12-11 16:06:29 +0000958 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100959 DCHECK_GT(WarmMethodThreshold(), 0);
960 DCHECK_GT(HotMethodThreshold(), WarmMethodThreshold());
961 DCHECK_GT(OSRMethodThreshold(), HotMethodThreshold());
962 DCHECK_GE(PriorityThreadWeight(), 1);
963 DCHECK_LE(PriorityThreadWeight(), HotMethodThreshold());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100964
David Srbeckye3fc2d12018-11-30 13:41:14 +0000965 if (old_count < WarmMethodThreshold() && new_count >= WarmMethodThreshold()) {
966 // Note: Native method have no "warm" state or profiling info.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000967 if (!method->IsNative() &&
968 (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) &&
969 code_cache_->CanAllocateProfilingInfo()) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700970 bool success = ProfilingInfo::Create(self, method, /* retry_allocation= */ false);
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000971 if (success) {
972 VLOG(jit) << "Start profiling " << method->PrettyMethod();
973 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100974
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000975 if (thread_pool_ == nullptr) {
976 // Calling ProfilingInfo::Create might put us in a suspended state, which could
977 // lead to the thread pool being deleted when we are shutting down.
David Srbeckye3fc2d12018-11-30 13:41:14 +0000978 return false;
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000979 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100980
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000981 if (!success) {
982 // We failed allocating. Instead of doing the collection on the Java thread, we push
983 // an allocation to a compiler thread, that will do the collection.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000984 thread_pool_->AddTask(
985 self, new JitCompileTask(method, JitCompileTask::TaskKind::kAllocateProfile));
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000986 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100987 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000988 }
989 if (UseJitCompilation()) {
David Srbeckyc45b5892019-04-24 10:32:04 +0100990 if (old_count == 0 &&
991 method->IsNative() &&
992 Runtime::Current()->IsUsingApexBootImageLocation()) {
993 // jitzygote: Compile JNI stub on first use to avoid the expensive generic stub.
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100994 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ false);
David Srbeckyc45b5892019-04-24 10:32:04 +0100995 return true;
996 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000997 if (old_count < HotMethodThreshold() && new_count >= HotMethodThreshold()) {
998 if (!code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Calin Juravleffc87072016-04-20 14:22:09 +0100999 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001000 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompile));
Calin Juravleffc87072016-04-20 14:22:09 +01001001 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001002 }
1003 if (old_count < OSRMethodThreshold() && new_count >= OSRMethodThreshold()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001004 if (!with_backedges) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001005 return false;
Calin Juravleffc87072016-04-20 14:22:09 +01001006 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001007 DCHECK(!method->IsNative()); // No back edges reported for native methods.
David Srbeckye3fc2d12018-11-30 13:41:14 +00001008 if (!code_cache_->IsOsrCompiled(method)) {
Calin Juravleffc87072016-04-20 14:22:09 +01001009 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001010 thread_pool_->AddTask(
1011 self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompileOsr));
Calin Juravleffc87072016-04-20 14:22:09 +01001012 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001013 }
1014 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001015 return true;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001016}
1017
Alex Light59b950f2018-10-08 10:43:06 -07001018class ScopedSetRuntimeThread {
1019 public:
1020 explicit ScopedSetRuntimeThread(Thread* self)
1021 : self_(self), was_runtime_thread_(self_->IsRuntimeThread()) {
1022 self_->SetIsRuntimeThread(true);
1023 }
1024
1025 ~ScopedSetRuntimeThread() {
1026 self_->SetIsRuntimeThread(was_runtime_thread_);
1027 }
1028
1029 private:
1030 Thread* self_;
1031 bool was_runtime_thread_;
1032};
1033
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001034void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
Calin Juravleffc87072016-04-20 14:22:09 +01001035 Runtime* runtime = Runtime::Current();
Nicolas Geoffray5e33ccd2019-07-03 10:53:08 +01001036 if (UNLIKELY(runtime->UseJitCompilation() && JitAtFirstUse())) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001037 ArtMethod* np_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001038 if (np_method->IsCompilable()) {
Nicolas Geoffray5e33ccd2019-07-03 10:53:08 +01001039 if (!np_method->IsNative() && GetCodeCache()->CanAllocateProfilingInfo()) {
Nicolas Geoffray29bb8032019-06-06 10:32:24 +01001040 // The compiler requires a ProfilingInfo object for non-native methods.
1041 ProfilingInfo::Create(thread, np_method, /* retry_allocation= */ true);
1042 }
1043 // TODO(ngeoffray): For JIT at first use, use kPreCompile. Currently we don't due to
1044 // conflicts with jitzygote optimizations.
1045 JitCompileTask compile_task(method, JitCompileTask::TaskKind::kCompile);
Alex Light59b950f2018-10-08 10:43:06 -07001046 // Fake being in a runtime thread so that class-load behavior will be the same as normal jit.
1047 ScopedSetRuntimeThread ssrt(thread);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001048 compile_task.Run(thread);
1049 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001050 return;
1051 }
1052
Andreas Gampe542451c2016-07-26 09:02:02 -07001053 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001054 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
Alex Light2d441b12018-06-08 15:33:21 -07001055 // instead of interpreting the method. We don't update it for instrumentation as the entrypoint
1056 // must remain the instrumentation entrypoint.
1057 if ((profiling_info != nullptr) &&
1058 (profiling_info->GetSavedEntryPoint() != nullptr) &&
1059 (method->GetEntryPointFromQuickCompiledCode() != GetQuickInstrumentationEntryPoint())) {
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001060 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1061 method, profiling_info->GetSavedEntryPoint());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001062 } else {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001063 AddSamples(thread, method, 1, /* with_backedges= */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001064 }
1065}
1066
Mathieu Chartieref41db72016-10-25 15:08:01 -07001067void Jit::InvokeVirtualOrInterface(ObjPtr<mirror::Object> this_object,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001068 ArtMethod* caller,
1069 uint32_t dex_pc,
1070 ArtMethod* callee ATTRIBUTE_UNUSED) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001071 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001072 DCHECK(this_object != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001073 ProfilingInfo* info = caller->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001074 if (info != nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001075 info->AddInvokeInfo(dex_pc, this_object->GetClass());
1076 }
1077}
1078
1079void Jit::WaitForCompilationToFinish(Thread* self) {
1080 if (thread_pool_ != nullptr) {
1081 thread_pool_->Wait(self, false, false);
1082 }
1083}
1084
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001085void Jit::Stop() {
1086 Thread* self = Thread::Current();
1087 // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
1088 WaitForCompilationToFinish(self);
1089 GetThreadPool()->StopWorkers(self);
1090 WaitForCompilationToFinish(self);
1091}
1092
1093void Jit::Start() {
David Srbeckyd25eb2c2018-07-19 12:17:04 +00001094 GetThreadPool()->StartWorkers(Thread::Current());
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001095}
1096
Andreas Gampef149b3f2016-11-16 14:58:24 -08001097ScopedJitSuspend::ScopedJitSuspend() {
1098 jit::Jit* jit = Runtime::Current()->GetJit();
1099 was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
1100 if (was_on_) {
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001101 jit->Stop();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001102 }
1103}
1104
1105ScopedJitSuspend::~ScopedJitSuspend() {
1106 if (was_on_) {
1107 DCHECK(Runtime::Current()->GetJit() != nullptr);
1108 DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001109 Runtime::Current()->GetJit()->Start();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001110 }
1111}
1112
Nicolas Geoffray0d54cfb2019-05-03 09:13:52 +01001113void Jit::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001114 if (is_zygote || Runtime::Current()->IsSafeMode()) {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001115 // Delete the thread pool, we are not going to JIT.
1116 thread_pool_.reset(nullptr);
1117 return;
1118 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001119 // At this point, the compiler options have been adjusted to the particular configuration
1120 // of the forked child. Parse them again.
David Srbecky46b53532019-08-06 13:39:05 +01001121 jit_compiler_->ParseCompilerOptions();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001122
1123 // Adjust the status of code cache collection: the status from zygote was to not collect.
David Srbecky46b53532019-08-06 13:39:05 +01001124 code_cache_->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001125 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001126
1127 if (thread_pool_ != nullptr) {
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001128 if (is_system_server &&
1129 Runtime::Current()->IsUsingApexBootImageLocation() &&
1130 UseJitCompilation()) {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001131 // Disable garbage collection: we don't want it to delete methods we're compiling
1132 // through boot and system server profiles.
1133 // TODO(ngeoffray): Fix this so we still collect deoptimized and unused code.
1134 code_cache_->SetGarbageCollectCode(false);
Nicolas Geoffray0d54cfb2019-05-03 09:13:52 +01001135 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001136
1137 // Resume JIT compilation.
1138 thread_pool_->CreateThreads();
1139 }
1140}
1141
1142void Jit::PreZygoteFork() {
1143 if (thread_pool_ == nullptr) {
1144 return;
1145 }
1146 thread_pool_->DeleteThreads();
1147}
1148
1149void Jit::PostZygoteFork() {
1150 if (thread_pool_ == nullptr) {
1151 return;
1152 }
1153 thread_pool_->CreateThreads();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001154}
1155
David Srbeckybfcea3d2019-08-05 15:44:00 +01001156void Jit::BootCompleted() {
1157 Thread* self = Thread::Current();
1158 std::deque<Task*> tasks;
1159 {
1160 MutexLock mu(self, boot_completed_lock_);
1161 tasks = std::move(tasks_after_boot_);
1162 boot_completed_ = true;
1163 }
1164 for (Task* task : tasks) {
1165 thread_pool_->AddTask(self, task);
1166 }
1167}
1168
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001169bool Jit::CanEncodeMethod(ArtMethod* method, bool is_for_shared_region) const {
1170 return !is_for_shared_region ||
1171 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(method->GetDeclaringClass());
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001172}
1173
1174bool Jit::CanEncodeClass(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001175 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(cls);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001176}
1177
1178bool Jit::CanEncodeString(ObjPtr<mirror::String> string, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001179 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001180}
1181
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001182bool Jit::CanAssumeInitialized(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
1183 if (!is_for_shared_region) {
1184 return cls->IsInitialized();
1185 } else {
1186 // Look up the class status in the oat file.
1187 const DexFile& dex_file = *cls->GetDexCache()->GetDexFile();
1188 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1189 // In case we run without an image there won't be a backing oat file.
1190 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
1191 return false;
1192 }
1193 uint16_t class_def_index = cls->GetDexClassDefIndex();
1194 return oat_dex_file->GetOatClass(class_def_index).GetStatus() >= ClassStatus::kInitialized;
1195 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001196}
1197
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001198} // namespace jit
1199} // namespace art