blob: 25b5be5d7d598f65ca382eb3b2f1a33c248967ce [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.
Nicolas Geoffray623d4f12019-09-30 13:45:51 +010025#include "base/memfd.h"
Andreas Gampe0897e1c2017-05-16 08:36:56 -070026#include "base/memory_tool.h"
Andreas Gampedcc528d2017-12-07 13:37:10 -080027#include "base/runtime_debug.h"
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +000028#include "base/scoped_flock.h"
David Sehrc431b9d2018-03-02 12:01:51 -080029#include "base/utils.h"
Vladimir Markoc7aa87e2018-05-24 15:19:52 +010030#include "class_root.h"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070031#include "debugger.h"
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +010032#include "dex/type_lookup_table.h"
Nicolas Geoffray623d4f12019-09-30 13:45:51 +010033#include "gc/space/image_space.h"
Vladimir Marko5115a4d2019-10-17 14:56:47 +010034#include "entrypoints/entrypoint_utils-inl.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080035#include "entrypoints/runtime_asm_entrypoints.h"
Nicolas Geoffray623d4f12019-09-30 13:45:51 +010036#include "image-inl.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080037#include "interpreter/interpreter.h"
David Srbeckye3fc2d12018-11-30 13:41:14 +000038#include "jit-inl.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080039#include "jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010040#include "jni/java_vm_ext.h"
Orion Hodson52f5a1f2018-05-02 11:05:44 +010041#include "mirror/method_handle_impl.h"
42#include "mirror/var_handle.h"
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +010043#include "oat_file.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010044#include "oat_file_manager.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000045#include "oat_quick_method_header.h"
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +010046#include "profile/profile_boot_info.h"
David Sehr82d046e2018-04-23 08:14:19 -070047#include "profile/profile_compilation_info.h"
Calin Juravle4d77b6a2015-12-01 18:38:09 +000048#include "profile_saver.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080049#include "runtime.h"
50#include "runtime_options.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070051#include "stack.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000052#include "stack_map.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070053#include "thread-inl.h"
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +010054#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080055
Nicolas Geoffray623d4f12019-09-30 13:45:51 +010056using android::base::unique_fd;
57
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080058namespace art {
59namespace jit {
60
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +000061static constexpr bool kEnableOnStackReplacement = true;
Nicolas Geoffraye8662132016-02-15 10:00:42 +000062
Orion Hodson4fa78a02019-09-12 09:35:24 +010063// Maximum permitted threshold value.
64static constexpr uint32_t kJitMaxThreshold = std::numeric_limits<uint16_t>::max();
65
Andreas Gampe7897cec2017-07-19 16:28:59 -070066// Different compilation threshold constants. These can be overridden on the command line.
Orion Hodson4fa78a02019-09-12 09:35:24 +010067
68// Non-debug default
69static constexpr uint32_t kJitDefaultCompileThreshold = 20 * kJitSamplesBatchSize;
70// Fast-debug build.
71static constexpr uint32_t kJitStressDefaultCompileThreshold = 2 * kJitSamplesBatchSize;
72// Slow-debug build.
73static constexpr uint32_t kJitSlowStressDefaultCompileThreshold = 2;
74
75// Different warm-up threshold constants. These default to the equivalent compile thresholds divided
76// by 2, but can be overridden at the command-line.
77static constexpr uint32_t kJitDefaultWarmUpThreshold = kJitDefaultCompileThreshold / 2;
78static constexpr uint32_t kJitStressDefaultWarmUpThreshold = kJitStressDefaultCompileThreshold / 2;
79static constexpr uint32_t kJitSlowStressDefaultWarmUpThreshold =
80 kJitSlowStressDefaultCompileThreshold / 2;
Andreas Gampe7897cec2017-07-19 16:28:59 -070081
David Srbecky21821472019-07-29 15:10:31 +010082DEFINE_RUNTIME_DEBUG_FLAG(Jit, kSlowMode);
83
Mathieu Chartier72918ea2016-03-24 11:07:06 -070084// JIT compiler
Igor Murashkin2ffb7032017-11-08 13:35:21 -080085void* Jit::jit_library_handle_ = nullptr;
David Srbecky46b53532019-08-06 13:39:05 +010086JitCompilerInterface* Jit::jit_compiler_ = nullptr;
87JitCompilerInterface* (*Jit::jit_load_)(void) = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070088
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080089JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080090 auto* jit_options = new JitOptions;
Calin Juravleffc87072016-04-20 14:22:09 +010091 jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000092
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000093 jit_options->code_cache_initial_capacity_ =
94 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
95 jit_options->code_cache_max_capacity_ =
96 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -070097 jit_options->dump_info_on_shutdown_ =
98 options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
Calin Juravle138dbff2016-06-28 19:36:58 +010099 jit_options->profile_saver_options_ =
100 options.GetOrDefault(RuntimeArgumentMap::ProfileSaverOpts);
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100101 jit_options->thread_pool_pthread_priority_ =
102 options.GetOrDefault(RuntimeArgumentMap::JITPoolThreadPthreadPriority);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000103
Orion Hodson4fa78a02019-09-12 09:35:24 +0100104 // Set default compile threshold to aide with sanity checking defaults.
105 jit_options->compile_threshold_ =
106 kIsDebugBuild
107 ? (Jit::kSlowMode
108 ? kJitSlowStressDefaultCompileThreshold
109 : kJitStressDefaultCompileThreshold)
110 : kJitDefaultCompileThreshold;
111
112 // When not running in slow-mode, thresholds are quantized to kJitSamplesbatchsize.
113 const uint32_t kJitThresholdStep = Jit::kSlowMode ? 1u : kJitSamplesBatchSize;
114
115 // Set default warm-up threshold to aide with sanity checking defaults.
116 jit_options->warmup_threshold_ =
117 kIsDebugBuild ? (Jit::kSlowMode
118 ? kJitSlowStressDefaultWarmUpThreshold
119 : kJitStressDefaultWarmUpThreshold)
120 : kJitDefaultWarmUpThreshold;
121
122 // Warmup threshold should be less than compile threshold (so long as compile threshold is not
123 // zero == JIT-on-first-use).
124 DCHECK_LT(jit_options->warmup_threshold_, jit_options->compile_threshold_);
125 DCHECK_EQ(RoundUp(jit_options->warmup_threshold_, kJitThresholdStep),
126 jit_options->warmup_threshold_);
127
Andreas Gampe7897cec2017-07-19 16:28:59 -0700128 if (options.Exists(RuntimeArgumentMap::JITCompileThreshold)) {
129 jit_options->compile_threshold_ = *options.Get(RuntimeArgumentMap::JITCompileThreshold);
Andreas Gampe7897cec2017-07-19 16:28:59 -0700130 }
Orion Hodson4fa78a02019-09-12 09:35:24 +0100131 jit_options->compile_threshold_ = RoundUp(jit_options->compile_threshold_, kJitThresholdStep);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000132
133 if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
134 jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000135 }
Orion Hodson4fa78a02019-09-12 09:35:24 +0100136 jit_options->warmup_threshold_ = RoundUp(jit_options->warmup_threshold_, kJitThresholdStep);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000137
138 if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
139 jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000140 } else {
141 jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
Orion Hodson4fa78a02019-09-12 09:35:24 +0100142 if (jit_options->osr_threshold_ > kJitMaxThreshold) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000143 jit_options->osr_threshold_ =
Orion Hodson4fa78a02019-09-12 09:35:24 +0100144 RoundDown(kJitMaxThreshold, kJitThresholdStep);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000145 }
146 }
Orion Hodson4fa78a02019-09-12 09:35:24 +0100147 jit_options->osr_threshold_ = RoundUp(jit_options->osr_threshold_, kJitThresholdStep);
148
149 // Enforce ordering constraints between thresholds if not jit-on-first-use (when the compile
150 // threshold is 0).
151 if (jit_options->compile_threshold_ != 0) {
152 // Clamp thresholds such that OSR > compile > warm-up (see Jit::MaybeCompileMethod).
153 jit_options->osr_threshold_ = std::clamp(jit_options->osr_threshold_,
154 2u * kJitThresholdStep,
155 RoundDown(kJitMaxThreshold, kJitThresholdStep));
156 jit_options->compile_threshold_ = std::clamp(jit_options->compile_threshold_,
157 kJitThresholdStep,
158 jit_options->osr_threshold_ - kJitThresholdStep);
159 jit_options->warmup_threshold_ =
160 std::clamp(jit_options->warmup_threshold_,
161 0u,
162 jit_options->compile_threshold_ - kJitThresholdStep);
163 }
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000164
Calin Juravleb2771b42016-04-07 17:09:25 +0100165 if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
166 jit_options->priority_thread_weight_ =
167 *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
168 if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
169 LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
170 } else if (jit_options->priority_thread_weight_ == 0) {
171 LOG(FATAL) << "Priority thread weight cannot be 0.";
172 }
173 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100174 jit_options->priority_thread_weight_ = std::max(
175 jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
176 static_cast<size_t>(1));
Calin Juravleb2771b42016-04-07 17:09:25 +0100177 }
178
Calin Juravle155ff3d2016-04-27 14:14:58 +0100179 if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100180 jit_options->invoke_transition_weight_ =
181 *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
Calin Juravle155ff3d2016-04-27 14:14:58 +0100182 if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
183 LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
184 } else if (jit_options->invoke_transition_weight_ == 0) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100185 LOG(FATAL) << "Invoke transition weight cannot be 0.";
Calin Juravle155ff3d2016-04-27 14:14:58 +0100186 }
Calin Juravle155ff3d2016-04-27 14:14:58 +0100187 } else {
188 jit_options->invoke_transition_weight_ = std::max(
189 jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
Mathieu Chartier6beced42016-11-15 15:51:31 -0800190 static_cast<size_t>(1));
Calin Juravle155ff3d2016-04-27 14:14:58 +0100191 }
192
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800193 return jit_options;
194}
195
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700196void Jit::DumpInfo(std::ostream& os) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000197 code_cache_->Dump(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700198 cumulative_timings_.Dump(os);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000199 MutexLock mu(Thread::Current(), lock_);
200 memory_use_.PrintMemoryUse(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700201}
202
Calin Juravleb8e69992016-03-09 15:37:48 +0000203void Jit::DumpForSigQuit(std::ostream& os) {
204 DumpInfo(os);
205 ProfileSaver::DumpInstanceInfo(os);
206}
207
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700208void Jit::AddTimingLogger(const TimingLogger& logger) {
209 cumulative_timings_.AddLogger(logger);
210}
211
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100212Jit::Jit(JitCodeCache* code_cache, JitOptions* options)
213 : code_cache_(code_cache),
214 options_(options),
David Srbeckybfcea3d2019-08-05 15:44:00 +0100215 boot_completed_lock_("Jit::boot_completed_lock_"),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100216 cumulative_timings_("JIT timings"),
217 memory_use_("Memory used for compilation", 16),
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000218 lock_("JIT memory use lock"),
219 zygote_mapping_methods_(),
220 fd_methods_(-1),
221 fd_methods_size_(0) {}
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800222
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100223Jit* Jit::Create(JitCodeCache* code_cache, JitOptions* options) {
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000224 if (jit_load_ == nullptr) {
225 LOG(WARNING) << "Not creating JIT: library not loaded";
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800226 return nullptr;
227 }
David Srbecky46b53532019-08-06 13:39:05 +0100228 jit_compiler_ = (jit_load_)();
229 if (jit_compiler_ == nullptr) {
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000230 LOG(WARNING) << "Not creating JIT: failed to allocate a compiler";
231 return nullptr;
232 }
233 std::unique_ptr<Jit> jit(new Jit(code_cache, options));
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000234
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000235 // If the code collector is enabled, check if that still holds:
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000236 // With 'perf', we want a 1-1 mapping between an address and a method.
237 // We aren't able to keep method pointers live during the instrumentation method entry trampoline
238 // so we will just disable jit-gc if we are doing that.
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000239 if (code_cache->GetGarbageCollectCode()) {
David Srbecky46b53532019-08-06 13:39:05 +0100240 code_cache->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000241 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
242 }
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100243
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000244 VLOG(jit) << "JIT created with initial_capacity="
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000245 << PrettySize(options->GetCodeCacheInitialCapacity())
246 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000247 << ", compile_threshold=" << options->GetCompileThreshold()
Calin Juravle138dbff2016-06-28 19:36:58 +0100248 << ", profile_saver_options=" << options->GetProfileSaverOptions();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100249
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100250 // Notify native debugger about the classes already loaded before the creation of the jit.
251 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800252 return jit.release();
253}
254
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000255template <typename T>
256bool Jit::LoadSymbol(T* address, const char* name, std::string* error_msg) {
257 *address = reinterpret_cast<T>(dlsym(jit_library_handle_, name));
258 if (*address == nullptr) {
259 *error_msg = std::string("JIT couldn't find ") + name + std::string(" entry point");
260 return false;
261 }
262 return true;
263}
264
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000265bool Jit::LoadCompilerLibrary(std::string* error_msg) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800266 jit_library_handle_ = dlopen(
267 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
268 if (jit_library_handle_ == nullptr) {
269 std::ostringstream oss;
270 oss << "JIT could not load libart-compiler.so: " << dlerror();
271 *error_msg = oss.str();
272 return false;
273 }
David Srbecky46b53532019-08-06 13:39:05 +0100274 if (!LoadSymbol(&jit_load_, "jit_load", error_msg)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800275 dlclose(jit_library_handle_);
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000276 return false;
277 }
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700278 return true;
279}
280
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100281bool Jit::CompileMethod(ArtMethod* method, Thread* self, bool baseline, bool osr, bool prejit) {
Calin Juravleffc87072016-04-20 14:22:09 +0100282 DCHECK(Runtime::Current()->UseJitCompilation());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800283 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000284
Alex Light0fa17862017-10-24 13:43:05 -0700285 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100286 // Don't compile the method if it has breakpoints.
Alex Light0fa17862017-10-24 13:43:05 -0700287 if (cb->IsMethodBeingInspected(method) && !cb->IsMethodSafeToJit(method)) {
288 VLOG(jit) << "JIT not compiling " << method->PrettyMethod()
289 << " due to not being safe to jit according to runtime-callbacks. For example, there"
290 << " could be breakpoints in this method.";
Mathieu Chartierd8565452015-03-26 09:41:50 -0700291 return false;
292 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100293
294 // Don't compile the method if we are supposed to be deoptimized.
295 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
296 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
David Sehr709b0702016-10-13 09:12:37 -0700297 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to deoptimization";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100298 return false;
299 }
300
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000301 JitMemoryRegion* region = GetCodeCache()->GetCurrentRegion();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100302 if (osr && GetCodeCache()->IsSharedRegion(*region)) {
303 VLOG(jit) << "JIT not osr compiling "
304 << method->PrettyMethod()
305 << " due to using shared region";
306 return false;
307 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000308
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000309 // If we get a request to compile a proxy method, we pass the actual Java method
310 // of that proxy method, as the compiler does not expect a proxy method.
Andreas Gampe542451c2016-07-26 09:02:02 -0700311 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000312 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, osr, prejit, region)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100313 return false;
314 }
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100315
316 VLOG(jit) << "Compiling method "
David Sehr709b0702016-10-13 09:12:37 -0700317 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100318 << " osr=" << std::boolalpha << osr;
David Srbecky46b53532019-08-06 13:39:05 +0100319 bool success = jit_compiler_->CompileMethod(self, region, method_to_compile, baseline, osr);
buzbee454b3b62016-04-07 14:42:47 -0700320 code_cache_->DoneCompiling(method_to_compile, self, osr);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100321 if (!success) {
322 VLOG(jit) << "Failed to compile method "
David Sehr709b0702016-10-13 09:12:37 -0700323 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100324 << " osr=" << std::boolalpha << osr;
325 }
Andreas Gampe320ba912016-11-18 17:39:45 -0800326 if (kIsDebugBuild) {
327 if (self->IsExceptionPending()) {
328 mirror::Throwable* exception = self->GetException();
329 LOG(FATAL) << "No pending exception expected after compiling "
330 << ArtMethod::PrettyMethod(method)
331 << ": "
332 << exception->Dump();
333 }
334 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100335 return success;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800336}
337
Mathieu Chartier93c21ba2018-12-10 13:08:30 -0800338void Jit::WaitForWorkersToBeCreated() {
339 if (thread_pool_ != nullptr) {
340 thread_pool_->WaitForWorkersToBeCreated();
341 }
342}
343
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800344void Jit::DeleteThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100345 Thread* self = Thread::Current();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100346 if (thread_pool_ != nullptr) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700347 std::unique_ptr<ThreadPool> pool;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100348 {
349 ScopedSuspendAll ssa(__FUNCTION__);
350 // Clear thread_pool_ field while the threads are suspended.
351 // A mutator in the 'AddSamples' method will check against it.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700352 pool = std::move(thread_pool_);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100353 }
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700354
355 // When running sanitized, let all tasks finish to not leak. Otherwise just clear the queue.
Roland Levillain05e34f42018-05-24 13:19:05 +0000356 if (!kRunningOnMemoryTool) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700357 pool->StopWorkers(self);
358 pool->RemoveAllTasks(self);
359 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100360 // We could just suspend all threads, but we know those threads
361 // will finish in a short period, so it's not worth adding a suspend logic
362 // here. Besides, this is only done for shutdown.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700363 pool->Wait(self, false, false);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800364 }
365}
366
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000367void Jit::StartProfileSaver(const std::string& filename,
Calin Juravle77651c42017-03-03 18:04:02 -0800368 const std::vector<std::string>& code_paths) {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100369 if (options_->GetSaveProfilingInfo()) {
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100370 ProfileSaver::Start(options_->GetProfileSaverOptions(), filename, code_cache_, code_paths);
Calin Juravle31f2c152015-10-23 17:56:15 +0100371 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000372}
373
374void Jit::StopProfileSaver() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100375 if (options_->GetSaveProfilingInfo() && ProfileSaver::IsStarted()) {
376 ProfileSaver::Stop(options_->DumpJitInfoOnShutdown());
Calin Juravle31f2c152015-10-23 17:56:15 +0100377 }
378}
379
Siva Chandra05d24152016-01-05 17:43:17 -0800380bool Jit::JitAtFirstUse() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100381 return HotMethodThreshold() == 0;
Siva Chandra05d24152016-01-05 17:43:17 -0800382}
383
Nicolas Geoffray35122442016-03-02 12:05:30 +0000384bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
385 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
386}
387
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800388Jit::~Jit() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100389 DCHECK(!options_->GetSaveProfilingInfo() || !ProfileSaver::IsStarted());
390 if (options_->DumpJitInfoOnShutdown()) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700391 DumpInfo(LOG_STREAM(INFO));
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100392 Runtime::Current()->DumpDeoptimizations(LOG_STREAM(INFO));
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700393 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800394 DeleteThreadPool();
David Srbecky46b53532019-08-06 13:39:05 +0100395 if (jit_compiler_ != nullptr) {
396 delete jit_compiler_;
397 jit_compiler_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800398 }
399 if (jit_library_handle_ != nullptr) {
400 dlclose(jit_library_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700401 jit_library_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800402 }
403}
404
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000405void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
Calin Juravleffc87072016-04-20 14:22:09 +0100406 if (!Runtime::Current()->UseJitCompilation()) {
407 // No need to notify if we only use the JIT to save profiles.
408 return;
409 }
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000410 jit::Jit* jit = Runtime::Current()->GetJit();
David Srbecky46b53532019-08-06 13:39:05 +0100411 if (jit->jit_compiler_->GenerateDebugInfo()) {
412 jit_compiler_->TypesLoaded(&type, 1);
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000413 }
414}
415
416void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
417 struct CollectClasses : public ClassVisitor {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100418 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700419 classes_.push_back(klass.Ptr());
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000420 return true;
421 }
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800422 std::vector<mirror::Class*> classes_;
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000423 };
424
David Srbecky46b53532019-08-06 13:39:05 +0100425 if (jit_compiler_->GenerateDebugInfo()) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000426 ScopedObjectAccess so(Thread::Current());
427
428 CollectClasses visitor;
429 linker->VisitClasses(&visitor);
David Srbecky46b53532019-08-06 13:39:05 +0100430 jit_compiler_->TypesLoaded(visitor.classes_.data(), visitor.classes_.size());
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000431 }
432}
433
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000434extern "C" void art_quick_osr_stub(void** stack,
Evgenii Stepanov6d90fde2018-09-04 17:50:38 -0700435 size_t stack_size_in_bytes,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000436 const uint8_t* native_pc,
437 JValue* result,
438 const char* shorty,
439 Thread* self);
440
441bool Jit::MaybeDoOnStackReplacement(Thread* thread,
442 ArtMethod* method,
443 uint32_t dex_pc,
444 int32_t dex_pc_offset,
445 JValue* result) {
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000446 if (!kEnableOnStackReplacement) {
447 return false;
448 }
449
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000450 Jit* jit = Runtime::Current()->GetJit();
451 if (jit == nullptr) {
452 return false;
453 }
454
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000455 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
456 // Don't attempt to do an OSR if we are close to the stack limit. Since
457 // the interpreter frames are still on stack, OSR has the potential
458 // to stack overflow even for a simple loop.
459 // b/27094810.
460 return false;
461 }
462
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000463 // Get the actual Java method if this method is from a proxy class. The compiler
464 // and the JIT code cache do not expect methods from proxy classes.
Andreas Gampe542451c2016-07-26 09:02:02 -0700465 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000466
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000467 // Cheap check if the method has been compiled already. That's an indicator that we should
468 // osr into it.
469 if (!jit->GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
470 return false;
471 }
472
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000473 // Fetch some data before looking up for an OSR method. We don't want thread
474 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
475 // method while we are being suspended.
David Sehr0225f8e2018-01-31 08:52:24 +0000476 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800477 const size_t number_of_vregs = accessor.RegistersSize();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000478 const char* shorty = method->GetShorty();
David Sehr709b0702016-10-13 09:12:37 -0700479 std::string method_name(VLOG_IS_ON(jit) ? method->PrettyMethod() : "");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000480 void** memory = nullptr;
481 size_t frame_size = 0;
482 ShadowFrame* shadow_frame = nullptr;
483 const uint8_t* native_pc = nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000484
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000485 {
Mathieu Chartier268764d2016-09-13 12:09:38 -0700486 ScopedAssertNoThreadSuspension sts("Holding OSR method");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000487 const OatQuickMethodHeader* osr_method = jit->GetCodeCache()->LookupOsrMethodHeader(method);
488 if (osr_method == nullptr) {
489 // No osr method yet, just return to the interpreter.
490 return false;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000491 }
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000492
David Srbecky052f8ca2018-04-26 15:42:54 +0100493 CodeInfo code_info(osr_method);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000494
495 // Find stack map starting at the target dex_pc.
David Srbecky052f8ca2018-04-26 15:42:54 +0100496 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc + dex_pc_offset);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000497 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 false;
501 }
502
Alex Light21611932017-09-26 13:07:39 -0700503 // Before allowing the jump, make sure no code is actively inspecting the method to avoid
504 // jumping from interpreter to OSR while e.g. single stepping. Note that we could selectively
505 // disable OSR when single stepping, but that's currently hard to know at this point.
506 if (Runtime::Current()->GetRuntimeCallbacks()->IsMethodBeingInspected(method)) {
Aart Bik29bdaee2016-05-18 15:44:07 -0700507 return false;
508 }
509
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000510 // We found a stack map, now fill the frame with dex register values from the interpreter's
511 // shadow frame.
David Srbeckyfd89b072018-06-03 12:00:22 +0100512 DexRegisterMap vreg_map = code_info.GetDexRegisterMapOf(stack_map);
Artem Serov2808be82018-12-20 19:15:11 +0000513 DCHECK_EQ(vreg_map.size(), number_of_vregs);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000514
515 frame_size = osr_method->GetFrameSizeInBytes();
516
517 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
518 // stack.
519 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
520 // but that is engineering complexity not worth the effort for something like OSR.
521 memory = reinterpret_cast<void**>(malloc(frame_size));
522 CHECK(memory != nullptr);
523 memset(memory, 0, frame_size);
524
525 // Art ABI: ArtMethod is at the bottom of the stack.
526 memory[0] = method;
527
528 shadow_frame = thread->PopShadowFrame();
David Srbeckyfd89b072018-06-03 12:00:22 +0100529 if (vreg_map.empty()) {
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000530 // If we don't have a dex register map, then there are no live dex registers at
531 // this dex pc.
532 } else {
533 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
David Srbeckye1402122018-06-13 18:20:45 +0100534 DexRegisterLocation::Kind location = vreg_map[vreg].GetKind();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000535 if (location == DexRegisterLocation::Kind::kNone) {
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000536 // Dex register is dead or uninitialized.
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000537 continue;
538 }
539
540 if (location == DexRegisterLocation::Kind::kConstant) {
541 // We skip constants because the compiled code knows how to handle them.
542 continue;
543 }
544
David Srbecky7dc11782016-02-25 13:23:56 +0000545 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000546
547 int32_t vreg_value = shadow_frame->GetVReg(vreg);
David Srbeckye1402122018-06-13 18:20:45 +0100548 int32_t slot_offset = vreg_map[vreg].GetStackOffsetInBytes();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000549 DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
550 DCHECK_GT(slot_offset, 0);
551 (reinterpret_cast<int32_t*>(memory))[slot_offset / sizeof(int32_t)] = vreg_value;
552 }
553 }
554
David Srbecky052f8ca2018-04-26 15:42:54 +0100555 native_pc = stack_map.GetNativePcOffset(kRuntimeISA) +
David Srbecky09ed0982016-02-12 21:58:43 +0000556 osr_method->GetEntryPoint();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000557 VLOG(jit) << "Jumping to "
558 << method_name
559 << "@"
560 << std::hex << reinterpret_cast<uintptr_t>(native_pc);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000561 }
562
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000563 {
564 ManagedStack fragment;
565 thread->PushManagedStackFragment(&fragment);
566 (*art_quick_osr_stub)(memory,
567 frame_size,
568 native_pc,
569 result,
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000570 shorty,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000571 thread);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000572
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000573 if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
574 thread->DeoptimizeWithDeoptimizationException(result);
575 }
576 thread->PopManagedStackFragment(fragment);
577 }
578 free(memory);
579 thread->PushShadowFrame(shadow_frame);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000580 VLOG(jit) << "Done running OSR code for " << method_name;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000581 return true;
582}
583
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000584void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
585 if (bytes > 4 * MB) {
586 LOG(INFO) << "Compiler allocated "
587 << PrettySize(bytes)
588 << " to compile "
David Sehr709b0702016-10-13 09:12:37 -0700589 << ArtMethod::PrettyMethod(method);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000590 }
591 MutexLock mu(Thread::Current(), lock_);
592 memory_use_.AddValue(bytes);
593}
594
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000595void Jit::NotifyZygoteCompilationDone() {
596 if (fd_methods_ == -1) {
597 return;
598 }
599
600 size_t offset = 0;
601 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
602 const ImageHeader& header = space->GetImageHeader();
603 const ImageSection& section = header.GetMethodsSection();
604 // Because mremap works at page boundaries, we can only handle methods
605 // within a page range. For methods that falls above or below the range,
606 // the child processes will copy their contents to their private mapping
607 // in `child_mapping_methods`. See `MapBootImageMethods`.
608 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
609 uint8_t* page_end =
610 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
611 if (page_end > page_start) {
612 uint64_t capacity = page_end - page_start;
613 memcpy(zygote_mapping_methods_.Begin() + offset, page_start, capacity);
614 offset += capacity;
615 }
616 }
617
618 // Do an msync to ensure we are not affected by writes still being in caches.
619 if (msync(zygote_mapping_methods_.Begin(), fd_methods_size_, MS_SYNC) != 0) {
620 PLOG(WARNING) << "Failed to sync boot image methods memory";
621 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
622 return;
623 }
624
625 // We don't need the shared mapping anymore, and we need to drop it in case
626 // the file hasn't been sealed writable.
627 zygote_mapping_methods_ = MemMap::Invalid();
628
629 std::string error_str;
630 MemMap child_mapping_methods = MemMap::MapFile(
631 fd_methods_size_,
632 PROT_READ | PROT_WRITE,
633 MAP_PRIVATE,
634 fd_methods_,
635 /* start= */ 0,
636 /* low_4gb= */ false,
637 "boot-image-methods",
638 &error_str);
639
640 if (!child_mapping_methods.IsValid()) {
641 LOG(WARNING) << "Failed to create child mapping of boot image methods: " << error_str;
642 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
643 return;
644 }
645
646 if (!IsSealFutureWriteSupported()) {
647 // If we didn't write seal the fd before, seal it now.
648
649 if (fcntl(fd_methods_, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_WRITE) == -1) {
650 PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
651 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
652 return;
653 }
654
655 // Ensure the contents are the same as before: there was a window between
656 // the memcpy and the sealing where other processes could have changed the
657 // contents.
658 offset = 0;
659 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
660 const ImageHeader& header = space->GetImageHeader();
661 const ImageSection& section = header.GetMethodsSection();
662 // Because mremap works at page boundaries, we can only handle methods
663 // within a page range. For methods that falls above or below the range,
664 // the child processes will copy their contents to their private mapping
665 // in `child_mapping_methods`. See `MapBootImageMethods`.
666 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
667 uint8_t* page_end =
668 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
669 if (page_end > page_start) {
670 uint64_t capacity = page_end - page_start;
671 if (memcmp(child_mapping_methods.Begin() + offset, page_start, capacity) != 0) {
672 LOG(WARNING) << "Contents differ in boot image methods data";
673 code_cache_->GetZygoteMap()->SetCompilationState(
674 ZygoteCompilationState::kNotifiedFailure);
675 return;
676 }
677 offset += capacity;
678 }
679 }
680 }
681
682 // Future spawned processes don't need the fd anymore.
683 fd_methods_.reset();
684
685 // In order to have the zygote and children share the memory, we also remap
686 // the memory into the zygote process.
687 offset = 0;
688 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
689 const ImageHeader& header = space->GetImageHeader();
690 const ImageSection& section = header.GetMethodsSection();
691 // Because mremap works at page boundaries, we can only handle methods
692 // within a page range. For methods that falls above or below the range,
693 // the child processes will copy their contents to their private mapping
694 // in `child_mapping_methods`. See `MapBootImageMethods`.
695 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
696 uint8_t* page_end =
697 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
698 if (page_end > page_start) {
699 uint64_t capacity = page_end - page_start;
700 if (mremap(child_mapping_methods.Begin() + offset,
701 capacity,
702 capacity,
703 MREMAP_FIXED | MREMAP_MAYMOVE,
704 page_start) == MAP_FAILED) {
705 // Failing to remap is safe as the process will just use the old
706 // contents.
707 PLOG(WARNING) << "Failed mremap of boot image methods of " << space->GetImageFilename();
708 }
709 offset += capacity;
710 }
711 }
712
713 // Mark that compilation of boot classpath is done, and memory can now be
714 // shared. Other processes will pick up this information.
715 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedOk);
716
717 // The private mapping created for this process has been mremaped. We can
718 // reset it.
719 child_mapping_methods.Reset();
720}
721
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100722class JitCompileTask final : public Task {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100723 public:
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000724 enum class TaskKind {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100725 kAllocateProfile,
726 kCompile,
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000727 kCompileBaseline,
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000728 kCompileOsr,
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100729 kPreCompile,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100730 };
731
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000732 JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind), klass_(nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100733 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000734 // For a non-bootclasspath class, add a global ref to the class to prevent class unloading
735 // until compilation is done.
736 if (method->GetDeclaringClass()->GetClassLoader() != nullptr) {
737 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
738 CHECK(klass_ != nullptr);
739 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100740 }
741
742 ~JitCompileTask() {
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000743 if (klass_ != nullptr) {
744 ScopedObjectAccess soa(Thread::Current());
745 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
746 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100747 }
748
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100749 void Run(Thread* self) override {
Andreas Gampe4bd52342019-07-15 15:09:04 -0700750 {
751 ScopedObjectAccess soa(self);
752 switch (kind_) {
753 case TaskKind::kPreCompile:
754 case TaskKind::kCompile:
755 case TaskKind::kCompileBaseline:
756 case TaskKind::kCompileOsr: {
757 Runtime::Current()->GetJit()->CompileMethod(
758 method_,
759 self,
760 /* baseline= */ (kind_ == TaskKind::kCompileBaseline),
761 /* osr= */ (kind_ == TaskKind::kCompileOsr),
762 /* prejit= */ (kind_ == TaskKind::kPreCompile));
763 break;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000764 }
Andreas Gampe4bd52342019-07-15 15:09:04 -0700765 case TaskKind::kAllocateProfile: {
766 if (ProfilingInfo::Create(self, method_, /* retry_allocation= */ true)) {
767 VLOG(jit) << "Start profiling " << ArtMethod::PrettyMethod(method_);
768 }
769 break;
770 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100771 }
772 }
Calin Juravlea2638922016-04-29 16:44:11 +0100773 ProfileSaver::NotifyJitActivity();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100774 }
775
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100776 void Finalize() override {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100777 delete this;
778 }
779
780 private:
781 ArtMethod* const method_;
782 const TaskKind kind_;
783 jobject klass_;
784
785 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
786};
787
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100788static std::string GetProfileFile(const std::string& dex_location) {
789 // Hardcoded assumption where the profile file is.
790 // TODO(ngeoffray): this is brittle and we would need to change change if we
791 // wanted to do more eager JITting of methods in a profile. This is
792 // currently only for system server.
793 return dex_location + ".prof";
794}
795
796static std::string GetBootProfileFile(const std::string& profile) {
797 // The boot profile can be found next to the compilation profile, with a
798 // different extension.
799 return ReplaceFileExtension(profile, "bprof");
800}
801
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100802/**
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100803 * A JIT task to run after all profile compilation is done.
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100804 */
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100805class JitDoneCompilingProfileTask final : public SelfDeletingTask {
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100806 public:
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100807 explicit JitDoneCompilingProfileTask(const std::vector<const DexFile*>& dex_files)
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100808 : dex_files_(dex_files) {}
809
810 void Run(Thread* self ATTRIBUTE_UNUSED) override {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100811 // Madvise DONTNEED dex files now that we're done compiling methods.
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100812 for (const DexFile* dex_file : dex_files_) {
813 if (IsAddressKnownBackedByFileOrShared(dex_file->Begin())) {
814 int result = madvise(const_cast<uint8_t*>(AlignDown(dex_file->Begin(), kPageSize)),
815 RoundUp(dex_file->Size(), kPageSize),
816 MADV_DONTNEED);
817 if (result == -1) {
818 PLOG(WARNING) << "Madvise failed";
819 }
820 }
821 }
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100822
823 if (Runtime::Current()->IsZygote()) {
824 // Copy the boot image methods data to the mappings we created to share
825 // with the children.
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000826 Runtime::Current()->GetJit()->NotifyZygoteCompilationDone();
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100827 }
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100828 }
829
830 private:
831 std::vector<const DexFile*> dex_files_;
832
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100833 DISALLOW_COPY_AND_ASSIGN(JitDoneCompilingProfileTask);
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100834};
835
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000836class ZygoteTask final : public Task {
837 public:
838 ZygoteTask() {}
839
840 void Run(Thread* self) override {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100841 Runtime* runtime = Runtime::Current();
842 std::string profile_file;
843 for (const std::string& option : runtime->GetImageCompilerOptions()) {
844 if (android::base::StartsWith(option, "--profile-file=")) {
845 profile_file = option.substr(strlen("--profile-file="));
846 break;
847 }
848 }
849
850 const std::vector<const DexFile*>& boot_class_path =
851 runtime->GetClassLinker()->GetBootClassPath();
852 ScopedNullHandle<mirror::ClassLoader> null_handle;
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100853 std::string boot_profile = GetBootProfileFile(profile_file);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100854 // We add to the queue for zygote so that we can fork processes in-between
855 // compilations.
Nicolas Geoffraya6f35832019-08-09 13:34:19 +0100856 uint32_t added_to_queue = 0;
857 if (Runtime::Current()->IsPrimaryZygote()) {
858 // We avoid doing compilation at boot for the secondary zygote, as apps
859 // forked from it are not critical for boot.
860 added_to_queue += runtime->GetJit()->CompileMethodsFromBootProfile(
861 self, boot_class_path, boot_profile, null_handle, /* add_to_queue= */ true);
862 }
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100863 added_to_queue += runtime->GetJit()->CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100864 self, boot_class_path, profile_file, null_handle, /* add_to_queue= */ true);
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100865
866 JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
867 code_cache->GetZygoteMap()->Initialize(added_to_queue);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100868 }
869
870 void Finalize() override {
871 delete this;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000872 }
873
874 private:
875 DISALLOW_COPY_AND_ASSIGN(ZygoteTask);
876};
877
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100878class JitProfileTask final : public Task {
879 public:
880 JitProfileTask(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100881 jobject class_loader) {
882 ScopedObjectAccess soa(Thread::Current());
883 StackHandleScope<1> hs(soa.Self());
884 Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
885 soa.Decode<mirror::ClassLoader>(class_loader)));
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100886 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
887 for (const auto& dex_file : dex_files) {
888 dex_files_.push_back(dex_file.get());
889 // Register the dex file so that we can guarantee it doesn't get deleted
890 // while reading it during the task.
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100891 class_linker->RegisterDexFile(*dex_file.get(), h_loader.Get());
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100892 }
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100893 // We also create our own global ref to use this class loader later.
894 class_loader_ = soa.Vm()->AddGlobalRef(soa.Self(), h_loader.Get());
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100895 }
896
897 void Run(Thread* self) override {
898 ScopedObjectAccess soa(self);
899 StackHandleScope<1> hs(self);
900 Handle<mirror::ClassLoader> loader = hs.NewHandle<mirror::ClassLoader>(
901 soa.Decode<mirror::ClassLoader>(class_loader_));
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100902
903 std::string profile = GetProfileFile(dex_files_[0]->GetLocation());
904 std::string boot_profile = GetBootProfileFile(profile);
905
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100906 Jit* jit = Runtime::Current()->GetJit();
907
908 jit->CompileMethodsFromBootProfile(
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100909 self,
910 dex_files_,
911 boot_profile,
912 loader,
913 /* add_to_queue= */ false);
914
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100915 jit->CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100916 self,
917 dex_files_,
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100918 profile,
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100919 loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +0100920 /* add_to_queue= */ true);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100921 }
922
923 void Finalize() override {
924 delete this;
925 }
926
Nicolas Geoffrayf5a07ae2019-06-20 14:59:07 +0100927 ~JitProfileTask() {
928 ScopedObjectAccess soa(Thread::Current());
929 soa.Vm()->DeleteGlobalRef(soa.Self(), class_loader_);
930 }
931
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100932 private:
933 std::vector<const DexFile*> dex_files_;
934 jobject class_loader_;
935
936 DISALLOW_COPY_AND_ASSIGN(JitProfileTask);
937};
938
Nicolas Geoffrayff258062019-10-09 15:33:48 +0100939static void CopyIfDifferent(void* s1, const void* s2, size_t n) {
940 if (memcmp(s1, s2, n) != 0) {
941 memcpy(s1, s2, n);
942 }
943}
944
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100945void Jit::MapBootImageMethods() {
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000946 CHECK_NE(fd_methods_.get(), -1);
947 if (!code_cache_->GetZygoteMap()->CanMapBootImageMethods()) {
948 LOG(WARNING) << "Not mapping boot image methods due to error from zygote";
949 return;
950 }
951
952 std::string error_str;
953 MemMap child_mapping_methods = MemMap::MapFile(
954 fd_methods_size_,
955 PROT_READ | PROT_WRITE,
956 MAP_PRIVATE,
957 fd_methods_,
958 /* start= */ 0,
959 /* low_4gb= */ false,
960 "boot-image-methods",
961 &error_str);
962
963 // We don't need the fd anymore.
964 fd_methods_.reset();
965
966 if (!child_mapping_methods.IsValid()) {
967 LOG(WARNING) << "Failed to create child mapping of boot image methods: " << error_str;
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100968 return;
969 }
970 size_t offset = 0;
971 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
972 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
973 const ImageHeader& header = space->GetImageHeader();
974 const ImageSection& section = header.GetMethodsSection();
975 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
976 uint8_t* page_end =
977 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
978 if (page_end <= page_start) {
979 // Section doesn't contain one aligned entire page.
980 continue;
981 }
982 uint64_t capacity = page_end - page_start;
983 // Walk over methods in the boot image, and check for ones whose class is
984 // not initialized in the process, but are in the zygote process. For
985 // such methods, we need their entrypoints to be stubs that do the
986 // initialization check.
987 header.VisitPackedArtMethods([&](ArtMethod& method) NO_THREAD_SAFETY_ANALYSIS {
988 if (method.IsRuntimeMethod()) {
989 return;
990 }
991 if (method.GetDeclaringClassUnchecked()->IsVisiblyInitialized() ||
992 !method.IsStatic() ||
993 method.IsConstructor()) {
994 // Method does not need any stub.
995 return;
996 }
997
998 // We are going to mremap the child mapping into the image:
999 //
1000 // ImageSection ChildMappingMethods
1001 //
1002 // section start --> -----------
1003 // | |
1004 // | |
1005 // page_start --> | | <----- -----------
1006 // | | | |
1007 // | | | |
1008 // | | | |
1009 // | | | |
1010 // | | | |
1011 // | | | |
1012 // | | | |
1013 // page_end --> | | <----- -----------
1014 // | |
1015 // section end --> -----------
1016
1017
1018 uint8_t* pointer = reinterpret_cast<uint8_t*>(&method);
1019 if (pointer >= page_start && pointer < page_end) {
1020 // For all the methods in the mapping, put the entrypoint to the
1021 // resolution stub.
1022 ArtMethod* new_method = reinterpret_cast<ArtMethod*>(
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001023 child_mapping_methods.Begin() + offset + (pointer - page_start));
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001024 const void* code = new_method->GetEntryPointFromQuickCompiledCode();
1025 if (!class_linker->IsQuickGenericJniStub(code) &&
1026 !class_linker->IsQuickToInterpreterBridge(code) &&
1027 !class_linker->IsQuickResolutionStub(code)) {
1028 LOG(INFO) << "Putting back the resolution stub to an ArtMethod";
1029 new_method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
1030 }
1031 } else if (pointer < page_start && (pointer + sizeof(ArtMethod)) > page_start) {
1032 LOG(INFO) << "Copying parts of the contents of an ArtMethod spanning page_start";
1033 // If the method spans `page_start`, copy the contents of the child
1034 // into the pages we are going to remap into the image.
1035 //
1036 // section start --> -----------
1037 // | |
1038 // | |
1039 // page_start --> |/////////| -----------
1040 // |/////////| -> copy -> |/////////|
1041 // | | | |
1042 //
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001043 CopyIfDifferent(child_mapping_methods.Begin() + offset,
Nicolas Geoffrayff258062019-10-09 15:33:48 +01001044 page_start,
1045 pointer + sizeof(ArtMethod) - page_start);
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001046 } else if (pointer < page_end && (pointer + sizeof(ArtMethod)) > page_end) {
1047 LOG(INFO) << "Copying parts of the contents of an ArtMethod spanning page_end";
1048 // If the method spans `page_end`, copy the contents of the child
1049 // into the pages we are going to remap into the image.
1050 //
1051 // | | | |
1052 // |/////////| -> copy -> |/////////|
1053 // page_end --> |/////////| -----------
1054 // | |
1055 // section end --> -----------
1056 //
1057 size_t bytes_to_copy = (page_end - pointer);
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001058 CopyIfDifferent(child_mapping_methods.Begin() + offset + capacity - bytes_to_copy,
Nicolas Geoffrayff258062019-10-09 15:33:48 +01001059 page_end - bytes_to_copy,
1060 bytes_to_copy);
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001061 }
1062 }, space->Begin(), kRuntimePointerSize);
1063
1064 // Map the memory in the boot image range.
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001065 if (mremap(child_mapping_methods.Begin() + offset,
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001066 capacity,
1067 capacity,
1068 MREMAP_FIXED | MREMAP_MAYMOVE,
1069 page_start) == MAP_FAILED) {
1070 PLOG(WARNING) << "Fail to mremap boot image methods for " << space->GetImageFilename();
1071 }
1072 offset += capacity;
1073 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001074
1075 // The private mapping created for this process has been mremaped. We can
1076 // reset it.
1077 child_mapping_methods.Reset();
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001078}
1079
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001080void Jit::CreateThreadPool() {
1081 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
1082 // is not null when we instrument.
1083
1084 // We need peers as we may report the JIT thread, e.g., in the debugger.
1085 constexpr bool kJitPoolNeedsPeers = true;
1086 thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
1087
1088 thread_pool_->SetPthreadPriority(options_->GetThreadPoolPthreadPriority());
1089 Start();
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001090
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001091 Runtime* runtime = Runtime::Current();
David Srbecky3db3d372019-04-17 18:19:17 +01001092 if (runtime->IsZygote() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001093 // If we're not using the default boot image location, request a JIT task to
1094 // compile all methods in the boot image profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001095 thread_pool_->AddTask(Thread::Current(), new ZygoteTask());
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001096
1097 // And create mappings to share boot image methods memory from the zygote to
1098 // child processes.
1099
1100 // Compute the total capacity required for the boot image methods.
1101 uint64_t total_capacity = 0;
1102 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1103 const ImageHeader& header = space->GetImageHeader();
1104 const ImageSection& section = header.GetMethodsSection();
1105 // Mappings need to be at the page level.
1106 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
1107 uint8_t* page_end =
1108 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
1109 if (page_end > page_start) {
1110 total_capacity += (page_end - page_start);
1111 }
1112 }
1113
1114 // Create the child and zygote mappings to the boot image methods.
1115 if (total_capacity > 0) {
1116 // Start with '/boot' and end with '.art' to match the pattern recognized
1117 // by android_os_Debug.cpp for boot images.
1118 const char* name = "/boot-image-methods.art";
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001119 unique_fd mem_fd = unique_fd(art::memfd_create(name, /* flags= */ MFD_ALLOW_SEALING));
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001120 if (mem_fd.get() == -1) {
1121 PLOG(WARNING) << "Could not create boot image methods file descriptor";
1122 return;
1123 }
1124 if (ftruncate(mem_fd.get(), total_capacity) != 0) {
1125 PLOG(WARNING) << "Failed to truncate boot image methods file to " << total_capacity;
1126 return;
1127 }
1128 std::string error_str;
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001129
1130 // Create the shared mapping eagerly, as this prevents other processes
1131 // from adding the writable seal.
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001132 zygote_mapping_methods_ = MemMap::MapFile(
1133 total_capacity,
1134 PROT_READ | PROT_WRITE,
1135 MAP_SHARED,
1136 mem_fd,
1137 /* start= */ 0,
1138 /* low_4gb= */ false,
1139 "boot-image-methods",
1140 &error_str);
1141
1142 if (!zygote_mapping_methods_.IsValid()) {
1143 LOG(WARNING) << "Failed to create zygote mapping of boot image methods: " << error_str;
1144 return;
1145 }
1146 if (zygote_mapping_methods_.MadviseDontFork() != 0) {
1147 LOG(WARNING) << "Failed to madvise dont fork boot image methods";
1148 zygote_mapping_methods_ = MemMap();
1149 return;
1150 }
1151
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001152 if (IsSealFutureWriteSupported()) {
1153 // Seal now.
1154 if (fcntl(mem_fd,
1155 F_ADD_SEALS,
1156 F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL | F_SEAL_FUTURE_WRITE) == -1) {
1157 PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
1158 zygote_mapping_methods_ = MemMap();
1159 return;
1160 }
1161 } else {
1162 // Only seal the size. We will seal the write once we are donew writing
1163 // to the shared mapping.
1164 if (fcntl(mem_fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW) == -1) {
1165 PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
1166 zygote_mapping_methods_ = MemMap();
1167 return;
1168 }
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001169 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001170 fd_methods_ = unique_fd(mem_fd.release());
1171 fd_methods_size_ = total_capacity;
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001172 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001173 }
1174}
1175
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001176void Jit::RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Nicolas Geoffray741a0702019-06-10 11:18:11 +01001177 jobject class_loader) {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001178 if (dex_files.empty()) {
1179 return;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001180 }
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001181 Runtime* runtime = Runtime::Current();
1182 if (runtime->IsSystemServer() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
1183 thread_pool_->AddTask(Thread::Current(), new JitProfileTask(dex_files, class_loader));
1184 }
1185}
1186
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001187bool Jit::CompileMethodFromProfile(Thread* self,
1188 ClassLinker* class_linker,
1189 uint32_t method_idx,
1190 Handle<mirror::DexCache> dex_cache,
1191 Handle<mirror::ClassLoader> class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001192 bool add_to_queue,
1193 bool compile_after_boot) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001194 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
1195 method_idx, dex_cache, class_loader);
1196 if (method == nullptr) {
1197 self->ClearException();
1198 return false;
1199 }
1200 if (!method->IsCompilable() || !method->IsInvokable()) {
1201 return false;
1202 }
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001203 if (method->IsPreCompiled()) {
1204 // Already seen by another profile.
1205 return false;
1206 }
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001207 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1208 if (class_linker->IsQuickToInterpreterBridge(entry_point) ||
1209 class_linker->IsQuickGenericJniStub(entry_point) ||
1210 class_linker->IsQuickResolutionStub(entry_point)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001211 method->SetPreCompiled();
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001212 if (!add_to_queue) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001213 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ true);
1214 } else {
David Srbeckybfcea3d2019-08-05 15:44:00 +01001215 Task* task = new JitCompileTask(method, JitCompileTask::TaskKind::kPreCompile);
1216 if (compile_after_boot) {
1217 MutexLock mu(Thread::Current(), boot_completed_lock_);
1218 if (!boot_completed_) {
1219 tasks_after_boot_.push_back(task);
1220 return true;
1221 }
1222 DCHECK(tasks_after_boot_.empty());
1223 }
1224 thread_pool_->AddTask(self, task);
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001225 return true;
1226 }
1227 }
1228 return false;
1229}
1230
1231uint32_t Jit::CompileMethodsFromBootProfile(
1232 Thread* self,
1233 const std::vector<const DexFile*>& dex_files,
1234 const std::string& profile_file,
1235 Handle<mirror::ClassLoader> class_loader,
1236 bool add_to_queue) {
1237 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
1238
1239 if (profile.Fd() == -1) {
1240 PLOG(WARNING) << "No boot profile: " << profile_file;
1241 return 0u;
1242 }
1243
1244 ProfileBootInfo profile_info;
1245 if (!profile_info.Load(profile.Fd(), dex_files)) {
1246 LOG(ERROR) << "Could not load profile file: " << profile_file;
1247 return 0u;
1248 }
1249
1250 ScopedObjectAccess soa(self);
1251 VariableSizedHandleScope handles(self);
1252 std::vector<Handle<mirror::DexCache>> dex_caches;
1253 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1254 for (const DexFile* dex_file : profile_info.GetDexFiles()) {
1255 dex_caches.push_back(handles.NewHandle(class_linker->FindDexCache(self, *dex_file)));
1256 }
1257
1258 uint32_t added_to_queue = 0;
1259 for (const std::pair<uint32_t, uint32_t>& pair : profile_info.GetMethods()) {
1260 if (CompileMethodFromProfile(self,
1261 class_linker,
1262 pair.second,
1263 dex_caches[pair.first],
1264 class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001265 add_to_queue,
1266 /*compile_after_boot=*/false)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001267 ++added_to_queue;
1268 }
1269 }
1270 return added_to_queue;
1271}
1272
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001273uint32_t Jit::CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001274 Thread* self,
1275 const std::vector<const DexFile*>& dex_files,
1276 const std::string& profile_file,
1277 Handle<mirror::ClassLoader> class_loader,
1278 bool add_to_queue) {
1279
1280 if (profile_file.empty()) {
1281 LOG(WARNING) << "Expected a profile file in JIT zygote mode";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001282 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001283 }
1284
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001285 // We don't generate boot profiles on device, therefore we don't
1286 // need to lock the file.
1287 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001288
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001289 if (profile.Fd() == -1) {
1290 PLOG(WARNING) << "No profile: " << profile_file;
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001291 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001292 }
1293
1294 ProfileCompilationInfo profile_info;
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001295 if (!profile_info.Load(profile.Fd())) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001296 LOG(ERROR) << "Could not load profile file";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001297 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001298 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001299 ScopedObjectAccess soa(self);
1300 StackHandleScope<1> hs(self);
1301 MutableHandle<mirror::DexCache> dex_cache = hs.NewHandle<mirror::DexCache>(nullptr);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001302 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001303 uint32_t added_to_queue = 0u;
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001304 for (const DexFile* dex_file : dex_files) {
Martin Stjernholme58624f2019-09-20 15:53:40 +01001305 if (LocationIsOnArtModule(dex_file->GetLocation().c_str())) {
1306 // The ART module jars are already preopted.
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +01001307 continue;
1308 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +01001309 // To speed up class lookups, generate a type lookup table for
1310 // the dex file.
Nicolas Geoffrayc5e3a522019-04-30 09:47:55 +01001311 if (dex_file->GetOatDexFile() == nullptr) {
1312 TypeLookupTable type_lookup_table = TypeLookupTable::Create(*dex_file);
1313 type_lookup_tables_.push_back(
1314 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
1315 dex_file->SetOatDexFile(type_lookup_tables_.back().get());
1316 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +01001317
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001318 std::set<dex::TypeIndex> class_types;
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001319 std::set<uint16_t> all_methods;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001320 if (!profile_info.GetClassesAndMethods(*dex_file,
1321 &class_types,
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001322 &all_methods,
1323 &all_methods,
1324 &all_methods)) {
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +01001325 // This means the profile file did not reference the dex file, which is the case
1326 // if there's no classes and methods of that dex file in the profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001327 continue;
1328 }
1329 dex_cache.Assign(class_linker->FindDexCache(self, *dex_file));
1330 CHECK(dex_cache != nullptr) << "Could not find dex cache for " << dex_file->GetLocation();
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001331
1332 for (uint16_t method_idx : all_methods) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001333 if (CompileMethodFromProfile(self,
1334 class_linker,
1335 method_idx,
1336 dex_cache,
1337 class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001338 add_to_queue,
1339 /*compile_after_boot=*/true)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001340 ++added_to_queue;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001341 }
1342 }
1343 }
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +01001344
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001345 // Add a task to run when all compilation is done.
1346 JitDoneCompilingProfileTask* task = new JitDoneCompilingProfileTask(dex_files);
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +01001347 MutexLock mu(Thread::Current(), boot_completed_lock_);
1348 if (!boot_completed_) {
1349 tasks_after_boot_.push_back(task);
1350 } else {
1351 DCHECK(tasks_after_boot_.empty());
1352 thread_pool_->AddTask(self, task);
1353 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001354 return added_to_queue;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001355}
1356
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001357static bool IgnoreSamplesForMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray32384402019-07-17 20:06:44 +01001358 if (method->IsClassInitializer() || !method->IsCompilable() || method->IsPreCompiled()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001359 // We do not want to compile such methods.
1360 return true;
1361 }
1362 if (method->IsNative()) {
1363 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
Vladimir Markoc7aa87e2018-05-24 15:19:52 +01001364 if (klass == GetClassRoot<mirror::MethodHandle>() ||
1365 klass == GetClassRoot<mirror::VarHandle>()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001366 // MethodHandle and VarHandle invocation methods are required to throw an
1367 // UnsupportedOperationException if invoked reflectively. We achieve this by having native
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001368 // implementations that raise the exception. We need to disable JIT compilation of these JNI
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001369 // methods as it can lead to transitioning between JIT compiled JNI stubs and generic JNI
1370 // stubs. Since these stubs have different stack representations we can then crash in stack
1371 // walking (b/78151261).
1372 return true;
1373 }
1374 }
1375 return false;
1376}
1377
David Srbeckye3fc2d12018-11-30 13:41:14 +00001378bool Jit::MaybeCompileMethod(Thread* self,
1379 ArtMethod* method,
1380 uint32_t old_count,
1381 uint32_t new_count,
1382 bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001383 if (thread_pool_ == nullptr) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001384 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001385 }
David Srbecky1fc4d422019-07-23 16:55:19 +01001386 if (UNLIKELY(method->IsPreCompiled()) && !with_backedges /* don't check for OSR */) {
Vladimir Marko5115a4d2019-10-17 14:56:47 +01001387 if (!NeedsClinitCheckBeforeCall(method) ||
1388 method->GetDeclaringClass()->IsVisiblyInitialized()) {
Nicolas Geoffray5a0b6722019-09-24 15:09:40 +01001389 const void* entry_point = code_cache_->GetSavedEntryPointOfPreCompiledMethod(method);
1390 if (entry_point != nullptr) {
1391 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(method, entry_point);
1392 return true;
1393 }
David Srbecky1fc4d422019-07-23 16:55:19 +01001394 }
1395 }
Nicolas Geoffray5a0b6722019-09-24 15:09:40 +01001396
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001397 if (IgnoreSamplesForMethod(method)) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001398 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001399 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +01001400 if (HotMethodThreshold() == 0) {
David Srbeckyf4886df2017-12-11 16:06:29 +00001401 // Tests might request JIT on first use (compiled synchronously in the interpreter).
David Srbeckye3fc2d12018-11-30 13:41:14 +00001402 return false;
David Srbeckyf4886df2017-12-11 16:06:29 +00001403 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +01001404 DCHECK_GT(WarmMethodThreshold(), 0);
1405 DCHECK_GT(HotMethodThreshold(), WarmMethodThreshold());
1406 DCHECK_GT(OSRMethodThreshold(), HotMethodThreshold());
1407 DCHECK_GE(PriorityThreadWeight(), 1);
1408 DCHECK_LE(PriorityThreadWeight(), HotMethodThreshold());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001409
David Srbeckye3fc2d12018-11-30 13:41:14 +00001410 if (old_count < WarmMethodThreshold() && new_count >= WarmMethodThreshold()) {
1411 // Note: Native method have no "warm" state or profiling info.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001412 if (!method->IsNative() &&
1413 (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) &&
1414 code_cache_->CanAllocateProfilingInfo()) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001415 bool success = ProfilingInfo::Create(self, method, /* retry_allocation= */ false);
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001416 if (success) {
1417 VLOG(jit) << "Start profiling " << method->PrettyMethod();
1418 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001419
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001420 if (thread_pool_ == nullptr) {
1421 // Calling ProfilingInfo::Create might put us in a suspended state, which could
1422 // lead to the thread pool being deleted when we are shutting down.
David Srbeckye3fc2d12018-11-30 13:41:14 +00001423 return false;
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001424 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001425
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001426 if (!success) {
1427 // We failed allocating. Instead of doing the collection on the Java thread, we push
1428 // an allocation to a compiler thread, that will do the collection.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001429 thread_pool_->AddTask(
1430 self, new JitCompileTask(method, JitCompileTask::TaskKind::kAllocateProfile));
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001431 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001432 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001433 }
1434 if (UseJitCompilation()) {
David Srbeckyc45b5892019-04-24 10:32:04 +01001435 if (old_count == 0 &&
1436 method->IsNative() &&
1437 Runtime::Current()->IsUsingApexBootImageLocation()) {
1438 // jitzygote: Compile JNI stub on first use to avoid the expensive generic stub.
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001439 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ false);
David Srbeckyc45b5892019-04-24 10:32:04 +01001440 return true;
1441 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001442 if (old_count < HotMethodThreshold() && new_count >= HotMethodThreshold()) {
1443 if (!code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Calin Juravleffc87072016-04-20 14:22:09 +01001444 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001445 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompile));
Calin Juravleffc87072016-04-20 14:22:09 +01001446 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001447 }
1448 if (old_count < OSRMethodThreshold() && new_count >= OSRMethodThreshold()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001449 if (!with_backedges) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001450 return false;
Calin Juravleffc87072016-04-20 14:22:09 +01001451 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001452 DCHECK(!method->IsNative()); // No back edges reported for native methods.
David Srbeckye3fc2d12018-11-30 13:41:14 +00001453 if (!code_cache_->IsOsrCompiled(method)) {
Calin Juravleffc87072016-04-20 14:22:09 +01001454 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001455 thread_pool_->AddTask(
1456 self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompileOsr));
Calin Juravleffc87072016-04-20 14:22:09 +01001457 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001458 }
1459 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001460 return true;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001461}
1462
Alex Light59b950f2018-10-08 10:43:06 -07001463class ScopedSetRuntimeThread {
1464 public:
1465 explicit ScopedSetRuntimeThread(Thread* self)
1466 : self_(self), was_runtime_thread_(self_->IsRuntimeThread()) {
1467 self_->SetIsRuntimeThread(true);
1468 }
1469
1470 ~ScopedSetRuntimeThread() {
1471 self_->SetIsRuntimeThread(was_runtime_thread_);
1472 }
1473
1474 private:
1475 Thread* self_;
1476 bool was_runtime_thread_;
1477};
1478
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001479void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
Calin Juravleffc87072016-04-20 14:22:09 +01001480 Runtime* runtime = Runtime::Current();
Nicolas Geoffray5e33ccd2019-07-03 10:53:08 +01001481 if (UNLIKELY(runtime->UseJitCompilation() && JitAtFirstUse())) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001482 ArtMethod* np_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001483 if (np_method->IsCompilable()) {
Nicolas Geoffray5e33ccd2019-07-03 10:53:08 +01001484 if (!np_method->IsNative() && GetCodeCache()->CanAllocateProfilingInfo()) {
Nicolas Geoffray29bb8032019-06-06 10:32:24 +01001485 // The compiler requires a ProfilingInfo object for non-native methods.
1486 ProfilingInfo::Create(thread, np_method, /* retry_allocation= */ true);
1487 }
1488 // TODO(ngeoffray): For JIT at first use, use kPreCompile. Currently we don't due to
1489 // conflicts with jitzygote optimizations.
1490 JitCompileTask compile_task(method, JitCompileTask::TaskKind::kCompile);
Alex Light59b950f2018-10-08 10:43:06 -07001491 // Fake being in a runtime thread so that class-load behavior will be the same as normal jit.
1492 ScopedSetRuntimeThread ssrt(thread);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001493 compile_task.Run(thread);
1494 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001495 return;
1496 }
1497
Andreas Gampe542451c2016-07-26 09:02:02 -07001498 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001499 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
Alex Light2d441b12018-06-08 15:33:21 -07001500 // instead of interpreting the method. We don't update it for instrumentation as the entrypoint
1501 // must remain the instrumentation entrypoint.
1502 if ((profiling_info != nullptr) &&
1503 (profiling_info->GetSavedEntryPoint() != nullptr) &&
1504 (method->GetEntryPointFromQuickCompiledCode() != GetQuickInstrumentationEntryPoint())) {
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001505 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1506 method, profiling_info->GetSavedEntryPoint());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001507 } else {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001508 AddSamples(thread, method, 1, /* with_backedges= */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001509 }
1510}
1511
Mathieu Chartieref41db72016-10-25 15:08:01 -07001512void Jit::InvokeVirtualOrInterface(ObjPtr<mirror::Object> this_object,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001513 ArtMethod* caller,
1514 uint32_t dex_pc,
1515 ArtMethod* callee ATTRIBUTE_UNUSED) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001516 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001517 DCHECK(this_object != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001518 ProfilingInfo* info = caller->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001519 if (info != nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001520 info->AddInvokeInfo(dex_pc, this_object->GetClass());
1521 }
1522}
1523
1524void Jit::WaitForCompilationToFinish(Thread* self) {
1525 if (thread_pool_ != nullptr) {
1526 thread_pool_->Wait(self, false, false);
1527 }
1528}
1529
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001530void Jit::Stop() {
1531 Thread* self = Thread::Current();
1532 // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
1533 WaitForCompilationToFinish(self);
1534 GetThreadPool()->StopWorkers(self);
1535 WaitForCompilationToFinish(self);
1536}
1537
1538void Jit::Start() {
David Srbeckyd25eb2c2018-07-19 12:17:04 +00001539 GetThreadPool()->StartWorkers(Thread::Current());
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001540}
1541
Andreas Gampef149b3f2016-11-16 14:58:24 -08001542ScopedJitSuspend::ScopedJitSuspend() {
1543 jit::Jit* jit = Runtime::Current()->GetJit();
1544 was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
1545 if (was_on_) {
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001546 jit->Stop();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001547 }
1548}
1549
1550ScopedJitSuspend::~ScopedJitSuspend() {
1551 if (was_on_) {
1552 DCHECK(Runtime::Current()->GetJit() != nullptr);
1553 DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001554 Runtime::Current()->GetJit()->Start();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001555 }
1556}
1557
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001558static void* RunPollingThread(void* arg) {
1559 Jit* jit = reinterpret_cast<Jit*>(arg);
1560 do {
1561 sleep(10);
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001562 } while (!jit->GetCodeCache()->GetZygoteMap()->IsCompilationNotified());
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001563 jit->MapBootImageMethods();
1564 return nullptr;
1565}
1566
Nicolas Geoffray0d54cfb2019-05-03 09:13:52 +01001567void Jit::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffraye9455f62019-08-15 20:57:04 +01001568 // Clear the potential boot tasks inherited from the zygote.
1569 {
1570 MutexLock mu(Thread::Current(), boot_completed_lock_);
1571 tasks_after_boot_.clear();
1572 }
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001573
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001574 if (Runtime::Current()->IsUsingApexBootImageLocation() && fd_methods_ != -1) {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001575 // Create a thread that will poll the status of zygote compilation, and map
1576 // the private mapping of boot image methods.
1577 zygote_mapping_methods_.ResetInForkedProcess();
1578 pthread_t polling_thread;
1579 pthread_attr_t attr;
1580 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
1581 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED),
1582 "PTHREAD_CREATE_DETACHED");
1583 CHECK_PTHREAD_CALL(
1584 pthread_create,
1585 (&polling_thread, &attr, RunPollingThread, reinterpret_cast<void*>(this)),
1586 "Methods maps thread");
1587 }
1588
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001589 if (is_zygote || Runtime::Current()->IsSafeMode()) {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001590 // Delete the thread pool, we are not going to JIT.
1591 thread_pool_.reset(nullptr);
1592 return;
1593 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001594 // At this point, the compiler options have been adjusted to the particular configuration
1595 // of the forked child. Parse them again.
David Srbecky46b53532019-08-06 13:39:05 +01001596 jit_compiler_->ParseCompilerOptions();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001597
1598 // Adjust the status of code cache collection: the status from zygote was to not collect.
David Srbecky46b53532019-08-06 13:39:05 +01001599 code_cache_->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001600 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001601
Nicolas Geoffraya67daeb2019-08-12 10:41:25 +01001602 if (is_system_server && Runtime::Current()->IsUsingApexBootImageLocation()) {
1603 // Disable garbage collection: we don't want it to delete methods we're compiling
1604 // through boot and system server profiles.
1605 // TODO(ngeoffray): Fix this so we still collect deoptimized and unused code.
1606 code_cache_->SetGarbageCollectCode(false);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001607 }
Nicolas Geoffray371390f2019-09-27 09:57:38 +01001608
1609 // We do this here instead of PostZygoteFork, as NativeDebugInfoPostFork only
1610 // applies to a child.
1611 NativeDebugInfoPostFork();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001612}
1613
1614void Jit::PreZygoteFork() {
1615 if (thread_pool_ == nullptr) {
1616 return;
1617 }
1618 thread_pool_->DeleteThreads();
David Srbecky1550a662019-08-14 17:16:46 +01001619
1620 NativeDebugInfoPreFork();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001621}
1622
1623void Jit::PostZygoteFork() {
1624 if (thread_pool_ == nullptr) {
1625 return;
1626 }
1627 thread_pool_->CreateThreads();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001628}
1629
David Srbeckybfcea3d2019-08-05 15:44:00 +01001630void Jit::BootCompleted() {
1631 Thread* self = Thread::Current();
1632 std::deque<Task*> tasks;
1633 {
1634 MutexLock mu(self, boot_completed_lock_);
1635 tasks = std::move(tasks_after_boot_);
1636 boot_completed_ = true;
1637 }
1638 for (Task* task : tasks) {
1639 thread_pool_->AddTask(self, task);
1640 }
1641}
1642
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001643bool Jit::CanEncodeMethod(ArtMethod* method, bool is_for_shared_region) const {
1644 return !is_for_shared_region ||
1645 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(method->GetDeclaringClass());
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001646}
1647
1648bool Jit::CanEncodeClass(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001649 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(cls);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001650}
1651
1652bool Jit::CanEncodeString(ObjPtr<mirror::String> string, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001653 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001654}
1655
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001656bool Jit::CanAssumeInitialized(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
1657 if (!is_for_shared_region) {
1658 return cls->IsInitialized();
1659 } else {
1660 // Look up the class status in the oat file.
1661 const DexFile& dex_file = *cls->GetDexCache()->GetDexFile();
1662 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1663 // In case we run without an image there won't be a backing oat file.
1664 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
1665 return false;
1666 }
1667 uint16_t class_def_index = cls->GetDexClassDefIndex();
1668 return oat_dex_file->GetOatClass(class_def_index).GetStatus() >= ClassStatus::kInitialized;
1669 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001670}
1671
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001672} // namespace jit
1673} // namespace art