blob: b7fab90bb19806efa82fe9107f5cdebeb50e91de [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
Nicolas Geoffray8852e532019-10-30 09:43:35 +0000713 LOG(INFO) << "Successfully notified child processes on sharing boot image methods";
714
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000715 // Mark that compilation of boot classpath is done, and memory can now be
716 // shared. Other processes will pick up this information.
717 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedOk);
718
719 // The private mapping created for this process has been mremaped. We can
720 // reset it.
721 child_mapping_methods.Reset();
722}
723
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100724class JitCompileTask final : public Task {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100725 public:
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000726 enum class TaskKind {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100727 kAllocateProfile,
728 kCompile,
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000729 kCompileBaseline,
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000730 kCompileOsr,
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100731 kPreCompile,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100732 };
733
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000734 JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind), klass_(nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100735 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000736 // For a non-bootclasspath class, add a global ref to the class to prevent class unloading
737 // until compilation is done.
738 if (method->GetDeclaringClass()->GetClassLoader() != nullptr) {
739 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
740 CHECK(klass_ != nullptr);
741 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100742 }
743
744 ~JitCompileTask() {
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000745 if (klass_ != nullptr) {
746 ScopedObjectAccess soa(Thread::Current());
747 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
748 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100749 }
750
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100751 void Run(Thread* self) override {
Andreas Gampe4bd52342019-07-15 15:09:04 -0700752 {
753 ScopedObjectAccess soa(self);
754 switch (kind_) {
755 case TaskKind::kPreCompile:
756 case TaskKind::kCompile:
757 case TaskKind::kCompileBaseline:
758 case TaskKind::kCompileOsr: {
759 Runtime::Current()->GetJit()->CompileMethod(
760 method_,
761 self,
762 /* baseline= */ (kind_ == TaskKind::kCompileBaseline),
763 /* osr= */ (kind_ == TaskKind::kCompileOsr),
764 /* prejit= */ (kind_ == TaskKind::kPreCompile));
765 break;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000766 }
Andreas Gampe4bd52342019-07-15 15:09:04 -0700767 case TaskKind::kAllocateProfile: {
768 if (ProfilingInfo::Create(self, method_, /* retry_allocation= */ true)) {
769 VLOG(jit) << "Start profiling " << ArtMethod::PrettyMethod(method_);
770 }
771 break;
772 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100773 }
774 }
Calin Juravlea2638922016-04-29 16:44:11 +0100775 ProfileSaver::NotifyJitActivity();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100776 }
777
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100778 void Finalize() override {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100779 delete this;
780 }
781
782 private:
783 ArtMethod* const method_;
784 const TaskKind kind_;
785 jobject klass_;
786
787 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
788};
789
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100790static std::string GetProfileFile(const std::string& dex_location) {
791 // Hardcoded assumption where the profile file is.
792 // TODO(ngeoffray): this is brittle and we would need to change change if we
793 // wanted to do more eager JITting of methods in a profile. This is
794 // currently only for system server.
795 return dex_location + ".prof";
796}
797
798static std::string GetBootProfileFile(const std::string& profile) {
799 // The boot profile can be found next to the compilation profile, with a
800 // different extension.
801 return ReplaceFileExtension(profile, "bprof");
802}
803
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100804/**
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100805 * A JIT task to run after all profile compilation is done.
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100806 */
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100807class JitDoneCompilingProfileTask final : public SelfDeletingTask {
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100808 public:
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100809 explicit JitDoneCompilingProfileTask(const std::vector<const DexFile*>& dex_files)
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100810 : dex_files_(dex_files) {}
811
812 void Run(Thread* self ATTRIBUTE_UNUSED) override {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100813 // Madvise DONTNEED dex files now that we're done compiling methods.
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100814 for (const DexFile* dex_file : dex_files_) {
815 if (IsAddressKnownBackedByFileOrShared(dex_file->Begin())) {
816 int result = madvise(const_cast<uint8_t*>(AlignDown(dex_file->Begin(), kPageSize)),
817 RoundUp(dex_file->Size(), kPageSize),
818 MADV_DONTNEED);
819 if (result == -1) {
820 PLOG(WARNING) << "Madvise failed";
821 }
822 }
823 }
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100824
825 if (Runtime::Current()->IsZygote()) {
Nicolas Geoffray8852e532019-10-30 09:43:35 +0000826 // Record that we are done compiling the profile.
827 Runtime::Current()->GetJit()->GetCodeCache()->GetZygoteMap()->SetCompilationState(
828 ZygoteCompilationState::kDone);
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100829 }
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100830 }
831
832 private:
833 std::vector<const DexFile*> dex_files_;
834
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100835 DISALLOW_COPY_AND_ASSIGN(JitDoneCompilingProfileTask);
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100836};
837
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000838class ZygoteTask final : public Task {
839 public:
840 ZygoteTask() {}
841
842 void Run(Thread* self) override {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100843 Runtime* runtime = Runtime::Current();
844 std::string profile_file;
845 for (const std::string& option : runtime->GetImageCompilerOptions()) {
846 if (android::base::StartsWith(option, "--profile-file=")) {
847 profile_file = option.substr(strlen("--profile-file="));
848 break;
849 }
850 }
851
852 const std::vector<const DexFile*>& boot_class_path =
853 runtime->GetClassLinker()->GetBootClassPath();
854 ScopedNullHandle<mirror::ClassLoader> null_handle;
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100855 std::string boot_profile = GetBootProfileFile(profile_file);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100856 // We add to the queue for zygote so that we can fork processes in-between
857 // compilations.
Nicolas Geoffraya6f35832019-08-09 13:34:19 +0100858 uint32_t added_to_queue = 0;
859 if (Runtime::Current()->IsPrimaryZygote()) {
860 // We avoid doing compilation at boot for the secondary zygote, as apps
861 // forked from it are not critical for boot.
862 added_to_queue += runtime->GetJit()->CompileMethodsFromBootProfile(
863 self, boot_class_path, boot_profile, null_handle, /* add_to_queue= */ true);
864 }
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100865 added_to_queue += runtime->GetJit()->CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100866 self, boot_class_path, profile_file, null_handle, /* add_to_queue= */ true);
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100867
868 JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
869 code_cache->GetZygoteMap()->Initialize(added_to_queue);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100870 }
871
872 void Finalize() override {
873 delete this;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000874 }
875
876 private:
877 DISALLOW_COPY_AND_ASSIGN(ZygoteTask);
878};
879
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100880class JitProfileTask final : public Task {
881 public:
882 JitProfileTask(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100883 jobject class_loader) {
884 ScopedObjectAccess soa(Thread::Current());
885 StackHandleScope<1> hs(soa.Self());
886 Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
887 soa.Decode<mirror::ClassLoader>(class_loader)));
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100888 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
889 for (const auto& dex_file : dex_files) {
890 dex_files_.push_back(dex_file.get());
891 // Register the dex file so that we can guarantee it doesn't get deleted
892 // while reading it during the task.
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100893 class_linker->RegisterDexFile(*dex_file.get(), h_loader.Get());
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100894 }
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100895 // We also create our own global ref to use this class loader later.
896 class_loader_ = soa.Vm()->AddGlobalRef(soa.Self(), h_loader.Get());
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100897 }
898
899 void Run(Thread* self) override {
900 ScopedObjectAccess soa(self);
901 StackHandleScope<1> hs(self);
902 Handle<mirror::ClassLoader> loader = hs.NewHandle<mirror::ClassLoader>(
903 soa.Decode<mirror::ClassLoader>(class_loader_));
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100904
905 std::string profile = GetProfileFile(dex_files_[0]->GetLocation());
906 std::string boot_profile = GetBootProfileFile(profile);
907
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100908 Jit* jit = Runtime::Current()->GetJit();
909
910 jit->CompileMethodsFromBootProfile(
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100911 self,
912 dex_files_,
913 boot_profile,
914 loader,
915 /* add_to_queue= */ false);
916
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100917 jit->CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100918 self,
919 dex_files_,
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100920 profile,
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100921 loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +0100922 /* add_to_queue= */ true);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100923 }
924
925 void Finalize() override {
926 delete this;
927 }
928
Nicolas Geoffrayf5a07ae2019-06-20 14:59:07 +0100929 ~JitProfileTask() {
930 ScopedObjectAccess soa(Thread::Current());
931 soa.Vm()->DeleteGlobalRef(soa.Self(), class_loader_);
932 }
933
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100934 private:
935 std::vector<const DexFile*> dex_files_;
936 jobject class_loader_;
937
938 DISALLOW_COPY_AND_ASSIGN(JitProfileTask);
939};
940
Nicolas Geoffrayff258062019-10-09 15:33:48 +0100941static void CopyIfDifferent(void* s1, const void* s2, size_t n) {
942 if (memcmp(s1, s2, n) != 0) {
943 memcpy(s1, s2, n);
944 }
945}
946
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100947void Jit::MapBootImageMethods() {
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000948 CHECK_NE(fd_methods_.get(), -1);
949 if (!code_cache_->GetZygoteMap()->CanMapBootImageMethods()) {
950 LOG(WARNING) << "Not mapping boot image methods due to error from zygote";
951 return;
952 }
953
954 std::string error_str;
955 MemMap child_mapping_methods = MemMap::MapFile(
956 fd_methods_size_,
957 PROT_READ | PROT_WRITE,
958 MAP_PRIVATE,
959 fd_methods_,
960 /* start= */ 0,
961 /* low_4gb= */ false,
962 "boot-image-methods",
963 &error_str);
964
965 // We don't need the fd anymore.
966 fd_methods_.reset();
967
968 if (!child_mapping_methods.IsValid()) {
969 LOG(WARNING) << "Failed to create child mapping of boot image methods: " << error_str;
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100970 return;
971 }
972 size_t offset = 0;
973 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
974 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
975 const ImageHeader& header = space->GetImageHeader();
976 const ImageSection& section = header.GetMethodsSection();
977 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
978 uint8_t* page_end =
979 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
980 if (page_end <= page_start) {
981 // Section doesn't contain one aligned entire page.
982 continue;
983 }
984 uint64_t capacity = page_end - page_start;
985 // Walk over methods in the boot image, and check for ones whose class is
986 // not initialized in the process, but are in the zygote process. For
987 // such methods, we need their entrypoints to be stubs that do the
988 // initialization check.
989 header.VisitPackedArtMethods([&](ArtMethod& method) NO_THREAD_SAFETY_ANALYSIS {
990 if (method.IsRuntimeMethod()) {
991 return;
992 }
993 if (method.GetDeclaringClassUnchecked()->IsVisiblyInitialized() ||
994 !method.IsStatic() ||
995 method.IsConstructor()) {
996 // Method does not need any stub.
997 return;
998 }
999
1000 // We are going to mremap the child mapping into the image:
1001 //
1002 // ImageSection ChildMappingMethods
1003 //
1004 // section start --> -----------
1005 // | |
1006 // | |
1007 // page_start --> | | <----- -----------
1008 // | | | |
1009 // | | | |
1010 // | | | |
1011 // | | | |
1012 // | | | |
1013 // | | | |
1014 // | | | |
1015 // page_end --> | | <----- -----------
1016 // | |
1017 // section end --> -----------
1018
1019
1020 uint8_t* pointer = reinterpret_cast<uint8_t*>(&method);
1021 if (pointer >= page_start && pointer < page_end) {
1022 // For all the methods in the mapping, put the entrypoint to the
1023 // resolution stub.
1024 ArtMethod* new_method = reinterpret_cast<ArtMethod*>(
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001025 child_mapping_methods.Begin() + offset + (pointer - page_start));
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001026 const void* code = new_method->GetEntryPointFromQuickCompiledCode();
1027 if (!class_linker->IsQuickGenericJniStub(code) &&
1028 !class_linker->IsQuickToInterpreterBridge(code) &&
1029 !class_linker->IsQuickResolutionStub(code)) {
1030 LOG(INFO) << "Putting back the resolution stub to an ArtMethod";
1031 new_method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
1032 }
1033 } else if (pointer < page_start && (pointer + sizeof(ArtMethod)) > page_start) {
1034 LOG(INFO) << "Copying parts of the contents of an ArtMethod spanning page_start";
1035 // If the method spans `page_start`, copy the contents of the child
1036 // into the pages we are going to remap into the image.
1037 //
1038 // section start --> -----------
1039 // | |
1040 // | |
1041 // page_start --> |/////////| -----------
1042 // |/////////| -> copy -> |/////////|
1043 // | | | |
1044 //
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001045 CopyIfDifferent(child_mapping_methods.Begin() + offset,
Nicolas Geoffrayff258062019-10-09 15:33:48 +01001046 page_start,
1047 pointer + sizeof(ArtMethod) - page_start);
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001048 } else if (pointer < page_end && (pointer + sizeof(ArtMethod)) > page_end) {
1049 LOG(INFO) << "Copying parts of the contents of an ArtMethod spanning page_end";
1050 // If the method spans `page_end`, copy the contents of the child
1051 // into the pages we are going to remap into the image.
1052 //
1053 // | | | |
1054 // |/////////| -> copy -> |/////////|
1055 // page_end --> |/////////| -----------
1056 // | |
1057 // section end --> -----------
1058 //
1059 size_t bytes_to_copy = (page_end - pointer);
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001060 CopyIfDifferent(child_mapping_methods.Begin() + offset + capacity - bytes_to_copy,
Nicolas Geoffrayff258062019-10-09 15:33:48 +01001061 page_end - bytes_to_copy,
1062 bytes_to_copy);
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001063 }
1064 }, space->Begin(), kRuntimePointerSize);
1065
1066 // Map the memory in the boot image range.
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001067 if (mremap(child_mapping_methods.Begin() + offset,
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001068 capacity,
1069 capacity,
1070 MREMAP_FIXED | MREMAP_MAYMOVE,
1071 page_start) == MAP_FAILED) {
1072 PLOG(WARNING) << "Fail to mremap boot image methods for " << space->GetImageFilename();
1073 }
1074 offset += capacity;
1075 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001076
1077 // The private mapping created for this process has been mremaped. We can
1078 // reset it.
1079 child_mapping_methods.Reset();
Nicolas Geoffray8e23d382019-10-30 13:53:01 +00001080 LOG(INFO) << "Successfully mapped boot image methods";
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001081}
1082
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001083void Jit::CreateThreadPool() {
1084 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
1085 // is not null when we instrument.
1086
1087 // We need peers as we may report the JIT thread, e.g., in the debugger.
1088 constexpr bool kJitPoolNeedsPeers = true;
1089 thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
1090
1091 thread_pool_->SetPthreadPriority(options_->GetThreadPoolPthreadPriority());
1092 Start();
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001093
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001094 Runtime* runtime = Runtime::Current();
David Srbecky3db3d372019-04-17 18:19:17 +01001095 if (runtime->IsZygote() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001096 // If we're not using the default boot image location, request a JIT task to
1097 // compile all methods in the boot image profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001098 thread_pool_->AddTask(Thread::Current(), new ZygoteTask());
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001099
1100 // And create mappings to share boot image methods memory from the zygote to
1101 // child processes.
1102
1103 // Compute the total capacity required for the boot image methods.
1104 uint64_t total_capacity = 0;
1105 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1106 const ImageHeader& header = space->GetImageHeader();
1107 const ImageSection& section = header.GetMethodsSection();
1108 // Mappings need to be at the page level.
1109 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
1110 uint8_t* page_end =
1111 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
1112 if (page_end > page_start) {
1113 total_capacity += (page_end - page_start);
1114 }
1115 }
1116
1117 // Create the child and zygote mappings to the boot image methods.
1118 if (total_capacity > 0) {
1119 // Start with '/boot' and end with '.art' to match the pattern recognized
1120 // by android_os_Debug.cpp for boot images.
1121 const char* name = "/boot-image-methods.art";
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001122 unique_fd mem_fd = unique_fd(art::memfd_create(name, /* flags= */ MFD_ALLOW_SEALING));
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001123 if (mem_fd.get() == -1) {
1124 PLOG(WARNING) << "Could not create boot image methods file descriptor";
1125 return;
1126 }
1127 if (ftruncate(mem_fd.get(), total_capacity) != 0) {
1128 PLOG(WARNING) << "Failed to truncate boot image methods file to " << total_capacity;
1129 return;
1130 }
1131 std::string error_str;
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001132
1133 // Create the shared mapping eagerly, as this prevents other processes
1134 // from adding the writable seal.
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001135 zygote_mapping_methods_ = MemMap::MapFile(
1136 total_capacity,
1137 PROT_READ | PROT_WRITE,
1138 MAP_SHARED,
1139 mem_fd,
1140 /* start= */ 0,
1141 /* low_4gb= */ false,
1142 "boot-image-methods",
1143 &error_str);
1144
1145 if (!zygote_mapping_methods_.IsValid()) {
1146 LOG(WARNING) << "Failed to create zygote mapping of boot image methods: " << error_str;
1147 return;
1148 }
1149 if (zygote_mapping_methods_.MadviseDontFork() != 0) {
1150 LOG(WARNING) << "Failed to madvise dont fork boot image methods";
1151 zygote_mapping_methods_ = MemMap();
1152 return;
1153 }
1154
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001155 if (IsSealFutureWriteSupported()) {
1156 // Seal now.
1157 if (fcntl(mem_fd,
1158 F_ADD_SEALS,
1159 F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL | F_SEAL_FUTURE_WRITE) == -1) {
1160 PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
1161 zygote_mapping_methods_ = MemMap();
1162 return;
1163 }
1164 } else {
1165 // Only seal the size. We will seal the write once we are donew writing
1166 // to the shared mapping.
1167 if (fcntl(mem_fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW) == -1) {
1168 PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
1169 zygote_mapping_methods_ = MemMap();
1170 return;
1171 }
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001172 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001173 fd_methods_ = unique_fd(mem_fd.release());
1174 fd_methods_size_ = total_capacity;
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001175 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001176 }
1177}
1178
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001179void Jit::RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Nicolas Geoffray741a0702019-06-10 11:18:11 +01001180 jobject class_loader) {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001181 if (dex_files.empty()) {
1182 return;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001183 }
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001184 Runtime* runtime = Runtime::Current();
1185 if (runtime->IsSystemServer() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
1186 thread_pool_->AddTask(Thread::Current(), new JitProfileTask(dex_files, class_loader));
1187 }
1188}
1189
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001190bool Jit::CompileMethodFromProfile(Thread* self,
1191 ClassLinker* class_linker,
1192 uint32_t method_idx,
1193 Handle<mirror::DexCache> dex_cache,
1194 Handle<mirror::ClassLoader> class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001195 bool add_to_queue,
1196 bool compile_after_boot) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001197 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
1198 method_idx, dex_cache, class_loader);
1199 if (method == nullptr) {
1200 self->ClearException();
1201 return false;
1202 }
1203 if (!method->IsCompilable() || !method->IsInvokable()) {
1204 return false;
1205 }
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001206 if (method->IsPreCompiled()) {
1207 // Already seen by another profile.
1208 return false;
1209 }
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001210 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1211 if (class_linker->IsQuickToInterpreterBridge(entry_point) ||
1212 class_linker->IsQuickGenericJniStub(entry_point) ||
1213 class_linker->IsQuickResolutionStub(entry_point)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001214 method->SetPreCompiled();
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001215 if (!add_to_queue) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001216 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ true);
1217 } else {
David Srbeckybfcea3d2019-08-05 15:44:00 +01001218 Task* task = new JitCompileTask(method, JitCompileTask::TaskKind::kPreCompile);
1219 if (compile_after_boot) {
1220 MutexLock mu(Thread::Current(), boot_completed_lock_);
1221 if (!boot_completed_) {
1222 tasks_after_boot_.push_back(task);
1223 return true;
1224 }
1225 DCHECK(tasks_after_boot_.empty());
1226 }
1227 thread_pool_->AddTask(self, task);
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001228 return true;
1229 }
1230 }
1231 return false;
1232}
1233
1234uint32_t Jit::CompileMethodsFromBootProfile(
1235 Thread* self,
1236 const std::vector<const DexFile*>& dex_files,
1237 const std::string& profile_file,
1238 Handle<mirror::ClassLoader> class_loader,
1239 bool add_to_queue) {
1240 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
1241
1242 if (profile.Fd() == -1) {
1243 PLOG(WARNING) << "No boot profile: " << profile_file;
1244 return 0u;
1245 }
1246
1247 ProfileBootInfo profile_info;
1248 if (!profile_info.Load(profile.Fd(), dex_files)) {
1249 LOG(ERROR) << "Could not load profile file: " << profile_file;
1250 return 0u;
1251 }
1252
1253 ScopedObjectAccess soa(self);
1254 VariableSizedHandleScope handles(self);
1255 std::vector<Handle<mirror::DexCache>> dex_caches;
1256 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1257 for (const DexFile* dex_file : profile_info.GetDexFiles()) {
1258 dex_caches.push_back(handles.NewHandle(class_linker->FindDexCache(self, *dex_file)));
1259 }
1260
1261 uint32_t added_to_queue = 0;
1262 for (const std::pair<uint32_t, uint32_t>& pair : profile_info.GetMethods()) {
1263 if (CompileMethodFromProfile(self,
1264 class_linker,
1265 pair.second,
1266 dex_caches[pair.first],
1267 class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001268 add_to_queue,
1269 /*compile_after_boot=*/false)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001270 ++added_to_queue;
1271 }
1272 }
1273 return added_to_queue;
1274}
1275
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001276uint32_t Jit::CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001277 Thread* self,
1278 const std::vector<const DexFile*>& dex_files,
1279 const std::string& profile_file,
1280 Handle<mirror::ClassLoader> class_loader,
1281 bool add_to_queue) {
1282
1283 if (profile_file.empty()) {
1284 LOG(WARNING) << "Expected a profile file in JIT zygote mode";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001285 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001286 }
1287
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001288 // We don't generate boot profiles on device, therefore we don't
1289 // need to lock the file.
1290 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001291
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001292 if (profile.Fd() == -1) {
1293 PLOG(WARNING) << "No profile: " << profile_file;
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001294 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001295 }
1296
1297 ProfileCompilationInfo profile_info;
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001298 if (!profile_info.Load(profile.Fd())) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001299 LOG(ERROR) << "Could not load profile file";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001300 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001301 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001302 ScopedObjectAccess soa(self);
1303 StackHandleScope<1> hs(self);
1304 MutableHandle<mirror::DexCache> dex_cache = hs.NewHandle<mirror::DexCache>(nullptr);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001305 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001306 uint32_t added_to_queue = 0u;
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001307 for (const DexFile* dex_file : dex_files) {
Martin Stjernholme58624f2019-09-20 15:53:40 +01001308 if (LocationIsOnArtModule(dex_file->GetLocation().c_str())) {
1309 // The ART module jars are already preopted.
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +01001310 continue;
1311 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +01001312 // To speed up class lookups, generate a type lookup table for
1313 // the dex file.
Nicolas Geoffrayc5e3a522019-04-30 09:47:55 +01001314 if (dex_file->GetOatDexFile() == nullptr) {
1315 TypeLookupTable type_lookup_table = TypeLookupTable::Create(*dex_file);
1316 type_lookup_tables_.push_back(
1317 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
1318 dex_file->SetOatDexFile(type_lookup_tables_.back().get());
1319 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +01001320
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001321 std::set<dex::TypeIndex> class_types;
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001322 std::set<uint16_t> all_methods;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001323 if (!profile_info.GetClassesAndMethods(*dex_file,
1324 &class_types,
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001325 &all_methods,
1326 &all_methods,
1327 &all_methods)) {
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +01001328 // This means the profile file did not reference the dex file, which is the case
1329 // if there's no classes and methods of that dex file in the profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001330 continue;
1331 }
1332 dex_cache.Assign(class_linker->FindDexCache(self, *dex_file));
1333 CHECK(dex_cache != nullptr) << "Could not find dex cache for " << dex_file->GetLocation();
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001334
1335 for (uint16_t method_idx : all_methods) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001336 if (CompileMethodFromProfile(self,
1337 class_linker,
1338 method_idx,
1339 dex_cache,
1340 class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001341 add_to_queue,
1342 /*compile_after_boot=*/true)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001343 ++added_to_queue;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001344 }
1345 }
1346 }
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +01001347
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001348 // Add a task to run when all compilation is done.
1349 JitDoneCompilingProfileTask* task = new JitDoneCompilingProfileTask(dex_files);
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +01001350 MutexLock mu(Thread::Current(), boot_completed_lock_);
1351 if (!boot_completed_) {
1352 tasks_after_boot_.push_back(task);
1353 } else {
1354 DCHECK(tasks_after_boot_.empty());
1355 thread_pool_->AddTask(self, task);
1356 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001357 return added_to_queue;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001358}
1359
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001360static bool IgnoreSamplesForMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray32384402019-07-17 20:06:44 +01001361 if (method->IsClassInitializer() || !method->IsCompilable() || method->IsPreCompiled()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001362 // We do not want to compile such methods.
1363 return true;
1364 }
1365 if (method->IsNative()) {
1366 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
Vladimir Markoc7aa87e2018-05-24 15:19:52 +01001367 if (klass == GetClassRoot<mirror::MethodHandle>() ||
1368 klass == GetClassRoot<mirror::VarHandle>()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001369 // MethodHandle and VarHandle invocation methods are required to throw an
1370 // UnsupportedOperationException if invoked reflectively. We achieve this by having native
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001371 // implementations that raise the exception. We need to disable JIT compilation of these JNI
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001372 // methods as it can lead to transitioning between JIT compiled JNI stubs and generic JNI
1373 // stubs. Since these stubs have different stack representations we can then crash in stack
1374 // walking (b/78151261).
1375 return true;
1376 }
1377 }
1378 return false;
1379}
1380
David Srbeckye3fc2d12018-11-30 13:41:14 +00001381bool Jit::MaybeCompileMethod(Thread* self,
1382 ArtMethod* method,
1383 uint32_t old_count,
1384 uint32_t new_count,
1385 bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001386 if (thread_pool_ == nullptr) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001387 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001388 }
David Srbecky1fc4d422019-07-23 16:55:19 +01001389 if (UNLIKELY(method->IsPreCompiled()) && !with_backedges /* don't check for OSR */) {
Vladimir Marko5115a4d2019-10-17 14:56:47 +01001390 if (!NeedsClinitCheckBeforeCall(method) ||
1391 method->GetDeclaringClass()->IsVisiblyInitialized()) {
Nicolas Geoffray5a0b6722019-09-24 15:09:40 +01001392 const void* entry_point = code_cache_->GetSavedEntryPointOfPreCompiledMethod(method);
1393 if (entry_point != nullptr) {
1394 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(method, entry_point);
1395 return true;
1396 }
David Srbecky1fc4d422019-07-23 16:55:19 +01001397 }
1398 }
Nicolas Geoffray5a0b6722019-09-24 15:09:40 +01001399
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001400 if (IgnoreSamplesForMethod(method)) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001401 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001402 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +01001403 if (HotMethodThreshold() == 0) {
David Srbeckyf4886df2017-12-11 16:06:29 +00001404 // Tests might request JIT on first use (compiled synchronously in the interpreter).
David Srbeckye3fc2d12018-11-30 13:41:14 +00001405 return false;
David Srbeckyf4886df2017-12-11 16:06:29 +00001406 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +01001407 DCHECK_GT(WarmMethodThreshold(), 0);
1408 DCHECK_GT(HotMethodThreshold(), WarmMethodThreshold());
1409 DCHECK_GT(OSRMethodThreshold(), HotMethodThreshold());
1410 DCHECK_GE(PriorityThreadWeight(), 1);
1411 DCHECK_LE(PriorityThreadWeight(), HotMethodThreshold());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001412
David Srbeckye3fc2d12018-11-30 13:41:14 +00001413 if (old_count < WarmMethodThreshold() && new_count >= WarmMethodThreshold()) {
1414 // Note: Native method have no "warm" state or profiling info.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001415 if (!method->IsNative() &&
1416 (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) &&
1417 code_cache_->CanAllocateProfilingInfo()) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001418 bool success = ProfilingInfo::Create(self, method, /* retry_allocation= */ false);
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001419 if (success) {
1420 VLOG(jit) << "Start profiling " << method->PrettyMethod();
1421 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001422
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001423 if (thread_pool_ == nullptr) {
1424 // Calling ProfilingInfo::Create might put us in a suspended state, which could
1425 // lead to the thread pool being deleted when we are shutting down.
David Srbeckye3fc2d12018-11-30 13:41:14 +00001426 return false;
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001427 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001428
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001429 if (!success) {
1430 // We failed allocating. Instead of doing the collection on the Java thread, we push
1431 // an allocation to a compiler thread, that will do the collection.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001432 thread_pool_->AddTask(
1433 self, new JitCompileTask(method, JitCompileTask::TaskKind::kAllocateProfile));
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001434 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001435 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001436 }
1437 if (UseJitCompilation()) {
David Srbeckyc45b5892019-04-24 10:32:04 +01001438 if (old_count == 0 &&
1439 method->IsNative() &&
1440 Runtime::Current()->IsUsingApexBootImageLocation()) {
1441 // jitzygote: Compile JNI stub on first use to avoid the expensive generic stub.
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001442 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ false);
David Srbeckyc45b5892019-04-24 10:32:04 +01001443 return true;
1444 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001445 if (old_count < HotMethodThreshold() && new_count >= HotMethodThreshold()) {
1446 if (!code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Calin Juravleffc87072016-04-20 14:22:09 +01001447 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001448 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompile));
Calin Juravleffc87072016-04-20 14:22:09 +01001449 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001450 }
1451 if (old_count < OSRMethodThreshold() && new_count >= OSRMethodThreshold()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001452 if (!with_backedges) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001453 return false;
Calin Juravleffc87072016-04-20 14:22:09 +01001454 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001455 DCHECK(!method->IsNative()); // No back edges reported for native methods.
David Srbeckye3fc2d12018-11-30 13:41:14 +00001456 if (!code_cache_->IsOsrCompiled(method)) {
Calin Juravleffc87072016-04-20 14:22:09 +01001457 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001458 thread_pool_->AddTask(
1459 self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompileOsr));
Calin Juravleffc87072016-04-20 14:22:09 +01001460 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001461 }
1462 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001463 return true;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001464}
1465
Alex Light59b950f2018-10-08 10:43:06 -07001466class ScopedSetRuntimeThread {
1467 public:
1468 explicit ScopedSetRuntimeThread(Thread* self)
1469 : self_(self), was_runtime_thread_(self_->IsRuntimeThread()) {
1470 self_->SetIsRuntimeThread(true);
1471 }
1472
1473 ~ScopedSetRuntimeThread() {
1474 self_->SetIsRuntimeThread(was_runtime_thread_);
1475 }
1476
1477 private:
1478 Thread* self_;
1479 bool was_runtime_thread_;
1480};
1481
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001482void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
Calin Juravleffc87072016-04-20 14:22:09 +01001483 Runtime* runtime = Runtime::Current();
Nicolas Geoffray5e33ccd2019-07-03 10:53:08 +01001484 if (UNLIKELY(runtime->UseJitCompilation() && JitAtFirstUse())) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001485 ArtMethod* np_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001486 if (np_method->IsCompilable()) {
Nicolas Geoffray5e33ccd2019-07-03 10:53:08 +01001487 if (!np_method->IsNative() && GetCodeCache()->CanAllocateProfilingInfo()) {
Nicolas Geoffray29bb8032019-06-06 10:32:24 +01001488 // The compiler requires a ProfilingInfo object for non-native methods.
1489 ProfilingInfo::Create(thread, np_method, /* retry_allocation= */ true);
1490 }
1491 // TODO(ngeoffray): For JIT at first use, use kPreCompile. Currently we don't due to
1492 // conflicts with jitzygote optimizations.
1493 JitCompileTask compile_task(method, JitCompileTask::TaskKind::kCompile);
Alex Light59b950f2018-10-08 10:43:06 -07001494 // Fake being in a runtime thread so that class-load behavior will be the same as normal jit.
1495 ScopedSetRuntimeThread ssrt(thread);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001496 compile_task.Run(thread);
1497 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001498 return;
1499 }
1500
Andreas Gampe542451c2016-07-26 09:02:02 -07001501 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001502 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
Alex Light2d441b12018-06-08 15:33:21 -07001503 // instead of interpreting the method. We don't update it for instrumentation as the entrypoint
1504 // must remain the instrumentation entrypoint.
1505 if ((profiling_info != nullptr) &&
1506 (profiling_info->GetSavedEntryPoint() != nullptr) &&
1507 (method->GetEntryPointFromQuickCompiledCode() != GetQuickInstrumentationEntryPoint())) {
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001508 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1509 method, profiling_info->GetSavedEntryPoint());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001510 } else {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001511 AddSamples(thread, method, 1, /* with_backedges= */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001512 }
1513}
1514
Mathieu Chartieref41db72016-10-25 15:08:01 -07001515void Jit::InvokeVirtualOrInterface(ObjPtr<mirror::Object> this_object,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001516 ArtMethod* caller,
1517 uint32_t dex_pc,
1518 ArtMethod* callee ATTRIBUTE_UNUSED) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001519 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001520 DCHECK(this_object != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001521 ProfilingInfo* info = caller->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001522 if (info != nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001523 info->AddInvokeInfo(dex_pc, this_object->GetClass());
1524 }
1525}
1526
1527void Jit::WaitForCompilationToFinish(Thread* self) {
1528 if (thread_pool_ != nullptr) {
1529 thread_pool_->Wait(self, false, false);
1530 }
1531}
1532
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001533void Jit::Stop() {
1534 Thread* self = Thread::Current();
1535 // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
1536 WaitForCompilationToFinish(self);
1537 GetThreadPool()->StopWorkers(self);
1538 WaitForCompilationToFinish(self);
1539}
1540
1541void Jit::Start() {
David Srbeckyd25eb2c2018-07-19 12:17:04 +00001542 GetThreadPool()->StartWorkers(Thread::Current());
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001543}
1544
Andreas Gampef149b3f2016-11-16 14:58:24 -08001545ScopedJitSuspend::ScopedJitSuspend() {
1546 jit::Jit* jit = Runtime::Current()->GetJit();
1547 was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
1548 if (was_on_) {
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001549 jit->Stop();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001550 }
1551}
1552
1553ScopedJitSuspend::~ScopedJitSuspend() {
1554 if (was_on_) {
1555 DCHECK(Runtime::Current()->GetJit() != nullptr);
1556 DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001557 Runtime::Current()->GetJit()->Start();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001558 }
1559}
1560
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001561static void* RunPollingThread(void* arg) {
1562 Jit* jit = reinterpret_cast<Jit*>(arg);
1563 do {
1564 sleep(10);
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001565 } while (!jit->GetCodeCache()->GetZygoteMap()->IsCompilationNotified());
Nicolas Geoffray8e23d382019-10-30 13:53:01 +00001566
1567 // We will suspend other threads: we can only do that if we're attached to the
1568 // runtime.
1569 Runtime* runtime = Runtime::Current();
1570 bool thread_attached = runtime->AttachCurrentThread(
1571 "BootImagePollingThread",
1572 /* as_daemon= */ true,
1573 /* thread_group= */ nullptr,
1574 /* create_peer= */ false);
1575 CHECK(thread_attached);
1576
1577 {
1578 // Prevent other threads from running while we are remapping the boot image
1579 // ArtMethod's. Native threads might still be running, but they cannot
1580 // change the contents of ArtMethod's.
1581 ScopedSuspendAll ssa(__FUNCTION__);
1582 runtime->GetJit()->MapBootImageMethods();
1583 }
1584
1585 Runtime::Current()->DetachCurrentThread();
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001586 return nullptr;
1587}
1588
Nicolas Geoffray0d54cfb2019-05-03 09:13:52 +01001589void Jit::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffraye9455f62019-08-15 20:57:04 +01001590 // Clear the potential boot tasks inherited from the zygote.
1591 {
1592 MutexLock mu(Thread::Current(), boot_completed_lock_);
1593 tasks_after_boot_.clear();
1594 }
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001595
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001596 if (Runtime::Current()->IsUsingApexBootImageLocation() && fd_methods_ != -1) {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001597 // Create a thread that will poll the status of zygote compilation, and map
1598 // the private mapping of boot image methods.
1599 zygote_mapping_methods_.ResetInForkedProcess();
1600 pthread_t polling_thread;
1601 pthread_attr_t attr;
1602 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
1603 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED),
1604 "PTHREAD_CREATE_DETACHED");
1605 CHECK_PTHREAD_CALL(
1606 pthread_create,
1607 (&polling_thread, &attr, RunPollingThread, reinterpret_cast<void*>(this)),
1608 "Methods maps thread");
1609 }
1610
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001611 if (is_zygote || Runtime::Current()->IsSafeMode()) {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001612 // Delete the thread pool, we are not going to JIT.
1613 thread_pool_.reset(nullptr);
1614 return;
1615 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001616 // At this point, the compiler options have been adjusted to the particular configuration
1617 // of the forked child. Parse them again.
David Srbecky46b53532019-08-06 13:39:05 +01001618 jit_compiler_->ParseCompilerOptions();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001619
1620 // Adjust the status of code cache collection: the status from zygote was to not collect.
David Srbecky46b53532019-08-06 13:39:05 +01001621 code_cache_->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001622 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001623
Nicolas Geoffraya67daeb2019-08-12 10:41:25 +01001624 if (is_system_server && Runtime::Current()->IsUsingApexBootImageLocation()) {
1625 // Disable garbage collection: we don't want it to delete methods we're compiling
1626 // through boot and system server profiles.
1627 // TODO(ngeoffray): Fix this so we still collect deoptimized and unused code.
1628 code_cache_->SetGarbageCollectCode(false);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001629 }
Nicolas Geoffray371390f2019-09-27 09:57:38 +01001630
1631 // We do this here instead of PostZygoteFork, as NativeDebugInfoPostFork only
1632 // applies to a child.
1633 NativeDebugInfoPostFork();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001634}
1635
1636void Jit::PreZygoteFork() {
1637 if (thread_pool_ == nullptr) {
1638 return;
1639 }
1640 thread_pool_->DeleteThreads();
David Srbecky1550a662019-08-14 17:16:46 +01001641
1642 NativeDebugInfoPreFork();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001643}
1644
1645void Jit::PostZygoteFork() {
1646 if (thread_pool_ == nullptr) {
1647 return;
1648 }
Nicolas Geoffray8852e532019-10-30 09:43:35 +00001649 if (Runtime::Current()->IsZygote() &&
1650 code_cache_->GetZygoteMap()->IsCompilationDoneButNotNotified()) {
1651 // Copy the boot image methods data to the mappings we created to share
1652 // with the children. We do this here as we are the only thread running and
1653 // we don't risk other threads concurrently updating the ArtMethod's.
1654 CHECK_EQ(GetTaskCount(), 1);
1655 NotifyZygoteCompilationDone();
1656 CHECK(code_cache_->GetZygoteMap()->IsCompilationNotified());
1657 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001658 thread_pool_->CreateThreads();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001659}
1660
David Srbeckybfcea3d2019-08-05 15:44:00 +01001661void Jit::BootCompleted() {
1662 Thread* self = Thread::Current();
1663 std::deque<Task*> tasks;
1664 {
1665 MutexLock mu(self, boot_completed_lock_);
1666 tasks = std::move(tasks_after_boot_);
1667 boot_completed_ = true;
1668 }
1669 for (Task* task : tasks) {
1670 thread_pool_->AddTask(self, task);
1671 }
1672}
1673
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001674bool Jit::CanEncodeMethod(ArtMethod* method, bool is_for_shared_region) const {
1675 return !is_for_shared_region ||
1676 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(method->GetDeclaringClass());
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001677}
1678
1679bool Jit::CanEncodeClass(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001680 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(cls);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001681}
1682
1683bool Jit::CanEncodeString(ObjPtr<mirror::String> string, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001684 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001685}
1686
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001687bool Jit::CanAssumeInitialized(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
1688 if (!is_for_shared_region) {
1689 return cls->IsInitialized();
1690 } else {
1691 // Look up the class status in the oat file.
1692 const DexFile& dex_file = *cls->GetDexCache()->GetDexFile();
1693 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1694 // In case we run without an image there won't be a backing oat file.
1695 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
1696 return false;
1697 }
1698 uint16_t class_def_index = cls->GetDexClassDefIndex();
1699 return oat_dex_file->GetOatClass(class_def_index).GetStatus() >= ClassStatus::kInitialized;
1700 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001701}
1702
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001703} // namespace jit
1704} // namespace art