blob: 63b5ffdbe31726decddeadc87232b5c5b8e63d47 [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 {
Nicolas Geoffray382df392019-10-31 11:57:15 +0000990 // Methods in the boot image should never have their single
991 // implementation flag set (and therefore never have a `data_` pointing
992 // to an ArtMethod for single implementation).
993 CHECK(method.IsIntrinsic() || !method.HasSingleImplementationFlag());
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100994 if (method.IsRuntimeMethod()) {
995 return;
996 }
997 if (method.GetDeclaringClassUnchecked()->IsVisiblyInitialized() ||
998 !method.IsStatic() ||
999 method.IsConstructor()) {
1000 // Method does not need any stub.
1001 return;
1002 }
1003
1004 // We are going to mremap the child mapping into the image:
1005 //
1006 // ImageSection ChildMappingMethods
1007 //
1008 // section start --> -----------
1009 // | |
1010 // | |
1011 // page_start --> | | <----- -----------
1012 // | | | |
1013 // | | | |
1014 // | | | |
1015 // | | | |
1016 // | | | |
1017 // | | | |
1018 // | | | |
1019 // page_end --> | | <----- -----------
1020 // | |
1021 // section end --> -----------
1022
1023
1024 uint8_t* pointer = reinterpret_cast<uint8_t*>(&method);
1025 if (pointer >= page_start && pointer < page_end) {
1026 // For all the methods in the mapping, put the entrypoint to the
1027 // resolution stub.
1028 ArtMethod* new_method = reinterpret_cast<ArtMethod*>(
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001029 child_mapping_methods.Begin() + offset + (pointer - page_start));
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001030 const void* code = new_method->GetEntryPointFromQuickCompiledCode();
1031 if (!class_linker->IsQuickGenericJniStub(code) &&
1032 !class_linker->IsQuickToInterpreterBridge(code) &&
1033 !class_linker->IsQuickResolutionStub(code)) {
1034 LOG(INFO) << "Putting back the resolution stub to an ArtMethod";
1035 new_method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
1036 }
1037 } else if (pointer < page_start && (pointer + sizeof(ArtMethod)) > page_start) {
1038 LOG(INFO) << "Copying parts of the contents of an ArtMethod spanning page_start";
1039 // If the method spans `page_start`, copy the contents of the child
1040 // into the pages we are going to remap into the image.
1041 //
1042 // section start --> -----------
1043 // | |
1044 // | |
1045 // page_start --> |/////////| -----------
1046 // |/////////| -> copy -> |/////////|
1047 // | | | |
1048 //
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001049 CopyIfDifferent(child_mapping_methods.Begin() + offset,
Nicolas Geoffrayff258062019-10-09 15:33:48 +01001050 page_start,
1051 pointer + sizeof(ArtMethod) - page_start);
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001052 } else if (pointer < page_end && (pointer + sizeof(ArtMethod)) > page_end) {
1053 LOG(INFO) << "Copying parts of the contents of an ArtMethod spanning page_end";
1054 // If the method spans `page_end`, copy the contents of the child
1055 // into the pages we are going to remap into the image.
1056 //
1057 // | | | |
1058 // |/////////| -> copy -> |/////////|
1059 // page_end --> |/////////| -----------
1060 // | |
1061 // section end --> -----------
1062 //
1063 size_t bytes_to_copy = (page_end - pointer);
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001064 CopyIfDifferent(child_mapping_methods.Begin() + offset + capacity - bytes_to_copy,
Nicolas Geoffrayff258062019-10-09 15:33:48 +01001065 page_end - bytes_to_copy,
1066 bytes_to_copy);
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001067 }
1068 }, space->Begin(), kRuntimePointerSize);
1069
1070 // Map the memory in the boot image range.
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001071 if (mremap(child_mapping_methods.Begin() + offset,
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001072 capacity,
1073 capacity,
1074 MREMAP_FIXED | MREMAP_MAYMOVE,
1075 page_start) == MAP_FAILED) {
1076 PLOG(WARNING) << "Fail to mremap boot image methods for " << space->GetImageFilename();
1077 }
1078 offset += capacity;
1079 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001080
1081 // The private mapping created for this process has been mremaped. We can
1082 // reset it.
1083 child_mapping_methods.Reset();
Nicolas Geoffray8e23d382019-10-30 13:53:01 +00001084 LOG(INFO) << "Successfully mapped boot image methods";
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001085}
1086
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001087void Jit::CreateThreadPool() {
1088 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
1089 // is not null when we instrument.
1090
1091 // We need peers as we may report the JIT thread, e.g., in the debugger.
1092 constexpr bool kJitPoolNeedsPeers = true;
1093 thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
1094
1095 thread_pool_->SetPthreadPriority(options_->GetThreadPoolPthreadPriority());
1096 Start();
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001097
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001098 Runtime* runtime = Runtime::Current();
David Srbecky3db3d372019-04-17 18:19:17 +01001099 if (runtime->IsZygote() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001100 // If we're not using the default boot image location, request a JIT task to
1101 // compile all methods in the boot image profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001102 thread_pool_->AddTask(Thread::Current(), new ZygoteTask());
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001103
1104 // And create mappings to share boot image methods memory from the zygote to
1105 // child processes.
1106
1107 // Compute the total capacity required for the boot image methods.
1108 uint64_t total_capacity = 0;
1109 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1110 const ImageHeader& header = space->GetImageHeader();
1111 const ImageSection& section = header.GetMethodsSection();
1112 // Mappings need to be at the page level.
1113 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
1114 uint8_t* page_end =
1115 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
1116 if (page_end > page_start) {
1117 total_capacity += (page_end - page_start);
1118 }
1119 }
1120
1121 // Create the child and zygote mappings to the boot image methods.
1122 if (total_capacity > 0) {
1123 // Start with '/boot' and end with '.art' to match the pattern recognized
1124 // by android_os_Debug.cpp for boot images.
1125 const char* name = "/boot-image-methods.art";
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001126 unique_fd mem_fd = unique_fd(art::memfd_create(name, /* flags= */ MFD_ALLOW_SEALING));
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001127 if (mem_fd.get() == -1) {
1128 PLOG(WARNING) << "Could not create boot image methods file descriptor";
1129 return;
1130 }
1131 if (ftruncate(mem_fd.get(), total_capacity) != 0) {
1132 PLOG(WARNING) << "Failed to truncate boot image methods file to " << total_capacity;
1133 return;
1134 }
1135 std::string error_str;
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001136
1137 // Create the shared mapping eagerly, as this prevents other processes
1138 // from adding the writable seal.
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001139 zygote_mapping_methods_ = MemMap::MapFile(
1140 total_capacity,
1141 PROT_READ | PROT_WRITE,
1142 MAP_SHARED,
1143 mem_fd,
1144 /* start= */ 0,
1145 /* low_4gb= */ false,
1146 "boot-image-methods",
1147 &error_str);
1148
1149 if (!zygote_mapping_methods_.IsValid()) {
1150 LOG(WARNING) << "Failed to create zygote mapping of boot image methods: " << error_str;
1151 return;
1152 }
1153 if (zygote_mapping_methods_.MadviseDontFork() != 0) {
1154 LOG(WARNING) << "Failed to madvise dont fork boot image methods";
1155 zygote_mapping_methods_ = MemMap();
1156 return;
1157 }
1158
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001159 if (IsSealFutureWriteSupported()) {
1160 // Seal now.
1161 if (fcntl(mem_fd,
1162 F_ADD_SEALS,
1163 F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL | F_SEAL_FUTURE_WRITE) == -1) {
1164 PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
1165 zygote_mapping_methods_ = MemMap();
1166 return;
1167 }
1168 } else {
1169 // Only seal the size. We will seal the write once we are donew writing
1170 // to the shared mapping.
1171 if (fcntl(mem_fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW) == -1) {
1172 PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
1173 zygote_mapping_methods_ = MemMap();
1174 return;
1175 }
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001176 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001177 fd_methods_ = unique_fd(mem_fd.release());
1178 fd_methods_size_ = total_capacity;
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001179 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001180 }
1181}
1182
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001183void Jit::RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Nicolas Geoffray741a0702019-06-10 11:18:11 +01001184 jobject class_loader) {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001185 if (dex_files.empty()) {
1186 return;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001187 }
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001188 Runtime* runtime = Runtime::Current();
1189 if (runtime->IsSystemServer() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
1190 thread_pool_->AddTask(Thread::Current(), new JitProfileTask(dex_files, class_loader));
1191 }
1192}
1193
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001194bool Jit::CompileMethodFromProfile(Thread* self,
1195 ClassLinker* class_linker,
1196 uint32_t method_idx,
1197 Handle<mirror::DexCache> dex_cache,
1198 Handle<mirror::ClassLoader> class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001199 bool add_to_queue,
1200 bool compile_after_boot) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001201 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
1202 method_idx, dex_cache, class_loader);
1203 if (method == nullptr) {
1204 self->ClearException();
1205 return false;
1206 }
1207 if (!method->IsCompilable() || !method->IsInvokable()) {
1208 return false;
1209 }
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001210 if (method->IsPreCompiled()) {
1211 // Already seen by another profile.
1212 return false;
1213 }
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001214 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1215 if (class_linker->IsQuickToInterpreterBridge(entry_point) ||
1216 class_linker->IsQuickGenericJniStub(entry_point) ||
1217 class_linker->IsQuickResolutionStub(entry_point)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001218 method->SetPreCompiled();
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001219 if (!add_to_queue) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001220 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ true);
1221 } else {
David Srbeckybfcea3d2019-08-05 15:44:00 +01001222 Task* task = new JitCompileTask(method, JitCompileTask::TaskKind::kPreCompile);
1223 if (compile_after_boot) {
1224 MutexLock mu(Thread::Current(), boot_completed_lock_);
1225 if (!boot_completed_) {
1226 tasks_after_boot_.push_back(task);
1227 return true;
1228 }
1229 DCHECK(tasks_after_boot_.empty());
1230 }
1231 thread_pool_->AddTask(self, task);
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001232 return true;
1233 }
1234 }
1235 return false;
1236}
1237
1238uint32_t Jit::CompileMethodsFromBootProfile(
1239 Thread* self,
1240 const std::vector<const DexFile*>& dex_files,
1241 const std::string& profile_file,
1242 Handle<mirror::ClassLoader> class_loader,
1243 bool add_to_queue) {
1244 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
1245
1246 if (profile.Fd() == -1) {
1247 PLOG(WARNING) << "No boot profile: " << profile_file;
1248 return 0u;
1249 }
1250
1251 ProfileBootInfo profile_info;
1252 if (!profile_info.Load(profile.Fd(), dex_files)) {
1253 LOG(ERROR) << "Could not load profile file: " << profile_file;
1254 return 0u;
1255 }
1256
1257 ScopedObjectAccess soa(self);
1258 VariableSizedHandleScope handles(self);
1259 std::vector<Handle<mirror::DexCache>> dex_caches;
1260 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1261 for (const DexFile* dex_file : profile_info.GetDexFiles()) {
1262 dex_caches.push_back(handles.NewHandle(class_linker->FindDexCache(self, *dex_file)));
1263 }
1264
1265 uint32_t added_to_queue = 0;
1266 for (const std::pair<uint32_t, uint32_t>& pair : profile_info.GetMethods()) {
1267 if (CompileMethodFromProfile(self,
1268 class_linker,
1269 pair.second,
1270 dex_caches[pair.first],
1271 class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001272 add_to_queue,
1273 /*compile_after_boot=*/false)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001274 ++added_to_queue;
1275 }
1276 }
1277 return added_to_queue;
1278}
1279
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001280uint32_t Jit::CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001281 Thread* self,
1282 const std::vector<const DexFile*>& dex_files,
1283 const std::string& profile_file,
1284 Handle<mirror::ClassLoader> class_loader,
1285 bool add_to_queue) {
1286
1287 if (profile_file.empty()) {
1288 LOG(WARNING) << "Expected a profile file in JIT zygote mode";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001289 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001290 }
1291
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001292 // We don't generate boot profiles on device, therefore we don't
1293 // need to lock the file.
1294 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001295
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001296 if (profile.Fd() == -1) {
1297 PLOG(WARNING) << "No profile: " << profile_file;
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001298 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001299 }
1300
1301 ProfileCompilationInfo profile_info;
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001302 if (!profile_info.Load(profile.Fd())) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001303 LOG(ERROR) << "Could not load profile file";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001304 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001305 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001306 ScopedObjectAccess soa(self);
1307 StackHandleScope<1> hs(self);
1308 MutableHandle<mirror::DexCache> dex_cache = hs.NewHandle<mirror::DexCache>(nullptr);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001309 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001310 uint32_t added_to_queue = 0u;
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001311 for (const DexFile* dex_file : dex_files) {
Martin Stjernholme58624f2019-09-20 15:53:40 +01001312 if (LocationIsOnArtModule(dex_file->GetLocation().c_str())) {
1313 // The ART module jars are already preopted.
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +01001314 continue;
1315 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +01001316 // To speed up class lookups, generate a type lookup table for
1317 // the dex file.
Nicolas Geoffrayc5e3a522019-04-30 09:47:55 +01001318 if (dex_file->GetOatDexFile() == nullptr) {
1319 TypeLookupTable type_lookup_table = TypeLookupTable::Create(*dex_file);
1320 type_lookup_tables_.push_back(
1321 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
1322 dex_file->SetOatDexFile(type_lookup_tables_.back().get());
1323 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +01001324
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001325 std::set<dex::TypeIndex> class_types;
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001326 std::set<uint16_t> all_methods;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001327 if (!profile_info.GetClassesAndMethods(*dex_file,
1328 &class_types,
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001329 &all_methods,
1330 &all_methods,
1331 &all_methods)) {
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +01001332 // This means the profile file did not reference the dex file, which is the case
1333 // if there's no classes and methods of that dex file in the profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001334 continue;
1335 }
1336 dex_cache.Assign(class_linker->FindDexCache(self, *dex_file));
1337 CHECK(dex_cache != nullptr) << "Could not find dex cache for " << dex_file->GetLocation();
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001338
1339 for (uint16_t method_idx : all_methods) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001340 if (CompileMethodFromProfile(self,
1341 class_linker,
1342 method_idx,
1343 dex_cache,
1344 class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001345 add_to_queue,
1346 /*compile_after_boot=*/true)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001347 ++added_to_queue;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001348 }
1349 }
1350 }
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +01001351
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001352 // Add a task to run when all compilation is done.
1353 JitDoneCompilingProfileTask* task = new JitDoneCompilingProfileTask(dex_files);
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +01001354 MutexLock mu(Thread::Current(), boot_completed_lock_);
1355 if (!boot_completed_) {
1356 tasks_after_boot_.push_back(task);
1357 } else {
1358 DCHECK(tasks_after_boot_.empty());
1359 thread_pool_->AddTask(self, task);
1360 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001361 return added_to_queue;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001362}
1363
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001364static bool IgnoreSamplesForMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray32384402019-07-17 20:06:44 +01001365 if (method->IsClassInitializer() || !method->IsCompilable() || method->IsPreCompiled()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001366 // We do not want to compile such methods.
1367 return true;
1368 }
1369 if (method->IsNative()) {
1370 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
Vladimir Markoc7aa87e2018-05-24 15:19:52 +01001371 if (klass == GetClassRoot<mirror::MethodHandle>() ||
1372 klass == GetClassRoot<mirror::VarHandle>()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001373 // MethodHandle and VarHandle invocation methods are required to throw an
1374 // UnsupportedOperationException if invoked reflectively. We achieve this by having native
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001375 // implementations that raise the exception. We need to disable JIT compilation of these JNI
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001376 // methods as it can lead to transitioning between JIT compiled JNI stubs and generic JNI
1377 // stubs. Since these stubs have different stack representations we can then crash in stack
1378 // walking (b/78151261).
1379 return true;
1380 }
1381 }
1382 return false;
1383}
1384
David Srbeckye3fc2d12018-11-30 13:41:14 +00001385bool Jit::MaybeCompileMethod(Thread* self,
1386 ArtMethod* method,
1387 uint32_t old_count,
1388 uint32_t new_count,
1389 bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001390 if (thread_pool_ == nullptr) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001391 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001392 }
David Srbecky1fc4d422019-07-23 16:55:19 +01001393 if (UNLIKELY(method->IsPreCompiled()) && !with_backedges /* don't check for OSR */) {
Vladimir Marko5115a4d2019-10-17 14:56:47 +01001394 if (!NeedsClinitCheckBeforeCall(method) ||
1395 method->GetDeclaringClass()->IsVisiblyInitialized()) {
Nicolas Geoffray5a0b6722019-09-24 15:09:40 +01001396 const void* entry_point = code_cache_->GetSavedEntryPointOfPreCompiledMethod(method);
1397 if (entry_point != nullptr) {
1398 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(method, entry_point);
1399 return true;
1400 }
David Srbecky1fc4d422019-07-23 16:55:19 +01001401 }
1402 }
Nicolas Geoffray5a0b6722019-09-24 15:09:40 +01001403
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001404 if (IgnoreSamplesForMethod(method)) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001405 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001406 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +01001407 if (HotMethodThreshold() == 0) {
David Srbeckyf4886df2017-12-11 16:06:29 +00001408 // Tests might request JIT on first use (compiled synchronously in the interpreter).
David Srbeckye3fc2d12018-11-30 13:41:14 +00001409 return false;
David Srbeckyf4886df2017-12-11 16:06:29 +00001410 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +01001411 DCHECK_GT(WarmMethodThreshold(), 0);
1412 DCHECK_GT(HotMethodThreshold(), WarmMethodThreshold());
1413 DCHECK_GT(OSRMethodThreshold(), HotMethodThreshold());
1414 DCHECK_GE(PriorityThreadWeight(), 1);
1415 DCHECK_LE(PriorityThreadWeight(), HotMethodThreshold());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001416
David Srbeckye3fc2d12018-11-30 13:41:14 +00001417 if (old_count < WarmMethodThreshold() && new_count >= WarmMethodThreshold()) {
1418 // Note: Native method have no "warm" state or profiling info.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001419 if (!method->IsNative() &&
1420 (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) &&
1421 code_cache_->CanAllocateProfilingInfo()) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001422 bool success = ProfilingInfo::Create(self, method, /* retry_allocation= */ false);
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001423 if (success) {
1424 VLOG(jit) << "Start profiling " << method->PrettyMethod();
1425 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001426
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001427 if (thread_pool_ == nullptr) {
1428 // Calling ProfilingInfo::Create might put us in a suspended state, which could
1429 // lead to the thread pool being deleted when we are shutting down.
David Srbeckye3fc2d12018-11-30 13:41:14 +00001430 return false;
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001431 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001432
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001433 if (!success) {
1434 // We failed allocating. Instead of doing the collection on the Java thread, we push
1435 // an allocation to a compiler thread, that will do the collection.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001436 thread_pool_->AddTask(
1437 self, new JitCompileTask(method, JitCompileTask::TaskKind::kAllocateProfile));
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001438 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001439 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001440 }
1441 if (UseJitCompilation()) {
David Srbeckyc45b5892019-04-24 10:32:04 +01001442 if (old_count == 0 &&
1443 method->IsNative() &&
1444 Runtime::Current()->IsUsingApexBootImageLocation()) {
1445 // jitzygote: Compile JNI stub on first use to avoid the expensive generic stub.
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001446 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ false);
David Srbeckyc45b5892019-04-24 10:32:04 +01001447 return true;
1448 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001449 if (old_count < HotMethodThreshold() && new_count >= HotMethodThreshold()) {
1450 if (!code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Calin Juravleffc87072016-04-20 14:22:09 +01001451 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001452 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompile));
Calin Juravleffc87072016-04-20 14:22:09 +01001453 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001454 }
1455 if (old_count < OSRMethodThreshold() && new_count >= OSRMethodThreshold()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001456 if (!with_backedges) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001457 return false;
Calin Juravleffc87072016-04-20 14:22:09 +01001458 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001459 DCHECK(!method->IsNative()); // No back edges reported for native methods.
David Srbeckye3fc2d12018-11-30 13:41:14 +00001460 if (!code_cache_->IsOsrCompiled(method)) {
Calin Juravleffc87072016-04-20 14:22:09 +01001461 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001462 thread_pool_->AddTask(
1463 self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompileOsr));
Calin Juravleffc87072016-04-20 14:22:09 +01001464 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001465 }
1466 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001467 return true;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001468}
1469
Alex Light59b950f2018-10-08 10:43:06 -07001470class ScopedSetRuntimeThread {
1471 public:
1472 explicit ScopedSetRuntimeThread(Thread* self)
1473 : self_(self), was_runtime_thread_(self_->IsRuntimeThread()) {
1474 self_->SetIsRuntimeThread(true);
1475 }
1476
1477 ~ScopedSetRuntimeThread() {
1478 self_->SetIsRuntimeThread(was_runtime_thread_);
1479 }
1480
1481 private:
1482 Thread* self_;
1483 bool was_runtime_thread_;
1484};
1485
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001486void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
Calin Juravleffc87072016-04-20 14:22:09 +01001487 Runtime* runtime = Runtime::Current();
Nicolas Geoffray5e33ccd2019-07-03 10:53:08 +01001488 if (UNLIKELY(runtime->UseJitCompilation() && JitAtFirstUse())) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001489 ArtMethod* np_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001490 if (np_method->IsCompilable()) {
Nicolas Geoffray5e33ccd2019-07-03 10:53:08 +01001491 if (!np_method->IsNative() && GetCodeCache()->CanAllocateProfilingInfo()) {
Nicolas Geoffray29bb8032019-06-06 10:32:24 +01001492 // The compiler requires a ProfilingInfo object for non-native methods.
1493 ProfilingInfo::Create(thread, np_method, /* retry_allocation= */ true);
1494 }
1495 // TODO(ngeoffray): For JIT at first use, use kPreCompile. Currently we don't due to
1496 // conflicts with jitzygote optimizations.
1497 JitCompileTask compile_task(method, JitCompileTask::TaskKind::kCompile);
Alex Light59b950f2018-10-08 10:43:06 -07001498 // Fake being in a runtime thread so that class-load behavior will be the same as normal jit.
1499 ScopedSetRuntimeThread ssrt(thread);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001500 compile_task.Run(thread);
1501 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001502 return;
1503 }
1504
Andreas Gampe542451c2016-07-26 09:02:02 -07001505 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001506 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
Alex Light2d441b12018-06-08 15:33:21 -07001507 // instead of interpreting the method. We don't update it for instrumentation as the entrypoint
1508 // must remain the instrumentation entrypoint.
1509 if ((profiling_info != nullptr) &&
1510 (profiling_info->GetSavedEntryPoint() != nullptr) &&
1511 (method->GetEntryPointFromQuickCompiledCode() != GetQuickInstrumentationEntryPoint())) {
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001512 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1513 method, profiling_info->GetSavedEntryPoint());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001514 } else {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001515 AddSamples(thread, method, 1, /* with_backedges= */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001516 }
1517}
1518
Mathieu Chartieref41db72016-10-25 15:08:01 -07001519void Jit::InvokeVirtualOrInterface(ObjPtr<mirror::Object> this_object,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001520 ArtMethod* caller,
1521 uint32_t dex_pc,
1522 ArtMethod* callee ATTRIBUTE_UNUSED) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001523 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001524 DCHECK(this_object != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001525 ProfilingInfo* info = caller->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001526 if (info != nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001527 info->AddInvokeInfo(dex_pc, this_object->GetClass());
1528 }
1529}
1530
1531void Jit::WaitForCompilationToFinish(Thread* self) {
1532 if (thread_pool_ != nullptr) {
1533 thread_pool_->Wait(self, false, false);
1534 }
1535}
1536
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001537void Jit::Stop() {
1538 Thread* self = Thread::Current();
1539 // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
1540 WaitForCompilationToFinish(self);
1541 GetThreadPool()->StopWorkers(self);
1542 WaitForCompilationToFinish(self);
1543}
1544
1545void Jit::Start() {
David Srbeckyd25eb2c2018-07-19 12:17:04 +00001546 GetThreadPool()->StartWorkers(Thread::Current());
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001547}
1548
Andreas Gampef149b3f2016-11-16 14:58:24 -08001549ScopedJitSuspend::ScopedJitSuspend() {
1550 jit::Jit* jit = Runtime::Current()->GetJit();
1551 was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
1552 if (was_on_) {
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001553 jit->Stop();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001554 }
1555}
1556
1557ScopedJitSuspend::~ScopedJitSuspend() {
1558 if (was_on_) {
1559 DCHECK(Runtime::Current()->GetJit() != nullptr);
1560 DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001561 Runtime::Current()->GetJit()->Start();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001562 }
1563}
1564
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001565static void* RunPollingThread(void* arg) {
1566 Jit* jit = reinterpret_cast<Jit*>(arg);
1567 do {
1568 sleep(10);
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001569 } while (!jit->GetCodeCache()->GetZygoteMap()->IsCompilationNotified());
Nicolas Geoffray8e23d382019-10-30 13:53:01 +00001570
1571 // We will suspend other threads: we can only do that if we're attached to the
1572 // runtime.
1573 Runtime* runtime = Runtime::Current();
1574 bool thread_attached = runtime->AttachCurrentThread(
1575 "BootImagePollingThread",
1576 /* as_daemon= */ true,
1577 /* thread_group= */ nullptr,
1578 /* create_peer= */ false);
1579 CHECK(thread_attached);
1580
1581 {
1582 // Prevent other threads from running while we are remapping the boot image
1583 // ArtMethod's. Native threads might still be running, but they cannot
1584 // change the contents of ArtMethod's.
1585 ScopedSuspendAll ssa(__FUNCTION__);
1586 runtime->GetJit()->MapBootImageMethods();
1587 }
1588
1589 Runtime::Current()->DetachCurrentThread();
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001590 return nullptr;
1591}
1592
Nicolas Geoffray0d54cfb2019-05-03 09:13:52 +01001593void Jit::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffraye9455f62019-08-15 20:57:04 +01001594 // Clear the potential boot tasks inherited from the zygote.
1595 {
1596 MutexLock mu(Thread::Current(), boot_completed_lock_);
1597 tasks_after_boot_.clear();
1598 }
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001599
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001600 if (Runtime::Current()->IsUsingApexBootImageLocation() && fd_methods_ != -1) {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001601 // Create a thread that will poll the status of zygote compilation, and map
1602 // the private mapping of boot image methods.
1603 zygote_mapping_methods_.ResetInForkedProcess();
1604 pthread_t polling_thread;
1605 pthread_attr_t attr;
1606 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
1607 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED),
1608 "PTHREAD_CREATE_DETACHED");
1609 CHECK_PTHREAD_CALL(
1610 pthread_create,
1611 (&polling_thread, &attr, RunPollingThread, reinterpret_cast<void*>(this)),
1612 "Methods maps thread");
1613 }
1614
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001615 if (is_zygote || Runtime::Current()->IsSafeMode()) {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001616 // Delete the thread pool, we are not going to JIT.
1617 thread_pool_.reset(nullptr);
1618 return;
1619 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001620 // At this point, the compiler options have been adjusted to the particular configuration
1621 // of the forked child. Parse them again.
David Srbecky46b53532019-08-06 13:39:05 +01001622 jit_compiler_->ParseCompilerOptions();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001623
1624 // Adjust the status of code cache collection: the status from zygote was to not collect.
David Srbecky46b53532019-08-06 13:39:05 +01001625 code_cache_->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001626 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001627
Nicolas Geoffraya67daeb2019-08-12 10:41:25 +01001628 if (is_system_server && Runtime::Current()->IsUsingApexBootImageLocation()) {
1629 // Disable garbage collection: we don't want it to delete methods we're compiling
1630 // through boot and system server profiles.
1631 // TODO(ngeoffray): Fix this so we still collect deoptimized and unused code.
1632 code_cache_->SetGarbageCollectCode(false);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001633 }
Nicolas Geoffray371390f2019-09-27 09:57:38 +01001634
1635 // We do this here instead of PostZygoteFork, as NativeDebugInfoPostFork only
1636 // applies to a child.
1637 NativeDebugInfoPostFork();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001638}
1639
1640void Jit::PreZygoteFork() {
1641 if (thread_pool_ == nullptr) {
1642 return;
1643 }
1644 thread_pool_->DeleteThreads();
David Srbecky1550a662019-08-14 17:16:46 +01001645
1646 NativeDebugInfoPreFork();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001647}
1648
1649void Jit::PostZygoteFork() {
1650 if (thread_pool_ == nullptr) {
1651 return;
1652 }
Nicolas Geoffray8852e532019-10-30 09:43:35 +00001653 if (Runtime::Current()->IsZygote() &&
1654 code_cache_->GetZygoteMap()->IsCompilationDoneButNotNotified()) {
1655 // Copy the boot image methods data to the mappings we created to share
1656 // with the children. We do this here as we are the only thread running and
1657 // we don't risk other threads concurrently updating the ArtMethod's.
1658 CHECK_EQ(GetTaskCount(), 1);
1659 NotifyZygoteCompilationDone();
1660 CHECK(code_cache_->GetZygoteMap()->IsCompilationNotified());
1661 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001662 thread_pool_->CreateThreads();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001663}
1664
David Srbeckybfcea3d2019-08-05 15:44:00 +01001665void Jit::BootCompleted() {
1666 Thread* self = Thread::Current();
1667 std::deque<Task*> tasks;
1668 {
1669 MutexLock mu(self, boot_completed_lock_);
1670 tasks = std::move(tasks_after_boot_);
1671 boot_completed_ = true;
1672 }
1673 for (Task* task : tasks) {
1674 thread_pool_->AddTask(self, task);
1675 }
1676}
1677
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001678bool Jit::CanEncodeMethod(ArtMethod* method, bool is_for_shared_region) const {
1679 return !is_for_shared_region ||
1680 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(method->GetDeclaringClass());
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001681}
1682
1683bool Jit::CanEncodeClass(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001684 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(cls);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001685}
1686
1687bool Jit::CanEncodeString(ObjPtr<mirror::String> string, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001688 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001689}
1690
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001691bool Jit::CanAssumeInitialized(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
1692 if (!is_for_shared_region) {
1693 return cls->IsInitialized();
1694 } else {
1695 // Look up the class status in the oat file.
1696 const DexFile& dex_file = *cls->GetDexCache()->GetDexFile();
1697 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1698 // In case we run without an image there won't be a backing oat file.
1699 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
1700 return false;
1701 }
1702 uint16_t class_def_index = cls->GetDexClassDefIndex();
1703 return oat_dex_file->GetOatClass(class_def_index).GetStatus() >= ClassStatus::kInitialized;
1704 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001705}
1706
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001707} // namespace jit
1708} // namespace art