blob: ad8cc9ab6357b66af72c355fd96099a22e96e7ad [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_code_cache.h"
18
19#include <sstream>
20
Andreas Gampec7d878d2018-11-19 18:42:06 +000021#include <android-base/logging.h>
Orion Hodson1d3fd082018-09-28 09:38:35 +010022
Andreas Gampe5629d2d2017-05-15 16:28:13 -070023#include "arch/context.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070024#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070025#include "base/enums.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070026#include "base/histogram-inl.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080027#include "base/logging.h" // For VLOG.
Orion Hodson563ada22018-09-04 11:28:31 +010028#include "base/membarrier.h"
Orion Hodson1d3fd082018-09-28 09:38:35 +010029#include "base/memfd.h"
David Sehr79e26072018-04-06 17:58:50 -070030#include "base/mem_map.h"
David Sehrc431b9d2018-03-02 12:01:51 -080031#include "base/quasi_atomic.h"
Calin Juravle66f55232015-12-08 15:09:10 +000032#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080033#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010034#include "base/time_utils.h"
Orion Hodsonf2331362018-07-11 15:14:10 +010035#include "base/utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070036#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000037#include "debugger_interface.h"
David Sehr9e734c72018-01-04 17:56:19 -080038#include "dex/dex_file_loader.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070039#include "dex/method_reference.h"
Vladimir Marko5115a4d2019-10-17 14:56:47 +010040#include "entrypoints/entrypoint_utils-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010041#include "entrypoints/runtime_asm_entrypoints.h"
42#include "gc/accounting/bitmap-inl.h"
Stefano Cianciullicca4c6e2022-06-24 17:03:52 +000043#include "gc/allocator/art-dlmalloc.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010044#include "gc/scoped_gc_critical_section.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000045#include "handle.h"
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +000046#include "handle_scope-inl.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070047#include "instrumentation.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070048#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000049#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000050#include "jit/profiling_info.h"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010051#include "jit/jit_scoped_code_cache_write.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010052#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080053#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070054#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070055#include "object_callbacks.h"
David Sehr82d046e2018-04-23 08:14:19 -070056#include "profile/profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070057#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070058#include "stack.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000059#include "thread-current-inl.h"
Hans Boehm1b3ec0f2022-01-26 16:53:07 +000060#include "thread-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010061#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080062
63namespace art {
64namespace jit {
65
Nicolas Geoffray933330a2016-03-16 14:20:06 +000066static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
67static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
68
Vladimir Marko2196c652017-11-30 16:16:07 +000069class JitCodeCache::JniStubKey {
70 public:
71 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
72 : shorty_(method->GetShorty()),
73 is_static_(method->IsStatic()),
74 is_fast_native_(method->IsFastNative()),
75 is_critical_native_(method->IsCriticalNative()),
76 is_synchronized_(method->IsSynchronized()) {
77 DCHECK(!(is_fast_native_ && is_critical_native_));
78 }
79
80 bool operator<(const JniStubKey& rhs) const {
81 if (is_static_ != rhs.is_static_) {
82 return rhs.is_static_;
83 }
84 if (is_synchronized_ != rhs.is_synchronized_) {
85 return rhs.is_synchronized_;
86 }
87 if (is_fast_native_ != rhs.is_fast_native_) {
88 return rhs.is_fast_native_;
89 }
90 if (is_critical_native_ != rhs.is_critical_native_) {
91 return rhs.is_critical_native_;
92 }
93 return strcmp(shorty_, rhs.shorty_) < 0;
94 }
95
96 // Update the shorty to point to another method's shorty. Call this function when removing
97 // the method that references the old shorty from JniCodeData and not removing the entire
98 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
99 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
100 const char* shorty = method->GetShorty();
101 DCHECK_STREQ(shorty_, shorty);
102 shorty_ = shorty;
103 }
104
105 private:
106 // The shorty points to a DexFile data and may need to change
107 // to point to the same shorty in a different DexFile.
108 mutable const char* shorty_;
109
110 const bool is_static_;
111 const bool is_fast_native_;
112 const bool is_critical_native_;
113 const bool is_synchronized_;
114};
115
116class JitCodeCache::JniStubData {
117 public:
118 JniStubData() : code_(nullptr), methods_() {}
119
120 void SetCode(const void* code) {
121 DCHECK(code != nullptr);
122 code_ = code;
123 }
124
Vladimir Markocce414f2019-10-07 08:51:33 +0100125 void UpdateEntryPoints(const void* entrypoint) REQUIRES_SHARED(Locks::mutator_lock_) {
126 DCHECK(IsCompiled());
127 DCHECK(entrypoint == OatQuickMethodHeader::FromCodePointer(GetCode())->GetEntryPoint());
128 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
129 for (ArtMethod* m : GetMethods()) {
130 // Because `m` might be in the process of being deleted:
131 // - Call the dedicated method instead of the more generic UpdateMethodsCode
Vladimir Marko5115a4d2019-10-17 14:56:47 +0100132 // - Check the class status without a full read barrier; use ReadBarrier::IsMarked().
133 bool can_set_entrypoint = true;
134 if (NeedsClinitCheckBeforeCall(m)) {
135 // To avoid resurrecting an unreachable object, we must not use a full read
136 // barrier but we do not want to miss updating an entrypoint under common
137 // circumstances, i.e. during a GC the class becomes visibly initialized,
138 // the method becomes hot, we compile the thunk and want to update the
139 // entrypoint while the method's declaring class field still points to the
140 // from-space class object with the old status. Therefore we read the
141 // declaring class without a read barrier and check if it's already marked.
142 // If yes, we check the status of the to-space class object as intended.
143 // Otherwise, there is no to-space object and the from-space class object
144 // contains the most recent value of the status field; even if this races
145 // with another thread doing a read barrier and updating the status, that's
146 // no different from a race with a thread that just updates the status.
147 // Such race can happen only for the zygote method pre-compilation, as we
148 // otherwise compile only thunks for methods of visibly initialized classes.
149 ObjPtr<mirror::Class> klass = m->GetDeclaringClass<kWithoutReadBarrier>();
150 ObjPtr<mirror::Class> marked = ReadBarrier::IsMarked(klass.Ptr());
151 ObjPtr<mirror::Class> checked_klass = (marked != nullptr) ? marked : klass;
152 can_set_entrypoint = checked_klass->IsVisiblyInitialized();
153 }
154 if (can_set_entrypoint) {
Vladimir Markocce414f2019-10-07 08:51:33 +0100155 instrum->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
156 }
157 }
158 }
159
Vladimir Marko2196c652017-11-30 16:16:07 +0000160 const void* GetCode() const {
161 return code_;
162 }
163
164 bool IsCompiled() const {
165 return GetCode() != nullptr;
166 }
167
168 void AddMethod(ArtMethod* method) {
169 if (!ContainsElement(methods_, method)) {
170 methods_.push_back(method);
171 }
172 }
173
174 const std::vector<ArtMethod*>& GetMethods() const {
175 return methods_;
176 }
177
David Srbecky41617b12020-03-18 21:19:06 +0000178 void RemoveMethodsIn(const LinearAlloc& alloc) REQUIRES_SHARED(Locks::mutator_lock_) {
179 auto kept_end = std::partition(
Vladimir Marko2196c652017-11-30 16:16:07 +0000180 methods_.begin(),
181 methods_.end(),
David Srbecky41617b12020-03-18 21:19:06 +0000182 [&alloc](ArtMethod* method) { return !alloc.ContainsUnsafe(method); });
183 for (auto it = kept_end; it != methods_.end(); it++) {
184 VLOG(jit) << "JIT removed (JNI) " << (*it)->PrettyMethod() << ": " << code_;
185 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000186 methods_.erase(kept_end, methods_.end());
187 }
188
David Srbecky41617b12020-03-18 21:19:06 +0000189 bool RemoveMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000190 auto it = std::find(methods_.begin(), methods_.end(), method);
191 if (it != methods_.end()) {
David Srbecky41617b12020-03-18 21:19:06 +0000192 VLOG(jit) << "JIT removed (JNI) " << (*it)->PrettyMethod() << ": " << code_;
Vladimir Marko2196c652017-11-30 16:16:07 +0000193 methods_.erase(it);
194 return true;
195 } else {
196 return false;
197 }
198 }
199
200 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
201 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
202 }
203
204 private:
205 const void* code_;
206 std::vector<ArtMethod*> methods_;
207};
208
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000209JitCodeCache* JitCodeCache::Create(bool used_only_for_profile_data,
210 bool rwx_memory_allowed,
211 bool is_zygote,
212 std::string* error_msg) {
213 // Register for membarrier expedited sync core if JIT will be generating code.
214 if (!used_only_for_profile_data) {
215 if (art::membarrier(art::MembarrierCommand::kRegisterPrivateExpeditedSyncCore) != 0) {
216 // MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE ensures that CPU instruction pipelines are
217 // flushed and it's used when adding code to the JIT. The memory used by the new code may
218 // have just been released and, in theory, the old code could still be in a pipeline.
219 VLOG(jit) << "Kernel does not support membarrier sync-core";
220 }
221 }
222
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100223 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000224 // Check whether the provided max capacity in options is below 1GB.
225 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
226 // We need to have 32 bit offsets from method headers in code cache which point to things
227 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
228 // Ensure we're below 1 GB to be safe.
229 if (max_capacity > 1 * GB) {
230 std::ostringstream oss;
231 oss << "Maxium code cache capacity is limited to 1 GB, "
232 << PrettySize(max_capacity) << " is too big";
233 *error_msg = oss.str();
234 return nullptr;
235 }
236
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100237 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100238 JitMemoryRegion region;
239 if (!region.Initialize(initial_capacity,
240 max_capacity,
241 rwx_memory_allowed,
242 is_zygote,
243 error_msg)) {
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000244 return nullptr;
245 }
246
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100247 std::unique_ptr<JitCodeCache> jit_code_cache(new JitCodeCache());
248 if (is_zygote) {
249 // Zygote should never collect code to share the memory with the children.
250 jit_code_cache->garbage_collect_code_ = false;
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000251 jit_code_cache->shared_region_ = std::move(region);
252 } else {
253 jit_code_cache->private_region_ = std::move(region);
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100254 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000255
256 VLOG(jit) << "Created jit code cache: initial capacity="
257 << PrettySize(initial_capacity)
258 << ", maximum capacity="
259 << PrettySize(max_capacity);
260
261 return jit_code_cache.release();
262}
263
264JitCodeCache::JitCodeCache()
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100265 : is_weak_access_enabled_(true),
266 inline_cache_cond_("Jit inline cache condition variable", *Locks::jit_lock_),
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100267 zygote_map_(&shared_region_),
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100268 lock_cond_("Jit code cache condition variable", *Locks::jit_lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100269 collection_in_progress_(false),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000270 last_collection_increased_code_cache_(false),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100271 garbage_collect_code_(true),
Nicolas Geoffrayc473dc72020-07-03 15:04:21 +0100272 number_of_baseline_compilations_(0),
273 number_of_optimized_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000274 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000275 number_of_collections_(0),
276 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
277 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100278 histogram_profiling_info_memory_use_("Memory used for profiling info", 16) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800279}
280
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000281JitCodeCache::~JitCodeCache() {}
282
Alex Light280e6c32020-03-03 13:52:07 -0800283bool JitCodeCache::PrivateRegionContainsPc(const void* ptr) const {
284 return private_region_.IsInExecSpace(ptr);
285}
286
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100287bool JitCodeCache::ContainsPc(const void* ptr) const {
Alex Light280e6c32020-03-03 13:52:07 -0800288 return PrivateRegionContainsPc(ptr) || shared_region_.IsInExecSpace(ptr);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800289}
290
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000291bool JitCodeCache::ContainsMethod(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100292 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000293 if (UNLIKELY(method->IsNative())) {
294 auto it = jni_stubs_map_.find(JniStubKey(method));
295 if (it != jni_stubs_map_.end() &&
296 it->second.IsCompiled() &&
297 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000298 return true;
299 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000300 } else {
301 for (const auto& it : method_code_map_) {
302 if (it.second == method) {
303 return true;
304 }
305 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100306 if (zygote_map_.ContainsMethod(method)) {
307 return true;
308 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000309 }
310 return false;
311}
312
Vladimir Marko2196c652017-11-30 16:16:07 +0000313const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
314 DCHECK(method->IsNative());
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100315 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000316 auto it = jni_stubs_map_.find(JniStubKey(method));
317 if (it != jni_stubs_map_.end()) {
318 JniStubData& data = it->second;
319 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
320 return data.GetCode();
321 }
322 }
323 return nullptr;
324}
325
Nicolas Geoffray32384402019-07-17 20:06:44 +0100326const void* JitCodeCache::GetSavedEntryPointOfPreCompiledMethod(ArtMethod* method) {
Nicolas Geoffray4cbb51a2020-02-07 11:25:54 +0000327 if (method->IsPreCompiled()) {
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100328 const void* code_ptr = nullptr;
Santiago Aboy Solanesf4bd5de2022-03-23 08:25:33 +0000329 if (method->GetDeclaringClass()->IsBootStrapClassLoaded()) {
Mythri Alle519ff8b2021-11-17 13:47:07 +0000330 code_ptr = zygote_map_.GetCodeFor(method);
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100331 } else {
Nicolas Geoffray32384402019-07-17 20:06:44 +0100332 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
333 auto it = saved_compiled_methods_map_.find(method);
334 if (it != saved_compiled_methods_map_.end()) {
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100335 code_ptr = it->second;
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100336 }
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100337 }
338 if (code_ptr != nullptr) {
339 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
340 return method_header->GetEntryPoint();
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100341 }
342 }
343 return nullptr;
344}
345
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100346bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
347 bool in_collection = false;
348 while (collection_in_progress_) {
349 in_collection = true;
350 lock_cond_.Wait(self);
351 }
352 return in_collection;
353}
354
355static uintptr_t FromCodeToAllocation(const void* code) {
Orion Hodsone764f382019-06-27 12:56:48 +0100356 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100357 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
358}
359
David Srbecky30fd8512020-02-20 20:27:58 +0000360static const void* FromAllocationToCode(const uint8_t* alloc) {
361 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
362 return reinterpret_cast<const void*>(alloc + RoundUp(sizeof(OatQuickMethodHeader), alignment));
363}
364
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000365static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
366 // The length of the table is stored just before the stack map (and therefore at the end of
367 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
368 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
369}
370
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000371static void DCheckRootsAreValid(const std::vector<Handle<mirror::Object>>& roots,
372 bool is_shared_region)
Alex Light3e36a9c2018-06-19 09:45:05 -0700373 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
374 if (!kIsDebugBuild) {
375 return;
376 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700377 // Put all roots in `roots_data`.
Vladimir Markoac3ac682018-09-20 11:01:43 +0100378 for (Handle<mirror::Object> object : roots) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700379 // Ensure the string is strongly interned. b/32995596
380 if (object->IsString()) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100381 ObjPtr<mirror::String> str = object->AsString();
Alex Light3e36a9c2018-06-19 09:45:05 -0700382 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
383 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
384 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000385 // Ensure that we don't put movable objects in the shared region.
386 if (is_shared_region) {
387 CHECK(!Runtime::Current()->GetHeap()->IsMovableObject(object.Get()));
388 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700389 }
390}
391
David Srbecky87fb0322019-08-20 10:34:02 +0100392static const uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000393 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
394 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
395 uint32_t roots = GetNumberOfRoots(data);
396 if (number_of_roots != nullptr) {
397 *number_of_roots = roots;
398 }
399 return data - ComputeRootTableSize(roots);
400}
401
402void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100403 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000404 for (const auto& entry : method_code_map_) {
405 uint32_t number_of_roots = 0;
David Srbecky87fb0322019-08-20 10:34:02 +0100406 const uint8_t* root_table = GetRootTable(entry.first, &number_of_roots);
407 uint8_t* roots_data = private_region_.IsInDataSpace(root_table)
408 ? private_region_.GetWritableDataAddress(root_table)
409 : shared_region_.GetWritableDataAddress(root_table);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000410 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
411 for (uint32_t i = 0; i < number_of_roots; ++i) {
412 // This does not need a read barrier because this is called by GC.
413 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffraye3f775b2019-12-04 14:41:52 +0000414 if (object == nullptr || object == Runtime::GetWeakClassSentinel()) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000415 // entry got deleted in a previous sweep.
Vladimir Markod355acf2019-03-21 17:09:40 +0000416 } else if (object->IsString<kDefaultVerifyFlags>()) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000417 mirror::Object* new_object = visitor->IsMarked(object);
418 // We know the string is marked because it's a strongly-interned string that
419 // is always alive. The IsMarked implementation of the CMS collector returns
420 // null for newly allocated objects, but we know those haven't moved. Therefore,
421 // only update the entry if we get a different non-null string.
422 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
423 // out of the weak access/creation pause. b/32167580
424 if (new_object != nullptr && new_object != object) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000425 roots[i] = GcRoot<mirror::Object>(new_object);
426 }
427 } else {
Nicolas Geoffraye3f775b2019-12-04 14:41:52 +0000428 Runtime::ProcessWeakClass(
429 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]),
430 visitor,
431 Runtime::GetWeakClassSentinel());
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000432 }
433 }
434 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000435 // Walk over inline caches to clear entries containing unloaded classes.
Nicolas Geoffray095dc462020-08-17 16:40:28 +0100436 for (auto it : profiling_infos_) {
437 ProfilingInfo* info = it.second;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000438 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
439 InlineCache* cache = &info->cache_[i];
440 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffraye3f775b2019-12-04 14:41:52 +0000441 Runtime::ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000442 }
443 }
444 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000445}
446
David Srbecky30fd8512020-02-20 20:27:58 +0000447void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
Nicolas Geoffrayae982f92018-12-08 12:31:10 +0000448 if (IsInZygoteExecSpace(code_ptr)) {
449 // No need to free, this is shared memory.
450 return;
451 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100452 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky30fd8512020-02-20 20:27:58 +0000453 const uint8_t* data = nullptr;
Vladimir Marko2196c652017-11-30 16:16:07 +0000454 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
David Srbecky30fd8512020-02-20 20:27:58 +0000455 data = GetRootTable(code_ptr);
Vladimir Marko2196c652017-11-30 16:16:07 +0000456 } // else this is a JNI stub without any data.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100457
David Srbecky30fd8512020-02-20 20:27:58 +0000458 FreeLocked(&private_region_, reinterpret_cast<uint8_t*>(allocation), data);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100459}
460
Mingyao Yang063fc772016-08-02 11:02:54 -0700461void JitCodeCache::FreeAllMethodHeaders(
462 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700463 // We need to remove entries in method_headers from CHA dependencies
464 // first since once we do FreeCode() below, the memory can be reused
465 // so it's possible for the same method_header to start representing
466 // different compile code.
Alex Light33b7b5d2018-08-07 19:13:51 +0000467 {
468 MutexLock mu2(Thread::Current(), *Locks::cha_lock_);
469 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
470 ->RemoveDependentsWithMethodHeaders(method_headers);
471 }
472
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100473 ScopedCodeCacheWrite scc(private_region_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700474 for (const OatQuickMethodHeader* method_header : method_headers) {
David Srbecky30fd8512020-02-20 20:27:58 +0000475 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700476 }
David Srbecky30fd8512020-02-20 20:27:58 +0000477
478 // We have potentially removed a lot of debug info. Do maintenance pass to save space.
479 RepackNativeDebugInfoForJit();
David Srbecky41617b12020-03-18 21:19:06 +0000480
481 // Check that the set of compiled methods exactly matches native debug information.
David Srbecky1f947b42020-12-08 16:08:04 +0000482 // Does not check zygote methods since they can change concurrently.
483 if (kIsDebugBuild && !Runtime::Current()->IsZygote()) {
David Srbecky41617b12020-03-18 21:19:06 +0000484 std::map<const void*, ArtMethod*> compiled_methods;
485 VisitAllMethods([&](const void* addr, ArtMethod* method) {
David Srbecky1f947b42020-12-08 16:08:04 +0000486 if (!IsInZygoteExecSpace(addr)) {
487 CHECK(addr != nullptr && method != nullptr);
488 compiled_methods.emplace(addr, method);
489 }
David Srbecky41617b12020-03-18 21:19:06 +0000490 });
491 std::set<const void*> debug_info;
492 ForEachNativeDebugSymbol([&](const void* addr, size_t, const char* name) {
493 addr = AlignDown(addr, GetInstructionSetInstructionAlignment(kRuntimeISA)); // Thumb-bit.
494 CHECK(debug_info.emplace(addr).second) << "Duplicate debug info: " << addr << " " << name;
495 CHECK_EQ(compiled_methods.count(addr), 1u) << "Extra debug info: " << addr << " " << name;
496 });
497 if (!debug_info.empty()) { // If debug-info generation is enabled.
498 for (auto it : compiled_methods) {
499 CHECK_EQ(debug_info.count(it.first), 1u) << "No debug info: " << it.second->PrettyMethod();
500 }
David Srbecky1f947b42020-12-08 16:08:04 +0000501 CHECK_EQ(compiled_methods.size(), debug_info.size());
David Srbecky41617b12020-03-18 21:19:06 +0000502 }
503 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700504}
505
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100506void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800507 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700508 // We use a set to first collect all method_headers whose code need to be
509 // removed. We need to free the underlying code after we remove CHA dependencies
510 // for entries in this set. And it's more efficient to iterate through
511 // the CHA dependency map just once with an unordered_set.
512 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000513 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100514 MutexLock mu(self, *Locks::jit_lock_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700515 // We do not check if a code cache GC is in progress, as this method comes
516 // with the classlinker_classes_lock_ held, and suspending ourselves could
517 // lead to a deadlock.
518 {
Vladimir Marko2196c652017-11-30 16:16:07 +0000519 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
520 it->second.RemoveMethodsIn(alloc);
521 if (it->second.GetMethods().empty()) {
522 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
523 it = jni_stubs_map_.erase(it);
524 } else {
525 it->first.UpdateShorty(it->second.GetMethods().front());
526 ++it;
527 }
528 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700529 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
530 if (alloc.ContainsUnsafe(it->second)) {
531 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
David Srbecky41617b12020-03-18 21:19:06 +0000532 VLOG(jit) << "JIT removed " << it->second->PrettyMethod() << ": " << it->first;
Mingyao Yang063fc772016-08-02 11:02:54 -0700533 it = method_code_map_.erase(it);
534 } else {
535 ++it;
536 }
537 }
538 }
539 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
540 if (alloc.ContainsUnsafe(it->first)) {
541 // Note that the code has already been pushed to method_headers in the loop
542 // above and is going to be removed in FreeCode() below.
543 it = osr_code_map_.erase(it);
544 } else {
545 ++it;
546 }
547 }
548 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
Nicolas Geoffray095dc462020-08-17 16:40:28 +0100549 ProfilingInfo* info = it->second;
Mingyao Yang063fc772016-08-02 11:02:54 -0700550 if (alloc.ContainsUnsafe(info->GetMethod())) {
David Srbecky87fb0322019-08-20 10:34:02 +0100551 private_region_.FreeWritableData(reinterpret_cast<uint8_t*>(info));
Mingyao Yang063fc772016-08-02 11:02:54 -0700552 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000553 } else {
554 ++it;
555 }
556 }
David Srbecky521644b2020-03-21 13:17:52 +0000557 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000558 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100559}
560
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000561bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
Lokesh Gidraca5ed9f2022-04-20 01:39:28 +0000562 return gUseReadBarrier
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000563 ? self->GetWeakRefAccessEnabled()
Orion Hodson88591fe2018-03-06 13:35:43 +0000564 : is_weak_access_enabled_.load(std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000565}
566
567void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
568 if (IsWeakAccessEnabled(self)) {
569 return;
570 }
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000571 ScopedThreadSuspension sts(self, ThreadState::kWaitingWeakGcRootRead);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100572 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000573 while (!IsWeakAccessEnabled(self)) {
574 inline_cache_cond_.Wait(self);
575 }
576}
577
578void JitCodeCache::BroadcastForInlineCacheAccess() {
579 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100580 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000581 inline_cache_cond_.Broadcast(self);
582}
583
584void JitCodeCache::AllowInlineCacheAccess() {
Lokesh Gidraca5ed9f2022-04-20 01:39:28 +0000585 DCHECK(!gUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000586 is_weak_access_enabled_.store(true, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000587 BroadcastForInlineCacheAccess();
588}
589
590void JitCodeCache::DisallowInlineCacheAccess() {
Lokesh Gidraca5ed9f2022-04-20 01:39:28 +0000591 DCHECK(!gUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000592 is_weak_access_enabled_.store(false, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000593}
594
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000595void JitCodeCache::CopyInlineCacheInto(
596 const InlineCache& ic,
597 /*out*/StackHandleScope<InlineCache::kIndividualCacheSize>* classes) {
598 static_assert(arraysize(ic.classes_) == InlineCache::kIndividualCacheSize);
599 DCHECK_EQ(classes->NumberOfReferences(), InlineCache::kIndividualCacheSize);
600 DCHECK_EQ(classes->RemainingSlots(), InlineCache::kIndividualCacheSize);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000601 WaitUntilInlineCacheAccessible(Thread::Current());
602 // Note that we don't need to lock `lock_` here, the compiler calling
603 // this method has already ensured the inline cache will not be deleted.
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000604 for (const GcRoot<mirror::Class>& root : ic.classes_) {
605 mirror::Class* object = root.Read();
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000606 if (object != nullptr) {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000607 DCHECK_NE(classes->RemainingSlots(), 0u);
608 classes->NewHandle(object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000609 }
610 }
611}
612
David Srbeckye36e7f22018-11-14 14:21:23 +0000613static void ClearMethodCounter(ArtMethod* method, bool was_warm)
614 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf044c222017-05-31 15:27:54 -0700615 if (was_warm) {
Vladimir Markoc945e0d2018-07-18 17:26:45 +0100616 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700617 }
Nicolas Geoffray58f916c2021-11-15 14:02:07 +0000618 method->ResetCounter(Runtime::Current()->GetJITOptions()->GetWarmupThreshold());
Nicolas Geoffray61673dc2021-11-06 13:58:31 +0000619 // We add one sample so that the profile knows that the method was executed at least once.
Vladimir Markoce131fe2021-10-26 20:03:35 +0000620 // This is required for layout purposes.
Nicolas Geoffray61673dc2021-11-06 13:58:31 +0000621 method->UpdateCounter(/* new_samples= */ 1);
Mathieu Chartierf044c222017-05-31 15:27:54 -0700622}
623
Alex Light33b7b5d2018-08-07 19:13:51 +0000624void JitCodeCache::WaitForPotentialCollectionToCompleteRunnable(Thread* self) {
625 while (collection_in_progress_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100626 Locks::jit_lock_->Unlock(self);
Alex Light33b7b5d2018-08-07 19:13:51 +0000627 {
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000628 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100629 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000630 WaitForPotentialCollectionToComplete(self);
631 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100632 Locks::jit_lock_->Lock(self);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100633 }
634}
635
David Srbeckyadb66f92019-10-10 12:59:43 +0000636bool JitCodeCache::Commit(Thread* self,
637 JitMemoryRegion* region,
638 ArtMethod* method,
639 ArrayRef<const uint8_t> reserved_code,
640 ArrayRef<const uint8_t> code,
641 ArrayRef<const uint8_t> reserved_data,
642 const std::vector<Handle<mirror::Object>>& roots,
643 ArrayRef<const uint8_t> stack_map,
David Srbecky41617b12020-03-18 21:19:06 +0000644 const std::vector<uint8_t>& debug_info,
645 bool is_full_debug_info,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100646 CompilationKind compilation_kind,
David Srbeckyadb66f92019-10-10 12:59:43 +0000647 bool has_should_deoptimize_flag,
Mythri Alle519ff8b2021-11-17 13:47:07 +0000648 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Santiago Aboy Solanes6cdabe12022-02-18 15:27:43 +0000649 DCHECK_IMPLIES(method->IsNative(), (compilation_kind != CompilationKind::kOsr));
Alex Light33b7b5d2018-08-07 19:13:51 +0000650
651 if (!method->IsNative()) {
652 // We need to do this before grabbing the lock_ because it needs to be able to see the string
653 // InternTable. Native methods do not have roots.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000654 DCheckRootsAreValid(roots, IsSharedRegion(*region));
Alex Light33b7b5d2018-08-07 19:13:51 +0000655 }
656
David Srbeckyadb66f92019-10-10 12:59:43 +0000657 const uint8_t* roots_data = reserved_data.data();
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100658 size_t root_table_size = ComputeRootTableSize(roots.size());
David Srbecky87fb0322019-08-20 10:34:02 +0100659 const uint8_t* stack_map_data = roots_data + root_table_size;
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100660
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100661 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000662 // We need to make sure that there will be no jit-gcs going on and wait for any ongoing one to
663 // finish.
664 WaitForPotentialCollectionToCompleteRunnable(self);
David Srbeckyadb66f92019-10-10 12:59:43 +0000665 const uint8_t* code_ptr = region->CommitCode(
666 reserved_code, code, stack_map_data, has_should_deoptimize_flag);
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100667 if (code_ptr == nullptr) {
David Srbeckyadb66f92019-10-10 12:59:43 +0000668 return false;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100669 }
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100670 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
671
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100672 // Commit roots and stack maps before updating the entry point.
David Srbeckyadb66f92019-10-10 12:59:43 +0000673 if (!region->CommitData(reserved_data, roots, stack_map)) {
674 return false;
Orion Hodsonaeb02232019-06-25 14:18:18 +0100675 }
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100676
Nicolas Geoffrayc473dc72020-07-03 15:04:21 +0100677 switch (compilation_kind) {
678 case CompilationKind::kOsr:
679 number_of_osr_compilations_++;
680 break;
681 case CompilationKind::kBaseline:
682 number_of_baseline_compilations_++;
683 break;
684 case CompilationKind::kOptimized:
685 number_of_optimized_compilations_++;
686 break;
687 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100688
David Srbecky41617b12020-03-18 21:19:06 +0000689 // We need to update the debug info before the entry point gets set.
690 // At the same time we want to do under JIT lock so that debug info and JIT maps are in sync.
691 if (!debug_info.empty()) {
692 // NB: Don't allow packing of full info since it would remove non-backtrace data.
693 AddNativeDebugInfoForJit(code_ptr, debug_info, /*allow_packing=*/ !is_full_debug_info);
694 }
695
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000696 // We need to update the entry point in the runnable state for the instrumentation.
697 {
Alex Light33b7b5d2018-08-07 19:13:51 +0000698 // The following needs to be guarded by cha_lock_ also. Otherwise it's possible that the
699 // compiled code is considered invalidated by some class linking, but below we still make the
700 // compiled code valid for the method. Need cha_lock_ for checking all single-implementation
701 // flags and register dependencies.
Mingyao Yang063fc772016-08-02 11:02:54 -0700702 MutexLock cha_mu(self, *Locks::cha_lock_);
703 bool single_impl_still_valid = true;
704 for (ArtMethod* single_impl : cha_single_implementation_list) {
705 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700706 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
707 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700708 single_impl_still_valid = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700709 ClearMethodCounter(method, /*was_warm=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700710 break;
711 }
712 }
713
714 // Discard the code if any single-implementation assumptions are now invalid.
Orion Hodson31492522019-06-18 12:13:49 +0100715 if (UNLIKELY(!single_impl_still_valid)) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700716 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
David Srbeckyadb66f92019-10-10 12:59:43 +0000717 return false;
Mingyao Yang063fc772016-08-02 11:02:54 -0700718 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000719 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800720 << "Should not be using cha on debuggable apps/runs!";
721
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100722 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mingyao Yang063fc772016-08-02 11:02:54 -0700723 for (ArtMethod* single_impl : cha_single_implementation_list) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100724 class_linker->GetClassHierarchyAnalysis()->AddDependency(single_impl, method, method_header);
Mingyao Yang063fc772016-08-02 11:02:54 -0700725 }
726
Vladimir Marko2196c652017-11-30 16:16:07 +0000727 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000728 auto it = jni_stubs_map_.find(JniStubKey(method));
729 DCHECK(it != jni_stubs_map_.end())
730 << "Entry inserted in NotifyCompilationOf() should be alive.";
731 JniStubData* data = &it->second;
732 DCHECK(ContainsElement(data->GetMethods(), method))
733 << "Entry inserted in NotifyCompilationOf() should contain this method.";
734 data->SetCode(code_ptr);
Vladimir Markocce414f2019-10-07 08:51:33 +0100735 data->UpdateEntryPoints(method_header->GetEntryPoint());
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100736 } else {
Nicolas Geoffray32384402019-07-17 20:06:44 +0100737 if (method->IsPreCompiled() && IsSharedRegion(*region)) {
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100738 zygote_map_.Put(code_ptr, method);
739 } else {
740 method_code_map_.Put(code_ptr, method);
741 }
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100742 if (compilation_kind == CompilationKind::kOsr) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000743 osr_code_map_.Put(method, code_ptr);
Vladimir Marko5115a4d2019-10-17 14:56:47 +0100744 } else if (NeedsClinitCheckBeforeCall(method) &&
745 !method->GetDeclaringClass()->IsVisiblyInitialized()) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100746 // This situation currently only occurs in the jit-zygote mode.
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100747 DCHECK(!garbage_collect_code_);
Nicolas Geoffray32384402019-07-17 20:06:44 +0100748 DCHECK(method->IsPreCompiled());
749 // The shared region can easily be queried. For the private region, we
750 // use a side map.
751 if (!IsSharedRegion(*region)) {
752 saved_compiled_methods_map_.Put(method, code_ptr);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100753 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000754 } else {
755 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
756 method, method_header->GetEntryPoint());
757 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000758 }
Nicolas Geoffrayde3e51d2019-11-28 16:29:55 +0000759 if (collection_in_progress_) {
760 // We need to update the live bitmap if there is a GC to ensure it sees this new
761 // code.
762 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
763 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000764 VLOG(jit)
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100765 << "JIT added (kind=" << compilation_kind << ") "
David Sehr709b0702016-10-13 09:12:37 -0700766 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000767 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
768 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
769 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700770 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
771 method_header->GetCodeSize());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000772 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100773
David Srbeckyadb66f92019-10-10 12:59:43 +0000774 return true;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100775}
776
777size_t JitCodeCache::CodeCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100778 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000779 return CodeCacheSizeLocked();
780}
781
Orion Hodsoneced6922017-06-01 10:54:28 +0100782bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000783 // This function is used only for testing and only with non-native methods.
784 CHECK(!method->IsNative());
785
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100786 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +0100787
Vladimir Marko2196c652017-11-30 16:16:07 +0000788 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
789 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +0100790
791 if (!in_cache) {
792 return false;
793 }
794
Nicolas Geoffray61673dc2021-11-06 13:58:31 +0000795 ClearMethodCounter(method, /* was_warm= */ false);
Nicolas Geoffrayc8a694d2022-01-17 17:12:38 +0000796 Runtime::Current()->GetInstrumentation()->InitializeMethodsCode(method, /*aot_code=*/ nullptr);
Orion Hodsoneced6922017-06-01 10:54:28 +0100797 VLOG(jit)
798 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
799 << ArtMethod::PrettyMethod(method) << "@" << method
800 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
801 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
802 return true;
803}
804
Vladimir Marko2196c652017-11-30 16:16:07 +0000805bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
806 if (LIKELY(!method->IsNative())) {
Nicolas Geoffray095dc462020-08-17 16:40:28 +0100807 auto it = profiling_infos_.find(method);
808 if (it != profiling_infos_.end()) {
809 profiling_infos_.erase(it);
Vladimir Marko2196c652017-11-30 16:16:07 +0000810 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000811 }
812
813 bool in_cache = false;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100814 ScopedCodeCacheWrite ccw(private_region_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000815 if (UNLIKELY(method->IsNative())) {
816 auto it = jni_stubs_map_.find(JniStubKey(method));
817 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
818 in_cache = true;
819 if (it->second.GetMethods().empty()) {
820 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100821 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +0000822 }
823 jni_stubs_map_.erase(it);
824 } else {
825 it->first.UpdateShorty(it->second.GetMethods().front());
826 }
827 }
828 } else {
829 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
830 if (it->second == method) {
831 in_cache = true;
832 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100833 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +0000834 }
David Srbecky41617b12020-03-18 21:19:06 +0000835 VLOG(jit) << "JIT removed " << it->second->PrettyMethod() << ": " << it->first;
Vladimir Marko2196c652017-11-30 16:16:07 +0000836 it = method_code_map_.erase(it);
837 } else {
838 ++it;
839 }
840 }
841
842 auto osr_it = osr_code_map_.find(method);
843 if (osr_it != osr_code_map_.end()) {
844 osr_code_map_.erase(osr_it);
845 }
846 }
847
848 return in_cache;
849}
850
Alex Lightdba61482016-12-21 08:20:29 -0800851// This notifies the code cache that the given method has been redefined and that it should remove
852// any cached information it has on the method. All threads must be suspended before calling this
853// method. The compiled code for the method (if there is any) must not be in any threads call stack.
854void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100855 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700856 RemoveMethodLocked(method, /* release_memory= */ true);
Alex Lightdba61482016-12-21 08:20:29 -0800857}
858
859// This invalidates old_method. Once this function returns one can no longer use old_method to
860// execute code unless it is fixed up. This fixup will happen later in the process of installing a
861// class redefinition.
862// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
863// shouldn't be used since it is no longer logically in the jit code cache.
864// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
865void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100866 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +0000867 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000868 // Update methods in jni_stubs_map_.
869 for (auto& entry : jni_stubs_map_) {
870 JniStubData& data = entry.second;
871 data.MoveObsoleteMethod(old_method, new_method);
872 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000873 return;
874 }
Alex Lightdba61482016-12-21 08:20:29 -0800875 // Update method_code_map_ to point to the new method.
876 for (auto& it : method_code_map_) {
877 if (it.second == old_method) {
878 it.second = new_method;
879 }
880 }
881 // Update osr_code_map_ to point to the new method.
882 auto code_map = osr_code_map_.find(old_method);
883 if (code_map != osr_code_map_.end()) {
884 osr_code_map_.Put(new_method, code_map->second);
885 osr_code_map_.erase(old_method);
886 }
887}
888
Alex Lightb28e3042020-03-06 13:02:46 -0800889void JitCodeCache::TransitionToDebuggable() {
Nicolas Geoffrayc76232e2020-03-18 11:23:33 +0000890 // Check that none of our methods have an entrypoint in the zygote exec
891 // space (this should be taken care of by
892 // ClassLinker::UpdateEntryPointsClassVisitor.
Alex Lightb28e3042020-03-06 13:02:46 -0800893 {
894 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayc76232e2020-03-18 11:23:33 +0000895 if (kIsDebugBuild) {
896 for (const auto& it : method_code_map_) {
897 ArtMethod* method = it.second;
898 DCHECK(!method->IsPreCompiled());
899 DCHECK(!IsInZygoteExecSpace(method->GetEntryPointFromQuickCompiledCode()));
Nicolas Geoffrayfc47d6b2020-03-11 15:05:43 +0000900 }
Alex Lightb28e3042020-03-06 13:02:46 -0800901 }
Nicolas Geoffrayfc47d6b2020-03-11 15:05:43 +0000902 // Not strictly necessary, but this map is useless now.
903 saved_compiled_methods_map_.clear();
Alex Lightb28e3042020-03-06 13:02:46 -0800904 }
Nicolas Geoffrayc76232e2020-03-18 11:23:33 +0000905 if (kIsDebugBuild) {
906 for (const auto& entry : zygote_map_) {
907 ArtMethod* method = entry.method;
908 if (method != nullptr) {
909 DCHECK(!method->IsPreCompiled());
910 DCHECK(!IsInZygoteExecSpace(method->GetEntryPointFromQuickCompiledCode()));
911 }
Nicolas Geoffrayfc47d6b2020-03-11 15:05:43 +0000912 }
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000913 }
914}
915
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000916size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +0100917 return GetCurrentRegion()->GetUsedMemoryForCode();
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100918}
919
920size_t JitCodeCache::DataCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100921 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000922 return DataCacheSizeLocked();
923}
924
925size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +0100926 return GetCurrentRegion()->GetUsedMemoryForData();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800927}
928
David Srbeckyadb66f92019-10-10 12:59:43 +0000929bool JitCodeCache::Reserve(Thread* self,
930 JitMemoryRegion* region,
931 size_t code_size,
932 size_t stack_map_size,
933 size_t number_of_roots,
934 ArtMethod* method,
935 /*out*/ArrayRef<const uint8_t>* reserved_code,
936 /*out*/ArrayRef<const uint8_t>* reserved_data) {
937 code_size = OatQuickMethodHeader::InstructionAlignedSize() + code_size;
938 size_t data_size = RoundUp(ComputeRootTableSize(number_of_roots) + stack_map_size, sizeof(void*));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000939
David Srbeckyadb66f92019-10-10 12:59:43 +0000940 const uint8_t* code;
941 const uint8_t* data;
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100942 while (true) {
943 bool at_max_capacity = false;
David Srbeckyadb66f92019-10-10 12:59:43 +0000944 {
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000945 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
David Srbeckyadb66f92019-10-10 12:59:43 +0000946 MutexLock mu(self, *Locks::jit_lock_);
947 WaitForPotentialCollectionToComplete(self);
948 ScopedCodeCacheWrite ccw(*region);
949 code = region->AllocateCode(code_size);
950 data = region->AllocateData(data_size);
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100951 at_max_capacity = IsAtMaxCapacity();
David Srbeckyadb66f92019-10-10 12:59:43 +0000952 }
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100953 if (code != nullptr && data != nullptr) {
954 break;
David Srbeckyadb66f92019-10-10 12:59:43 +0000955 }
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100956 Free(self, region, code, data);
957 if (at_max_capacity) {
958 VLOG(jit) << "JIT failed to allocate code of size "
959 << PrettySize(code_size)
960 << ", and data of size "
961 << PrettySize(data_size);
962 return false;
963 }
964 // Run a code cache collection and try again.
965 GarbageCollectCache(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100966 }
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100967
David Srbeckyadb66f92019-10-10 12:59:43 +0000968 *reserved_code = ArrayRef<const uint8_t>(code, code_size);
969 *reserved_data = ArrayRef<const uint8_t>(data, data_size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100970
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100971 MutexLock mu(self, *Locks::jit_lock_);
David Srbeckyadb66f92019-10-10 12:59:43 +0000972 histogram_code_memory_use_.AddValue(code_size);
973 if (code_size > kCodeSizeLogThreshold) {
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000974 LOG(INFO) << "JIT allocated "
David Srbeckyadb66f92019-10-10 12:59:43 +0000975 << PrettySize(code_size)
976 << " for compiled code of "
977 << ArtMethod::PrettyMethod(method);
978 }
979 histogram_stack_map_memory_use_.AddValue(data_size);
980 if (data_size > kStackMapSizeLogThreshold) {
981 LOG(INFO) << "JIT allocated "
982 << PrettySize(data_size)
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000983 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700984 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800985 }
David Srbeckyadb66f92019-10-10 12:59:43 +0000986 return true;
987}
988
989void JitCodeCache::Free(Thread* self,
990 JitMemoryRegion* region,
991 const uint8_t* code,
992 const uint8_t* data) {
993 MutexLock mu(self, *Locks::jit_lock_);
994 ScopedCodeCacheWrite ccw(*region);
David Srbecky30fd8512020-02-20 20:27:58 +0000995 FreeLocked(region, code, data);
996}
997
998void JitCodeCache::FreeLocked(JitMemoryRegion* region, const uint8_t* code, const uint8_t* data) {
David Srbeckyadb66f92019-10-10 12:59:43 +0000999 if (code != nullptr) {
David Srbecky30fd8512020-02-20 20:27:58 +00001000 RemoveNativeDebugInfoForJit(reinterpret_cast<const void*>(FromAllocationToCode(code)));
David Srbeckyadb66f92019-10-10 12:59:43 +00001001 region->FreeCode(code);
1002 }
1003 if (data != nullptr) {
1004 region->FreeData(data);
1005 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001006}
1007
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001008class MarkCodeClosure final : public Closure {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001009 public:
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001010 MarkCodeClosure(JitCodeCache* code_cache, CodeCacheBitmap* bitmap, Barrier* barrier)
1011 : code_cache_(code_cache), bitmap_(bitmap), barrier_(barrier) {}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001012
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001013 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001014 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001015 DCHECK(thread == Thread::Current() || thread->IsSuspended());
Andreas Gampec7d878d2018-11-19 18:42:06 +00001016 StackVisitor::WalkStack(
1017 [&](const art::StackVisitor* stack_visitor) {
1018 const OatQuickMethodHeader* method_header =
1019 stack_visitor->GetCurrentOatQuickMethodHeader();
1020 if (method_header == nullptr) {
1021 return true;
1022 }
1023 const void* code = method_header->GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001024 if (code_cache_->ContainsPc(code) && !code_cache_->IsInZygoteExecSpace(code)) {
Andreas Gampec7d878d2018-11-19 18:42:06 +00001025 // Use the atomic set version, as multiple threads are executing this code.
1026 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1027 }
1028 return true;
1029 },
1030 thread,
1031 /* context= */ nullptr,
1032 art::StackVisitor::StackWalkKind::kSkipInlinedFrames);
1033
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001034 if (kIsDebugBuild) {
1035 // The stack walking code queries the side instrumentation stack if it
1036 // sees an instrumentation exit pc, so the JIT code of methods in that stack
Orion Hodson853fc2e2020-07-27 17:01:44 +01001037 // must have been seen. We check this below.
Nicolas Geoffraye91e7952020-01-23 10:15:56 +00001038 for (const auto& it : *thread->GetInstrumentationStack()) {
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001039 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1040 // its stack frame, it is not the method owning return_pc_. We just pass null to
1041 // LookupMethodHeader: the method is only checked against in debug builds.
1042 OatQuickMethodHeader* method_header =
Nicolas Geoffraye91e7952020-01-23 10:15:56 +00001043 code_cache_->LookupMethodHeader(it.second.return_pc_, /* method= */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001044 if (method_header != nullptr) {
1045 const void* code = method_header->GetCode();
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001046 CHECK(bitmap_->Test(FromCodeToAllocation(code)));
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001047 }
1048 }
1049 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001050 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001051 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001052
1053 private:
1054 JitCodeCache* const code_cache_;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001055 CodeCacheBitmap* const bitmap_;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001056 Barrier* const barrier_;
1057};
1058
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001059void JitCodeCache::NotifyCollectionDone(Thread* self) {
1060 collection_in_progress_ = false;
1061 lock_cond_.Broadcast(self);
1062}
1063
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001064void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1065 Barrier barrier(0);
1066 size_t threads_running_checkpoint = 0;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001067 MarkCodeClosure closure(this, GetLiveBitmap(), &barrier);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001068 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1069 // Now that we have run our checkpoint, move to a suspended state and wait
1070 // for other threads to run the checkpoint.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001071 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001072 if (threads_running_checkpoint != 0) {
1073 barrier.Increment(self, threads_running_checkpoint);
1074 }
1075}
1076
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +01001077bool JitCodeCache::IsAtMaxCapacity() const {
1078 return private_region_.GetCurrentCapacity() == private_region_.GetMaxCapacity();
1079}
1080
Nicolas Geoffray35122442016-03-02 12:05:30 +00001081bool JitCodeCache::ShouldDoFullCollection() {
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +01001082 if (IsAtMaxCapacity()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001083 // Always do a full collection when the code cache is full.
1084 return true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001085 } else if (private_region_.GetCurrentCapacity() < kReservedCapacity) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001086 // Always do partial collection when the code cache size is below the reserved
1087 // capacity.
1088 return false;
1089 } else if (last_collection_increased_code_cache_) {
1090 // This time do a full collection.
1091 return true;
1092 } else {
1093 // This time do a partial collection.
1094 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001095 }
1096}
1097
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001098void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001099 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001100 // Wait for an existing collection, or let everyone know we are starting one.
1101 {
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001102 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001103 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001104 if (!garbage_collect_code_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001105 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001106 return;
1107 } else if (WaitForPotentialCollectionToComplete(self)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001108 return;
1109 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001110 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001111 live_bitmap_.reset(CodeCacheBitmap::Create(
1112 "code-cache-bitmap",
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001113 reinterpret_cast<uintptr_t>(private_region_.GetExecPages()->Begin()),
1114 reinterpret_cast<uintptr_t>(
1115 private_region_.GetExecPages()->Begin() + private_region_.GetCurrentCapacity() / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001116 collection_in_progress_ = true;
1117 }
1118 }
1119
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001120 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001121 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001122 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001123
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001124 bool do_full_collection = false;
1125 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001126 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001127 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001128 }
1129
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001130 VLOG(jit) << "Do "
1131 << (do_full_collection ? "full" : "partial")
1132 << " code cache collection, code="
1133 << PrettySize(CodeCacheSize())
1134 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001135
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001136 DoCollection(self, /* collect_profiling_info= */ do_full_collection);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001137
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001138 VLOG(jit) << "After code cache collection, code="
1139 << PrettySize(CodeCacheSize())
1140 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001141
1142 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001143 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001144
1145 // Increase the code cache only when we do partial collections.
1146 // TODO: base this strategy on how full the code cache is?
1147 if (do_full_collection) {
1148 last_collection_increased_code_cache_ = false;
1149 } else {
1150 last_collection_increased_code_cache_ = true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001151 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001152 }
1153
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001154 bool next_collection_will_be_full = ShouldDoFullCollection();
1155
1156 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001157 if (next_collection_will_be_full) {
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001158 for (auto it : profiling_infos_) {
Nicolas Geoffray9e598902021-11-19 14:53:07 +00001159 it.second->ResetCounter();
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001160 }
1161
Vladimir Marko2196c652017-11-30 16:16:07 +00001162 // Change entry points of native methods back to the GenericJNI entrypoint.
1163 for (const auto& entry : jni_stubs_map_) {
1164 const JniStubData& data = entry.second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001165 if (!data.IsCompiled() || IsInZygoteExecSpace(data.GetCode())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001166 continue;
1167 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001168 const OatQuickMethodHeader* method_header =
1169 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1170 for (ArtMethod* method : data.GetMethods()) {
1171 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1172 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
Nicolas Geoffray61673dc2021-11-06 13:58:31 +00001173 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1174 method->SetHotCounter();
Vladimir Marko2196c652017-11-30 16:16:07 +00001175 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1176 }
1177 }
1178 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001179 }
1180 live_bitmap_.reset(nullptr);
1181 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001182 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001183 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001184 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001185}
1186
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001187void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001188 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001189 std::unordered_set<OatQuickMethodHeader*> method_headers;
1190 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001191 MutexLock mu(self, *Locks::jit_lock_);
Mingyao Yang063fc772016-08-02 11:02:54 -07001192 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001193 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1194 JniStubData* data = &it->second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001195 if (IsInZygoteExecSpace(data->GetCode()) ||
1196 !data->IsCompiled() ||
1197 GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001198 ++it;
1199 } else {
1200 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
David Srbecky41617b12020-03-18 21:19:06 +00001201 for (ArtMethod* method : data->GetMethods()) {
1202 VLOG(jit) << "JIT removed (JNI) " << method->PrettyMethod() << ": " << data->GetCode();
1203 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001204 it = jni_stubs_map_.erase(it);
1205 }
1206 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001207 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1208 const void* code_ptr = it->first;
1209 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001210 if (IsInZygoteExecSpace(code_ptr) || GetLiveBitmap()->Test(allocation)) {
Mingyao Yang063fc772016-08-02 11:02:54 -07001211 ++it;
1212 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001213 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1214 method_headers.insert(header);
David Srbecky41617b12020-03-18 21:19:06 +00001215 VLOG(jit) << "JIT removed " << it->second->PrettyMethod() << ": " << it->first;
Mingyao Yang063fc772016-08-02 11:02:54 -07001216 it = method_code_map_.erase(it);
1217 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001218 }
David Srbecky521644b2020-03-21 13:17:52 +00001219 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001220 }
1221}
1222
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001223bool JitCodeCache::GetGarbageCollectCode() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001224 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001225 return garbage_collect_code_;
1226}
1227
1228void JitCodeCache::SetGarbageCollectCode(bool value) {
1229 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001230 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray9c7b4f12020-08-03 15:22:59 +01001231 // Update the flag while holding the lock to ensure no thread will try to GC.
1232 garbage_collect_code_ = value;
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001233}
1234
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001235void JitCodeCache::RemoveMethodBeingCompiled(ArtMethod* method, CompilationKind kind) {
1236 DCHECK(IsMethodBeingCompiled(method, kind));
1237 switch (kind) {
1238 case CompilationKind::kOsr:
1239 current_osr_compilations_.erase(method);
1240 break;
1241 case CompilationKind::kBaseline:
1242 current_baseline_compilations_.erase(method);
1243 break;
1244 case CompilationKind::kOptimized:
1245 current_optimized_compilations_.erase(method);
1246 break;
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001247 }
1248}
1249
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001250void JitCodeCache::AddMethodBeingCompiled(ArtMethod* method, CompilationKind kind) {
1251 DCHECK(!IsMethodBeingCompiled(method, kind));
1252 switch (kind) {
1253 case CompilationKind::kOsr:
1254 current_osr_compilations_.insert(method);
1255 break;
1256 case CompilationKind::kBaseline:
1257 current_baseline_compilations_.insert(method);
1258 break;
1259 case CompilationKind::kOptimized:
1260 current_optimized_compilations_.insert(method);
1261 break;
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001262 }
1263}
1264
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001265bool JitCodeCache::IsMethodBeingCompiled(ArtMethod* method, CompilationKind kind) {
1266 switch (kind) {
1267 case CompilationKind::kOsr:
1268 return ContainsElement(current_osr_compilations_, method);
1269 case CompilationKind::kBaseline:
1270 return ContainsElement(current_baseline_compilations_, method);
1271 case CompilationKind::kOptimized:
1272 return ContainsElement(current_optimized_compilations_, method);
1273 }
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001274}
1275
1276bool JitCodeCache::IsMethodBeingCompiled(ArtMethod* method) {
1277 return ContainsElement(current_optimized_compilations_, method) ||
1278 ContainsElement(current_osr_compilations_, method) ||
1279 ContainsElement(current_baseline_compilations_, method);
1280}
1281
Nicolas Geoffray9e598902021-11-19 14:53:07 +00001282ProfilingInfo* JitCodeCache::GetProfilingInfo(ArtMethod* method, Thread* self) {
1283 MutexLock mu(self, *Locks::jit_lock_);
1284 DCHECK(IsMethodBeingCompiled(method))
1285 << "GetProfilingInfo should only be called when the method is being compiled";
1286 auto it = profiling_infos_.find(method);
1287 if (it == profiling_infos_.end()) {
1288 return nullptr;
1289 }
1290 return it->second;
1291}
1292
1293void JitCodeCache::ResetHotnessCounter(ArtMethod* method, Thread* self) {
1294 MutexLock mu(self, *Locks::jit_lock_);
1295 auto it = profiling_infos_.find(method);
1296 DCHECK(it != profiling_infos_.end());
1297 it->second->ResetCounter();
1298}
1299
1300
Nicolas Geoffray35122442016-03-02 12:05:30 +00001301void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001302 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001303 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001304 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001305
Nicolas Geoffray1a277a62020-07-31 16:07:17 +01001306 // Update to interpreter the methods that have baseline entrypoints and whose baseline
Nicolas Geoffray9e598902021-11-19 14:53:07 +00001307 // hotness count hasn't changed.
Nicolas Geoffray1a277a62020-07-31 16:07:17 +01001308 // Note that these methods may be in thread stack or concurrently revived
1309 // between. That's OK, as the thread executing it will mark it.
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00001310 uint16_t warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001311 for (auto it : profiling_infos_) {
1312 ProfilingInfo* info = it.second;
Nicolas Geoffray9e598902021-11-19 14:53:07 +00001313 if (!info->CounterHasChanged()) {
Nicolas Geoffray1a277a62020-07-31 16:07:17 +01001314 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1315 if (ContainsPc(entry_point)) {
1316 OatQuickMethodHeader* method_header =
1317 OatQuickMethodHeader::FromEntryPoint(entry_point);
1318 if (CodeInfo::IsBaseline(method_header->GetOptimizedCodeInfoPtr())) {
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00001319 info->GetMethod()->ResetCounter(warmup_threshold);
Nicolas Geoffrayc8a694d2022-01-17 17:12:38 +00001320 Runtime::Current()->GetInstrumentation()->InitializeMethodsCode(
1321 info->GetMethod(), /*aot_code=*/ nullptr);
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001322 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001323 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001324 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001325 }
Nicolas Geoffray1a277a62020-07-31 16:07:17 +01001326 // TODO: collect profiling info
1327 // TODO: collect optimized code
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001328
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001329 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1330 // an entry point is either:
1331 // - an osr compiled code, that will be removed if not in a thread call stack.
1332 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001333 for (const auto& entry : jni_stubs_map_) {
1334 const JniStubData& data = entry.second;
1335 const void* code_ptr = data.GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001336 if (IsInZygoteExecSpace(code_ptr)) {
1337 continue;
1338 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001339 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1340 for (ArtMethod* method : data.GetMethods()) {
1341 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1342 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1343 break;
1344 }
1345 }
1346 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001347 for (const auto& it : method_code_map_) {
1348 ArtMethod* method = it.second;
1349 const void* code_ptr = it.first;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001350 if (IsInZygoteExecSpace(code_ptr)) {
1351 continue;
1352 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001353 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1354 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1355 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1356 }
1357 }
1358
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001359 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001360 // on thread stacks).
1361 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001362 }
1363
1364 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001365 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001366
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001367 // At this point, mutator threads are still running, and entrypoints of methods can
1368 // change. We do know they cannot change to a code cache entry that is not marked,
1369 // therefore we can safely remove those entries.
1370 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001371
Nicolas Geoffray35122442016-03-02 12:05:30 +00001372 if (collect_profiling_info) {
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001373 // TODO: Collect unused profiling infos.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001374 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001375}
1376
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001377OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001378 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1379 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001380 // On Thumb-2, the pc is offset by one.
1381 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001382 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001383 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1384 return nullptr;
1385 }
1386
Vladimir Marko2196c652017-11-30 16:16:07 +00001387 if (!kIsDebugBuild) {
1388 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1389 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001390 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001391
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001392 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001393 OatQuickMethodHeader* method_header = nullptr;
1394 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1395 if (method != nullptr && UNLIKELY(method->IsNative())) {
1396 auto it = jni_stubs_map_.find(JniStubKey(method));
1397 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1398 return nullptr;
1399 }
1400 const void* code_ptr = it->second.GetCode();
1401 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1402 if (!method_header->Contains(pc)) {
1403 return nullptr;
1404 }
1405 } else {
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001406 if (shared_region_.IsInExecSpace(reinterpret_cast<const void*>(pc))) {
1407 const void* code_ptr = zygote_map_.GetCodeFor(method, pc);
1408 if (code_ptr != nullptr) {
1409 return OatQuickMethodHeader::FromCodePointer(code_ptr);
1410 }
1411 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001412 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1413 if (it != method_code_map_.begin()) {
1414 --it;
1415 const void* code_ptr = it->first;
1416 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1417 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1418 found_method = it->second;
1419 }
1420 }
1421 if (method_header == nullptr && method == nullptr) {
1422 // Scan all compiled JNI stubs as well. This slow search is used only
1423 // for checks in debug build, for release builds the `method` is not null.
1424 for (auto&& entry : jni_stubs_map_) {
1425 const JniStubData& data = entry.second;
1426 if (data.IsCompiled() &&
1427 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1428 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1429 }
1430 }
1431 }
1432 if (method_header == nullptr) {
1433 return nullptr;
1434 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001435 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001436
1437 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Vladimir Markoeab02482019-05-09 10:28:17 +01001438 DCHECK_EQ(found_method, method)
1439 << ArtMethod::PrettyMethod(method) << " "
1440 << ArtMethod::PrettyMethod(found_method) << " "
David Sehr709b0702016-10-13 09:12:37 -07001441 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001442 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001443 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001444}
1445
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001446OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001447 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001448 auto it = osr_code_map_.find(method);
1449 if (it == osr_code_map_.end()) {
1450 return nullptr;
1451 }
1452 return OatQuickMethodHeader::FromCodePointer(it->second);
1453}
1454
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001455ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1456 ArtMethod* method,
Nicolas Geoffray60ef3992020-08-07 07:49:57 +00001457 const std::vector<uint32_t>& entries) {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001458 DCHECK(CanAllocateProfilingInfo());
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001459 ProfilingInfo* info = nullptr;
Nicolas Geoffray60ef3992020-08-07 07:49:57 +00001460 {
1461 MutexLock mu(self, *Locks::jit_lock_);
1462 info = AddProfilingInfoInternal(self, method, entries);
1463 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001464
Nicolas Geoffray60ef3992020-08-07 07:49:57 +00001465 if (info == nullptr) {
1466 GarbageCollectCache(self);
1467 MutexLock mu(self, *Locks::jit_lock_);
1468 info = AddProfilingInfoInternal(self, method, entries);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001469 }
1470 return info;
1471}
1472
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001473ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001474 ArtMethod* method,
1475 const std::vector<uint32_t>& entries) {
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001476 // Check whether some other thread has concurrently created it.
1477 auto it = profiling_infos_.find(method);
1478 if (it != profiling_infos_.end()) {
1479 return it->second;
1480 }
1481
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001482 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001483 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001484 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001485
David Srbecky87fb0322019-08-20 10:34:02 +01001486 const uint8_t* data = private_region_.AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001487 if (data == nullptr) {
1488 return nullptr;
1489 }
David Srbecky87fb0322019-08-20 10:34:02 +01001490 uint8_t* writable_data = private_region_.GetWritableDataAddress(data);
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001491 ProfilingInfo* info = new (writable_data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001492
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001493 profiling_infos_.Put(method, info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001494 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001495 return info;
1496}
1497
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001498void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001499 return shared_region_.OwnsSpace(mspace)
1500 ? shared_region_.MoreCore(mspace, increment)
1501 : private_region_.MoreCore(mspace, increment);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001502}
1503
Calin Juravle99629622016-04-19 16:33:46 +01001504void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001505 std::vector<ProfileMethodInfo>& methods) {
Nicolas Geoffray1afdfe62018-11-21 09:38:10 +00001506 Thread* self = Thread::Current();
1507 WaitUntilInlineCacheAccessible(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001508 MutexLock mu(self, *Locks::jit_lock_);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001509 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001510 for (auto it : profiling_infos_) {
1511 ProfilingInfo* info = it.second;
Calin Juravle99629622016-04-19 16:33:46 +01001512 ArtMethod* method = info->GetMethod();
1513 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001514 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1515 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001516 // Skip dex files which are not profiled.
1517 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001518 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001519 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001520
Nicolas Geoffray61673dc2021-11-06 13:58:31 +00001521 // If the method is still baseline compiled, don't save the inline caches.
Calin Juravlea39fd982017-05-18 10:15:52 -07001522 // They might be incomplete and cause unnecessary deoptimizations.
1523 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
Nicolas Geoffray61673dc2021-11-06 13:58:31 +00001524 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1525 if (ContainsPc(entry_point) &&
1526 CodeInfo::IsBaseline(
1527 OatQuickMethodHeader::FromEntryPoint(entry_point)->GetOptimizedCodeInfoPtr())) {
Calin Juravlea39fd982017-05-18 10:15:52 -07001528 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001529 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001530 continue;
1531 }
1532
Calin Juravle940eb0c2017-01-30 19:30:44 -08001533 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001534 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001535 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001536 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001537 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001538 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1539 mirror::Class* cls = cache.classes_[k].Read();
1540 if (cls == nullptr) {
1541 break;
1542 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001543
Calin Juravle13439f02017-02-21 01:17:21 -08001544 // Check if the receiver is in the boot class path or if it's in the
1545 // same class loader as the caller. If not, skip it, as there is not
1546 // much we can do during AOT.
1547 if (!cls->IsBootStrapClassLoaded() &&
1548 caller->GetClassLoader() != cls->GetClassLoader()) {
1549 is_missing_types = true;
1550 continue;
1551 }
1552
Calin Juravle4ca70a32017-02-21 16:22:24 -08001553 const DexFile* class_dex_file = nullptr;
1554 dex::TypeIndex type_index;
1555
1556 if (cls->GetDexCache() == nullptr) {
1557 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001558 // Make a best effort to find the type index in the method's dex file.
1559 // We could search all open dex files but that might turn expensive
1560 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001561 class_dex_file = dex_file;
1562 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1563 } else {
1564 class_dex_file = &(cls->GetDexFile());
1565 type_index = cls->GetDexTypeIndex();
1566 }
1567 if (!type_index.IsValid()) {
1568 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001569 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001570 continue;
1571 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001572 if (ContainsElement(dex_base_locations,
1573 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001574 // Only consider classes from the same apk (including multidex).
1575 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001576 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001577 } else {
1578 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001579 }
1580 }
1581 if (!profile_classes.empty()) {
1582 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001583 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001584 }
1585 }
1586 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001587 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001588 }
1589}
1590
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001591bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001592 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001593 return osr_code_map_.find(method) != osr_code_map_.end();
1594}
1595
Nicolas Geoffrayfc944762022-04-29 12:35:07 +00001596void JitCodeCache::VisitRoots(RootVisitor* visitor) {
Lokesh Gidra5316aea2022-02-18 15:26:30 -08001597 Thread* self = Thread::Current();
1598 gc::Heap* const heap = Runtime::Current()->GetHeap();
1599 if (heap->CurrentCollectorType() != gc::CollectorType::kCollectorTypeCMC
1600 || !heap->MarkCompactCollector()->IsCompacting(self)) {
1601 MutexLock mu(self, *Locks::jit_lock_);
1602 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
1603 for (ArtMethod* method : current_optimized_compilations_) {
1604 method->VisitRoots(root_visitor, kRuntimePointerSize);
1605 }
1606 for (ArtMethod* method : current_baseline_compilations_) {
1607 method->VisitRoots(root_visitor, kRuntimePointerSize);
1608 }
1609 for (ArtMethod* method : current_osr_compilations_) {
1610 method->VisitRoots(root_visitor, kRuntimePointerSize);
1611 }
Nicolas Geoffrayfc944762022-04-29 12:35:07 +00001612 }
1613}
1614
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001615bool JitCodeCache::NotifyCompilationOf(ArtMethod* method,
1616 Thread* self,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001617 CompilationKind compilation_kind,
Nicolas Geoffray60ef3992020-08-07 07:49:57 +00001618 bool prejit) {
Nicolas Geoffrayfc944762022-04-29 12:35:07 +00001619 if (kIsDebugBuild) {
1620 MutexLock mu(self, *Locks::jit_lock_);
1621 // Note: the compilation kind may have been adjusted after what was passed initially.
1622 // We really just want to check that the method is indeed being compiled.
1623 CHECK(IsMethodBeingCompiled(method));
1624 }
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001625 const void* existing_entry_point = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001626 if (compilation_kind != CompilationKind::kOsr && ContainsPc(existing_entry_point)) {
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001627 OatQuickMethodHeader* method_header =
1628 OatQuickMethodHeader::FromEntryPoint(existing_entry_point);
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001629 bool is_baseline = (compilation_kind == CompilationKind::kBaseline);
1630 if (CodeInfo::IsBaseline(method_header->GetOptimizedCodeInfoPtr()) == is_baseline) {
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001631 VLOG(jit) << "Not compiling "
1632 << method->PrettyMethod()
1633 << " because it has already been compiled"
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001634 << " kind=" << compilation_kind;
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001635 return false;
1636 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001637 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001638
Vladimir Marko5115a4d2019-10-17 14:56:47 +01001639 if (NeedsClinitCheckBeforeCall(method) && !prejit) {
1640 // We do not need a synchronization barrier for checking the visibly initialized status
1641 // or checking the initialized status just for requesting visible initialization.
1642 ClassStatus status = method->GetDeclaringClass()
1643 ->GetStatus<kDefaultVerifyFlags, /*kWithSynchronizationBarrier=*/ false>();
1644 if (status != ClassStatus::kVisiblyInitialized) {
1645 // Unless we're pre-jitting, we currently don't save the JIT compiled code if we cannot
1646 // update the entrypoint due to needing an initialization check.
1647 if (status == ClassStatus::kInitialized) {
1648 // Request visible initialization but do not block to allow compiling other methods.
1649 // Hopefully, this will complete by the time the method becomes hot again.
1650 Runtime::Current()->GetClassLinker()->MakeInitializedClassesVisiblyInitialized(
1651 self, /*wait=*/ false);
1652 }
1653 VLOG(jit) << "Not compiling "
1654 << method->PrettyMethod()
1655 << " because it has the resolution stub";
1656 // Give it a new chance to be hot.
1657 ClearMethodCounter(method, /*was_warm=*/ false);
1658 return false;
Vladimir Markocce414f2019-10-07 08:51:33 +01001659 }
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01001660 }
1661
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001662 if (compilation_kind == CompilationKind::kOsr) {
Nicolas Geoffray085f7402019-12-16 16:30:48 +00001663 MutexLock mu(self, *Locks::jit_lock_);
1664 if (osr_code_map_.find(method) != osr_code_map_.end()) {
1665 return false;
1666 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001667 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001668
Vladimir Marko2196c652017-11-30 16:16:07 +00001669 if (UNLIKELY(method->IsNative())) {
Nicolas Geoffray085f7402019-12-16 16:30:48 +00001670 MutexLock mu(self, *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001671 JniStubKey key(method);
1672 auto it = jni_stubs_map_.find(key);
1673 bool new_compilation = false;
1674 if (it == jni_stubs_map_.end()) {
1675 // Create a new entry to mark the stub as being compiled.
1676 it = jni_stubs_map_.Put(key, JniStubData{});
1677 new_compilation = true;
1678 }
1679 JniStubData* data = &it->second;
1680 data->AddMethod(method);
1681 if (data->IsCompiled()) {
1682 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1683 const void* entrypoint = method_header->GetEntryPoint();
1684 // Update also entrypoints of other methods held by the JniStubData.
1685 // We could simply update the entrypoint of `method` but if the last JIT GC has
1686 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1687 // as well change them back as this stub shall not be collected anyway and this
1688 // can avoid a few expensive GenericJNI calls.
Vladimir Markocce414f2019-10-07 08:51:33 +01001689 data->UpdateEntryPoints(entrypoint);
Vladimir Marko2196c652017-11-30 16:16:07 +00001690 if (collection_in_progress_) {
David Srbeckyc45b5892019-04-24 10:32:04 +01001691 if (!IsInZygoteExecSpace(data->GetCode())) {
1692 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1693 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001694 }
1695 }
1696 return new_compilation;
1697 } else {
Nicolas Geoffray8a608fa2021-11-29 14:47:21 +00001698 if (compilation_kind == CompilationKind::kBaseline) {
1699 DCHECK(CanAllocateProfilingInfo());
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001700 bool has_profiling_info = false;
1701 {
1702 MutexLock mu(self, *Locks::jit_lock_);
1703 has_profiling_info = (profiling_infos_.find(method) != profiling_infos_.end());
1704 }
1705 if (!has_profiling_info) {
1706 if (ProfilingInfo::Create(self, method) == nullptr) {
1707 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled baseline";
1708 ClearMethodCounter(method, /*was_warm=*/ false);
1709 return false;
1710 }
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001711 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001712 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001713 }
Nicolas Geoffrayfc944762022-04-29 12:35:07 +00001714 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001715}
1716
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001717ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001718 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001719 auto it = profiling_infos_.find(method);
1720 if (it == profiling_infos_.end()) {
1721 return nullptr;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001722 }
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001723 if (!it->second->IncrementInlineUse()) {
1724 // Overflow of inlining uses, just bail.
1725 return nullptr;
1726 }
1727 return it->second;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001728}
1729
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001730void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001731 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001732 auto it = profiling_infos_.find(method);
1733 DCHECK(it != profiling_infos_.end());
1734 it->second->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001735}
1736
Nicolas Geoffrayfc944762022-04-29 12:35:07 +00001737void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001738 DCHECK_EQ(Thread::Current(), self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001739 MutexLock mu(self, *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001740 if (UNLIKELY(method->IsNative())) {
1741 auto it = jni_stubs_map_.find(JniStubKey(method));
1742 DCHECK(it != jni_stubs_map_.end());
1743 JniStubData* data = &it->second;
1744 DCHECK(ContainsElement(data->GetMethods(), method));
1745 if (UNLIKELY(!data->IsCompiled())) {
1746 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1747 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
David Srbeckyadb66f92019-10-10 12:59:43 +00001748 } // else Commit() updated entrypoints of all methods in the JniStubData.
Vladimir Marko2196c652017-11-30 16:16:07 +00001749 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001750}
1751
Mythri Alle519ff8b2021-11-17 13:47:07 +00001752void JitCodeCache::InvalidateAllCompiledCode() {
1753 art::MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray60ef3992020-08-07 07:49:57 +00001754 VLOG(jit) << "Invalidating all compiled code";
1755 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1756 for (auto it : method_code_map_) {
Mythri Alle519ff8b2021-11-17 13:47:07 +00001757 ArtMethod* meth = it.second;
1758 // We were compiled, so we must be warm.
1759 ClearMethodCounter(meth, /*was_warm=*/true);
1760 if (meth->IsObsolete()) {
1761 linker->SetEntryPointsForObsoleteMethod(meth);
1762 } else {
Nicolas Geoffrayc8a694d2022-01-17 17:12:38 +00001763 Runtime::Current()->GetInstrumentation()->InitializeMethodsCode(meth, /*aot_code=*/ nullptr);
Mythri Alle519ff8b2021-11-17 13:47:07 +00001764 }
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001765 }
Mythri Alle322ef182022-08-16 06:40:02 +00001766
1767 for (auto it : zygote_map_) {
1768 if (it.method == nullptr) {
1769 continue;
1770 }
1771 if (it.method->IsPreCompiled()) {
1772 it.method->ClearPreCompiled();
1773 }
1774 Runtime::Current()->GetInstrumentation()->InitializeMethodsCode(it.method,
1775 /*aot_code=*/nullptr);
1776 }
1777
Nicolas Geoffray60ef3992020-08-07 07:49:57 +00001778 saved_compiled_methods_map_.clear();
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001779 osr_code_map_.clear();
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001780}
1781
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001782void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1783 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001784 DCHECK(!method->IsNative());
Alex Light2d441b12018-06-08 15:33:21 -07001785 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001786
Alex Light2d441b12018-06-08 15:33:21 -07001787 // Clear the method counter if we are running jitted code since we might want to jit this again in
1788 // the future.
1789 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001790 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001791 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayc8a694d2022-01-17 17:12:38 +00001792 Runtime::Current()->GetInstrumentation()->InitializeMethodsCode(method, /*aot_code=*/ nullptr);
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001793 ClearMethodCounter(method, /*was_warm=*/ true);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001794 } else {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001795 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001796 auto it = osr_code_map_.find(method);
1797 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1798 // Remove the OSR method, to avoid using it again.
1799 osr_code_map_.erase(it);
1800 }
1801 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001802
Nicolas Geoffray32384402019-07-17 20:06:44 +01001803 // In case the method was pre-compiled, clear that information so we
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001804 // can recompile it ourselves.
Nicolas Geoffray32384402019-07-17 20:06:44 +01001805 if (method->IsPreCompiled()) {
1806 method->ClearPreCompiled();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001807 }
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001808}
1809
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001810void JitCodeCache::Dump(std::ostream& os) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001811 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
David Srbecky44b977d2019-08-09 12:15:32 +01001812 os << "Current JIT code cache size (used / resident): "
1813 << GetCurrentRegion()->GetUsedMemoryForCode() / KB << "KB / "
1814 << GetCurrentRegion()->GetResidentMemoryForCode() / KB << "KB\n"
1815 << "Current JIT data cache size (used / resident): "
1816 << GetCurrentRegion()->GetUsedMemoryForData() / KB << "KB / "
1817 << GetCurrentRegion()->GetResidentMemoryForData() / KB << "KB\n";
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001818 if (!Runtime::Current()->IsZygote()) {
1819 os << "Zygote JIT code cache size (at point of fork): "
David Srbecky44b977d2019-08-09 12:15:32 +01001820 << shared_region_.GetUsedMemoryForCode() / KB << "KB / "
1821 << shared_region_.GetResidentMemoryForCode() / KB << "KB\n"
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001822 << "Zygote JIT data cache size (at point of fork): "
David Srbecky44b977d2019-08-09 12:15:32 +01001823 << shared_region_.GetUsedMemoryForData() / KB << "KB / "
1824 << shared_region_.GetResidentMemoryForData() / KB << "KB\n";
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001825 }
1826 os << "Current JIT mini-debug-info size: " << PrettySize(GetJitMiniDebugInfoMemUsage()) << "\n"
1827 << "Current JIT capacity: " << PrettySize(GetCurrentRegion()->GetCurrentCapacity()) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00001828 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001829 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
Nicolas Geoffrayc473dc72020-07-03 15:04:21 +01001830 << "Total number of JIT baseline compilations: " << number_of_baseline_compilations_ << "\n"
1831 << "Total number of JIT optimized compilations: " << number_of_optimized_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001832 << "Total number of JIT compilations for on stack replacement: "
1833 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001834 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001835 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1836 histogram_code_memory_use_.PrintMemoryUse(os);
1837 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001838}
1839
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001840void JitCodeCache::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffrayb08d5db2019-07-17 10:45:36 +01001841 Thread* self = Thread::Current();
1842
1843 // Remove potential tasks that have been inherited from the zygote.
1844 // We do this now and not in Jit::PostForkChildAction, as system server calls
1845 // JitCodeCache::PostForkChildAction first, and then does some code loading
1846 // that may result in new JIT tasks that we want to keep.
1847 ThreadPool* pool = Runtime::Current()->GetJit()->GetThreadPool();
1848 if (pool != nullptr) {
1849 pool->RemoveAllTasks(self);
1850 }
1851
1852 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray88f3fd92019-06-27 16:32:13 +01001853
1854 // Reset potential writable MemMaps inherited from the zygote. We never want
1855 // to write to them.
1856 shared_region_.ResetWritableMappings();
1857
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001858 if (is_zygote || Runtime::Current()->IsSafeMode()) {
1859 // Don't create a private region for a child zygote. Regions are usually map shared
1860 // (to satisfy dual-view), and we don't want children of a child zygote to inherit it.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001861 return;
1862 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001863
1864 // Reset all statistics to be specific to this process.
Nicolas Geoffrayc473dc72020-07-03 15:04:21 +01001865 number_of_baseline_compilations_ = 0;
1866 number_of_optimized_compilations_ = 0;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001867 number_of_osr_compilations_ = 0;
1868 number_of_collections_ = 0;
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001869 histogram_stack_map_memory_use_.Reset();
1870 histogram_code_memory_use_.Reset();
1871 histogram_profiling_info_memory_use_.Reset();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001872
1873 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
1874 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001875 std::string error_msg;
Nicolas Geoffray9c54e182019-06-18 10:42:52 +01001876 if (!private_region_.Initialize(initial_capacity,
1877 max_capacity,
1878 /* rwx_memory_allowed= */ !is_system_server,
1879 is_zygote,
1880 &error_msg)) {
1881 LOG(WARNING) << "Could not create private region after zygote fork: " << error_msg;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001882 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001883}
1884
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001885JitMemoryRegion* JitCodeCache::GetCurrentRegion() {
1886 return Runtime::Current()->IsZygote() ? &shared_region_ : &private_region_;
1887}
1888
David Srbecky41617b12020-03-18 21:19:06 +00001889void JitCodeCache::VisitAllMethods(const std::function<void(const void*, ArtMethod*)>& cb) {
1890 for (const auto& it : jni_stubs_map_) {
1891 const JniStubData& data = it.second;
1892 if (data.IsCompiled()) {
1893 for (ArtMethod* method : data.GetMethods()) {
1894 cb(data.GetCode(), method);
1895 }
1896 }
1897 }
1898 for (auto it : method_code_map_) { // Includes OSR methods.
1899 cb(it.first, it.second);
1900 }
1901 for (auto it : saved_compiled_methods_map_) {
1902 cb(it.second, it.first);
1903 }
1904 for (auto it : zygote_map_) {
1905 if (it.code_ptr != nullptr && it.method != nullptr) {
1906 cb(it.code_ptr, it.method);
1907 }
1908 }
1909}
1910
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001911void ZygoteMap::Initialize(uint32_t number_of_methods) {
1912 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
1913 // Allocate for 40-80% capacity. This will offer OK lookup times, and termination
1914 // cases.
1915 size_t capacity = RoundUpToPowerOfTwo(number_of_methods * 100 / 80);
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001916 const uint8_t* memory = region_->AllocateData(
1917 capacity * sizeof(Entry) + sizeof(ZygoteCompilationState));
1918 if (memory == nullptr) {
1919 LOG(WARNING) << "Could not allocate data for the zygote map";
1920 return;
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001921 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001922 const Entry* data = reinterpret_cast<const Entry*>(memory);
1923 region_->FillData(data, capacity, Entry { nullptr, nullptr });
1924 map_ = ArrayRef(data, capacity);
1925 compilation_state_ = reinterpret_cast<const ZygoteCompilationState*>(
1926 memory + capacity * sizeof(Entry));
1927 region_->WriteData(compilation_state_, ZygoteCompilationState::kInProgress);
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001928}
1929
1930const void* ZygoteMap::GetCodeFor(ArtMethod* method, uintptr_t pc) const {
1931 if (map_.empty()) {
1932 return nullptr;
1933 }
1934
1935 if (method == nullptr) {
1936 // Do a linear search. This should only be used in debug builds.
1937 CHECK(kIsDebugBuild);
1938 for (const Entry& entry : map_) {
1939 const void* code_ptr = entry.code_ptr;
1940 if (code_ptr != nullptr) {
1941 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1942 if (method_header->Contains(pc)) {
1943 return code_ptr;
1944 }
1945 }
1946 }
1947 return nullptr;
1948 }
1949
1950 std::hash<ArtMethod*> hf;
1951 size_t index = hf(method) & (map_.size() - 1u);
1952 size_t original_index = index;
1953 // Loop over the array: we know this loop terminates as we will either
1954 // encounter the given method, or a null entry. Both terminate the loop.
1955 // Note that the zygote may concurrently write new entries to the map. That's OK as the
1956 // map is never resized.
1957 while (true) {
1958 const Entry& entry = map_[index];
1959 if (entry.method == nullptr) {
1960 // Not compiled yet.
1961 return nullptr;
1962 }
1963 if (entry.method == method) {
1964 if (entry.code_ptr == nullptr) {
1965 // This is a race with the zygote which wrote the method, but hasn't written the
1966 // code. Just bail and wait for the next time we need the method.
1967 return nullptr;
1968 }
1969 if (pc != 0 && !OatQuickMethodHeader::FromCodePointer(entry.code_ptr)->Contains(pc)) {
1970 return nullptr;
1971 }
1972 return entry.code_ptr;
1973 }
1974 index = (index + 1) & (map_.size() - 1);
1975 DCHECK_NE(original_index, index);
1976 }
1977}
1978
1979void ZygoteMap::Put(const void* code, ArtMethod* method) {
1980 if (map_.empty()) {
1981 return;
1982 }
1983 CHECK(Runtime::Current()->IsZygote());
1984 std::hash<ArtMethod*> hf;
1985 size_t index = hf(method) & (map_.size() - 1);
1986 size_t original_index = index;
1987 // Because the size of the map is bigger than the number of methods that will
1988 // be added, we are guaranteed to find a free slot in the array, and
1989 // therefore for this loop to terminate.
1990 while (true) {
David Srbecky87fb0322019-08-20 10:34:02 +01001991 const Entry* entry = &map_[index];
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001992 if (entry->method == nullptr) {
1993 // Note that readers can read this memory concurrently, but that's OK as
1994 // we are writing pointers.
1995 region_->WriteData(entry, Entry { method, code });
1996 break;
1997 }
1998 index = (index + 1) & (map_.size() - 1);
1999 DCHECK_NE(original_index, index);
2000 }
2001 DCHECK_EQ(GetCodeFor(method), code);
2002}
2003
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002004} // namespace jit
2005} // namespace art