blob: 9d9a7d3bd41a65fe1c3eb86f49eca9e83c322456 [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"
Andreas Gampe88dbad32018-06-26 19:54:12 -070043#include "gc/allocator/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"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010060#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080061
62namespace art {
63namespace jit {
64
Nicolas Geoffray933330a2016-03-16 14:20:06 +000065static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
66static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
67
Vladimir Marko2196c652017-11-30 16:16:07 +000068class JitCodeCache::JniStubKey {
69 public:
70 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
71 : shorty_(method->GetShorty()),
72 is_static_(method->IsStatic()),
73 is_fast_native_(method->IsFastNative()),
74 is_critical_native_(method->IsCriticalNative()),
75 is_synchronized_(method->IsSynchronized()) {
76 DCHECK(!(is_fast_native_ && is_critical_native_));
77 }
78
79 bool operator<(const JniStubKey& rhs) const {
80 if (is_static_ != rhs.is_static_) {
81 return rhs.is_static_;
82 }
83 if (is_synchronized_ != rhs.is_synchronized_) {
84 return rhs.is_synchronized_;
85 }
86 if (is_fast_native_ != rhs.is_fast_native_) {
87 return rhs.is_fast_native_;
88 }
89 if (is_critical_native_ != rhs.is_critical_native_) {
90 return rhs.is_critical_native_;
91 }
92 return strcmp(shorty_, rhs.shorty_) < 0;
93 }
94
95 // Update the shorty to point to another method's shorty. Call this function when removing
96 // the method that references the old shorty from JniCodeData and not removing the entire
97 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
98 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
99 const char* shorty = method->GetShorty();
100 DCHECK_STREQ(shorty_, shorty);
101 shorty_ = shorty;
102 }
103
104 private:
105 // The shorty points to a DexFile data and may need to change
106 // to point to the same shorty in a different DexFile.
107 mutable const char* shorty_;
108
109 const bool is_static_;
110 const bool is_fast_native_;
111 const bool is_critical_native_;
112 const bool is_synchronized_;
113};
114
115class JitCodeCache::JniStubData {
116 public:
117 JniStubData() : code_(nullptr), methods_() {}
118
119 void SetCode(const void* code) {
120 DCHECK(code != nullptr);
121 code_ = code;
122 }
123
Vladimir Markocce414f2019-10-07 08:51:33 +0100124 void UpdateEntryPoints(const void* entrypoint) REQUIRES_SHARED(Locks::mutator_lock_) {
125 DCHECK(IsCompiled());
126 DCHECK(entrypoint == OatQuickMethodHeader::FromCodePointer(GetCode())->GetEntryPoint());
127 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
128 for (ArtMethod* m : GetMethods()) {
129 // Because `m` might be in the process of being deleted:
130 // - Call the dedicated method instead of the more generic UpdateMethodsCode
Vladimir Marko5115a4d2019-10-17 14:56:47 +0100131 // - Check the class status without a full read barrier; use ReadBarrier::IsMarked().
132 bool can_set_entrypoint = true;
133 if (NeedsClinitCheckBeforeCall(m)) {
134 // To avoid resurrecting an unreachable object, we must not use a full read
135 // barrier but we do not want to miss updating an entrypoint under common
136 // circumstances, i.e. during a GC the class becomes visibly initialized,
137 // the method becomes hot, we compile the thunk and want to update the
138 // entrypoint while the method's declaring class field still points to the
139 // from-space class object with the old status. Therefore we read the
140 // declaring class without a read barrier and check if it's already marked.
141 // If yes, we check the status of the to-space class object as intended.
142 // Otherwise, there is no to-space object and the from-space class object
143 // contains the most recent value of the status field; even if this races
144 // with another thread doing a read barrier and updating the status, that's
145 // no different from a race with a thread that just updates the status.
146 // Such race can happen only for the zygote method pre-compilation, as we
147 // otherwise compile only thunks for methods of visibly initialized classes.
148 ObjPtr<mirror::Class> klass = m->GetDeclaringClass<kWithoutReadBarrier>();
149 ObjPtr<mirror::Class> marked = ReadBarrier::IsMarked(klass.Ptr());
150 ObjPtr<mirror::Class> checked_klass = (marked != nullptr) ? marked : klass;
151 can_set_entrypoint = checked_klass->IsVisiblyInitialized();
152 }
153 if (can_set_entrypoint) {
Vladimir Markocce414f2019-10-07 08:51:33 +0100154 instrum->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
155 }
156 }
157 }
158
Vladimir Marko2196c652017-11-30 16:16:07 +0000159 const void* GetCode() const {
160 return code_;
161 }
162
163 bool IsCompiled() const {
164 return GetCode() != nullptr;
165 }
166
167 void AddMethod(ArtMethod* method) {
168 if (!ContainsElement(methods_, method)) {
169 methods_.push_back(method);
170 }
171 }
172
173 const std::vector<ArtMethod*>& GetMethods() const {
174 return methods_;
175 }
176
David Srbecky41617b12020-03-18 21:19:06 +0000177 void RemoveMethodsIn(const LinearAlloc& alloc) REQUIRES_SHARED(Locks::mutator_lock_) {
178 auto kept_end = std::partition(
Vladimir Marko2196c652017-11-30 16:16:07 +0000179 methods_.begin(),
180 methods_.end(),
David Srbecky41617b12020-03-18 21:19:06 +0000181 [&alloc](ArtMethod* method) { return !alloc.ContainsUnsafe(method); });
182 for (auto it = kept_end; it != methods_.end(); it++) {
183 VLOG(jit) << "JIT removed (JNI) " << (*it)->PrettyMethod() << ": " << code_;
184 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000185 methods_.erase(kept_end, methods_.end());
186 }
187
David Srbecky41617b12020-03-18 21:19:06 +0000188 bool RemoveMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000189 auto it = std::find(methods_.begin(), methods_.end(), method);
190 if (it != methods_.end()) {
David Srbecky41617b12020-03-18 21:19:06 +0000191 VLOG(jit) << "JIT removed (JNI) " << (*it)->PrettyMethod() << ": " << code_;
Vladimir Marko2196c652017-11-30 16:16:07 +0000192 methods_.erase(it);
193 return true;
194 } else {
195 return false;
196 }
197 }
198
199 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
200 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
201 }
202
203 private:
204 const void* code_;
205 std::vector<ArtMethod*> methods_;
206};
207
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000208JitCodeCache* JitCodeCache::Create(bool used_only_for_profile_data,
209 bool rwx_memory_allowed,
210 bool is_zygote,
211 std::string* error_msg) {
212 // Register for membarrier expedited sync core if JIT will be generating code.
213 if (!used_only_for_profile_data) {
214 if (art::membarrier(art::MembarrierCommand::kRegisterPrivateExpeditedSyncCore) != 0) {
215 // MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE ensures that CPU instruction pipelines are
216 // flushed and it's used when adding code to the JIT. The memory used by the new code may
217 // have just been released and, in theory, the old code could still be in a pipeline.
218 VLOG(jit) << "Kernel does not support membarrier sync-core";
219 }
220 }
221
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100222 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000223 // Check whether the provided max capacity in options is below 1GB.
224 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
225 // We need to have 32 bit offsets from method headers in code cache which point to things
226 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
227 // Ensure we're below 1 GB to be safe.
228 if (max_capacity > 1 * GB) {
229 std::ostringstream oss;
230 oss << "Maxium code cache capacity is limited to 1 GB, "
231 << PrettySize(max_capacity) << " is too big";
232 *error_msg = oss.str();
233 return nullptr;
234 }
235
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100236 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100237 JitMemoryRegion region;
238 if (!region.Initialize(initial_capacity,
239 max_capacity,
240 rwx_memory_allowed,
241 is_zygote,
242 error_msg)) {
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000243 return nullptr;
244 }
245
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100246 std::unique_ptr<JitCodeCache> jit_code_cache(new JitCodeCache());
247 if (is_zygote) {
248 // Zygote should never collect code to share the memory with the children.
249 jit_code_cache->garbage_collect_code_ = false;
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000250 jit_code_cache->shared_region_ = std::move(region);
251 } else {
252 jit_code_cache->private_region_ = std::move(region);
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100253 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000254
255 VLOG(jit) << "Created jit code cache: initial capacity="
256 << PrettySize(initial_capacity)
257 << ", maximum capacity="
258 << PrettySize(max_capacity);
259
260 return jit_code_cache.release();
261}
262
263JitCodeCache::JitCodeCache()
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100264 : is_weak_access_enabled_(true),
265 inline_cache_cond_("Jit inline cache condition variable", *Locks::jit_lock_),
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100266 zygote_map_(&shared_region_),
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100267 lock_cond_("Jit code cache condition variable", *Locks::jit_lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100268 collection_in_progress_(false),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000269 last_collection_increased_code_cache_(false),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100270 garbage_collect_code_(true),
Nicolas Geoffrayc473dc72020-07-03 15:04:21 +0100271 number_of_baseline_compilations_(0),
272 number_of_optimized_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000273 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000274 number_of_collections_(0),
275 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
276 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100277 histogram_profiling_info_memory_use_("Memory used for profiling info", 16) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800278}
279
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000280JitCodeCache::~JitCodeCache() {}
281
Alex Light280e6c32020-03-03 13:52:07 -0800282bool JitCodeCache::PrivateRegionContainsPc(const void* ptr) const {
283 return private_region_.IsInExecSpace(ptr);
284}
285
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100286bool JitCodeCache::ContainsPc(const void* ptr) const {
Alex Light280e6c32020-03-03 13:52:07 -0800287 return PrivateRegionContainsPc(ptr) || shared_region_.IsInExecSpace(ptr);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800288}
289
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000290bool JitCodeCache::ContainsMethod(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100291 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000292 if (UNLIKELY(method->IsNative())) {
293 auto it = jni_stubs_map_.find(JniStubKey(method));
294 if (it != jni_stubs_map_.end() &&
295 it->second.IsCompiled() &&
296 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000297 return true;
298 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000299 } else {
300 for (const auto& it : method_code_map_) {
301 if (it.second == method) {
302 return true;
303 }
304 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100305 if (zygote_map_.ContainsMethod(method)) {
306 return true;
307 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000308 }
309 return false;
310}
311
Vladimir Marko2196c652017-11-30 16:16:07 +0000312const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
313 DCHECK(method->IsNative());
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100314 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000315 auto it = jni_stubs_map_.find(JniStubKey(method));
316 if (it != jni_stubs_map_.end()) {
317 JniStubData& data = it->second;
318 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
319 return data.GetCode();
320 }
321 }
322 return nullptr;
323}
324
Nicolas Geoffray32384402019-07-17 20:06:44 +0100325const void* JitCodeCache::GetSavedEntryPointOfPreCompiledMethod(ArtMethod* method) {
Nicolas Geoffray4cbb51a2020-02-07 11:25:54 +0000326 if (method->IsPreCompiled()) {
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100327 const void* code_ptr = nullptr;
Nicolas Geoffray32384402019-07-17 20:06:44 +0100328 if (method->GetDeclaringClass()->GetClassLoader() == nullptr) {
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100329 code_ptr = zygote_map_.GetCodeFor(method);
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100330 } else {
Nicolas Geoffray32384402019-07-17 20:06:44 +0100331 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
332 auto it = saved_compiled_methods_map_.find(method);
333 if (it != saved_compiled_methods_map_.end()) {
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100334 code_ptr = it->second;
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100335 }
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100336 }
337 if (code_ptr != nullptr) {
338 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
339 return method_header->GetEntryPoint();
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100340 }
341 }
342 return nullptr;
343}
344
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100345bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
346 bool in_collection = false;
347 while (collection_in_progress_) {
348 in_collection = true;
349 lock_cond_.Wait(self);
350 }
351 return in_collection;
352}
353
354static uintptr_t FromCodeToAllocation(const void* code) {
Orion Hodsone764f382019-06-27 12:56:48 +0100355 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100356 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
357}
358
David Srbecky30fd8512020-02-20 20:27:58 +0000359static const void* FromAllocationToCode(const uint8_t* alloc) {
360 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
361 return reinterpret_cast<const void*>(alloc + RoundUp(sizeof(OatQuickMethodHeader), alignment));
362}
363
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000364static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
365 // The length of the table is stored just before the stack map (and therefore at the end of
366 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
367 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
368}
369
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000370static void DCheckRootsAreValid(const std::vector<Handle<mirror::Object>>& roots,
371 bool is_shared_region)
Alex Light3e36a9c2018-06-19 09:45:05 -0700372 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
373 if (!kIsDebugBuild) {
374 return;
375 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700376 // Put all roots in `roots_data`.
Vladimir Markoac3ac682018-09-20 11:01:43 +0100377 for (Handle<mirror::Object> object : roots) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700378 // Ensure the string is strongly interned. b/32995596
379 if (object->IsString()) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100380 ObjPtr<mirror::String> str = object->AsString();
Alex Light3e36a9c2018-06-19 09:45:05 -0700381 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
382 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
383 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000384 // Ensure that we don't put movable objects in the shared region.
385 if (is_shared_region) {
386 CHECK(!Runtime::Current()->GetHeap()->IsMovableObject(object.Get()));
387 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700388 }
389}
390
David Srbecky87fb0322019-08-20 10:34:02 +0100391static const uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000392 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
393 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
394 uint32_t roots = GetNumberOfRoots(data);
395 if (number_of_roots != nullptr) {
396 *number_of_roots = roots;
397 }
398 return data - ComputeRootTableSize(roots);
399}
400
401void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100402 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000403 for (const auto& entry : method_code_map_) {
404 uint32_t number_of_roots = 0;
David Srbecky87fb0322019-08-20 10:34:02 +0100405 const uint8_t* root_table = GetRootTable(entry.first, &number_of_roots);
406 uint8_t* roots_data = private_region_.IsInDataSpace(root_table)
407 ? private_region_.GetWritableDataAddress(root_table)
408 : shared_region_.GetWritableDataAddress(root_table);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000409 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
410 for (uint32_t i = 0; i < number_of_roots; ++i) {
411 // This does not need a read barrier because this is called by GC.
412 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffraye3f775b2019-12-04 14:41:52 +0000413 if (object == nullptr || object == Runtime::GetWeakClassSentinel()) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000414 // entry got deleted in a previous sweep.
Vladimir Markod355acf2019-03-21 17:09:40 +0000415 } else if (object->IsString<kDefaultVerifyFlags>()) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000416 mirror::Object* new_object = visitor->IsMarked(object);
417 // We know the string is marked because it's a strongly-interned string that
418 // is always alive. The IsMarked implementation of the CMS collector returns
419 // null for newly allocated objects, but we know those haven't moved. Therefore,
420 // only update the entry if we get a different non-null string.
421 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
422 // out of the weak access/creation pause. b/32167580
423 if (new_object != nullptr && new_object != object) {
424 DCHECK(new_object->IsString());
425 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 {
562 return kUseReadBarrier
563 ? 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 }
571 ScopedThreadSuspension sts(self, 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() {
585 DCHECK(!kUseReadBarrier);
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() {
591 DCHECK(!kUseReadBarrier);
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 }
618 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
619 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100620 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
621 // the warmup threshold is 1.
622 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
623 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700624}
625
Alex Light33b7b5d2018-08-07 19:13:51 +0000626void JitCodeCache::WaitForPotentialCollectionToCompleteRunnable(Thread* self) {
627 while (collection_in_progress_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100628 Locks::jit_lock_->Unlock(self);
Alex Light33b7b5d2018-08-07 19:13:51 +0000629 {
630 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100631 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000632 WaitForPotentialCollectionToComplete(self);
633 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100634 Locks::jit_lock_->Lock(self);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100635 }
636}
637
David Srbeckyadb66f92019-10-10 12:59:43 +0000638bool JitCodeCache::Commit(Thread* self,
639 JitMemoryRegion* region,
640 ArtMethod* method,
641 ArrayRef<const uint8_t> reserved_code,
642 ArrayRef<const uint8_t> code,
643 ArrayRef<const uint8_t> reserved_data,
644 const std::vector<Handle<mirror::Object>>& roots,
645 ArrayRef<const uint8_t> stack_map,
David Srbecky41617b12020-03-18 21:19:06 +0000646 const std::vector<uint8_t>& debug_info,
647 bool is_full_debug_info,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100648 CompilationKind compilation_kind,
David Srbeckyadb66f92019-10-10 12:59:43 +0000649 bool has_should_deoptimize_flag,
650 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100651 DCHECK(!method->IsNative() || (compilation_kind != CompilationKind::kOsr));
Alex Light33b7b5d2018-08-07 19:13:51 +0000652
653 if (!method->IsNative()) {
654 // We need to do this before grabbing the lock_ because it needs to be able to see the string
655 // InternTable. Native methods do not have roots.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000656 DCheckRootsAreValid(roots, IsSharedRegion(*region));
Alex Light33b7b5d2018-08-07 19:13:51 +0000657 }
658
David Srbeckyadb66f92019-10-10 12:59:43 +0000659 const uint8_t* roots_data = reserved_data.data();
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100660 size_t root_table_size = ComputeRootTableSize(roots.size());
David Srbecky87fb0322019-08-20 10:34:02 +0100661 const uint8_t* stack_map_data = roots_data + root_table_size;
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100662
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100663 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000664 // We need to make sure that there will be no jit-gcs going on and wait for any ongoing one to
665 // finish.
666 WaitForPotentialCollectionToCompleteRunnable(self);
David Srbeckyadb66f92019-10-10 12:59:43 +0000667 const uint8_t* code_ptr = region->CommitCode(
668 reserved_code, code, stack_map_data, has_should_deoptimize_flag);
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100669 if (code_ptr == nullptr) {
David Srbeckyadb66f92019-10-10 12:59:43 +0000670 return false;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100671 }
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100672 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
673
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100674 // Commit roots and stack maps before updating the entry point.
David Srbeckyadb66f92019-10-10 12:59:43 +0000675 if (!region->CommitData(reserved_data, roots, stack_map)) {
676 return false;
Orion Hodsonaeb02232019-06-25 14:18:18 +0100677 }
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100678
Nicolas Geoffrayc473dc72020-07-03 15:04:21 +0100679 switch (compilation_kind) {
680 case CompilationKind::kOsr:
681 number_of_osr_compilations_++;
682 break;
683 case CompilationKind::kBaseline:
684 number_of_baseline_compilations_++;
685 break;
686 case CompilationKind::kOptimized:
687 number_of_optimized_compilations_++;
688 break;
689 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100690
David Srbecky41617b12020-03-18 21:19:06 +0000691 // We need to update the debug info before the entry point gets set.
692 // At the same time we want to do under JIT lock so that debug info and JIT maps are in sync.
693 if (!debug_info.empty()) {
694 // NB: Don't allow packing of full info since it would remove non-backtrace data.
695 AddNativeDebugInfoForJit(code_ptr, debug_info, /*allow_packing=*/ !is_full_debug_info);
696 }
697
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000698 // We need to update the entry point in the runnable state for the instrumentation.
699 {
Alex Light33b7b5d2018-08-07 19:13:51 +0000700 // The following needs to be guarded by cha_lock_ also. Otherwise it's possible that the
701 // compiled code is considered invalidated by some class linking, but below we still make the
702 // compiled code valid for the method. Need cha_lock_ for checking all single-implementation
703 // flags and register dependencies.
Mingyao Yang063fc772016-08-02 11:02:54 -0700704 MutexLock cha_mu(self, *Locks::cha_lock_);
705 bool single_impl_still_valid = true;
706 for (ArtMethod* single_impl : cha_single_implementation_list) {
707 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700708 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
709 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700710 single_impl_still_valid = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700711 ClearMethodCounter(method, /*was_warm=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700712 break;
713 }
714 }
715
716 // Discard the code if any single-implementation assumptions are now invalid.
Orion Hodson31492522019-06-18 12:13:49 +0100717 if (UNLIKELY(!single_impl_still_valid)) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700718 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
David Srbeckyadb66f92019-10-10 12:59:43 +0000719 return false;
Mingyao Yang063fc772016-08-02 11:02:54 -0700720 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000721 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800722 << "Should not be using cha on debuggable apps/runs!";
723
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100724 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mingyao Yang063fc772016-08-02 11:02:54 -0700725 for (ArtMethod* single_impl : cha_single_implementation_list) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100726 class_linker->GetClassHierarchyAnalysis()->AddDependency(single_impl, method, method_header);
Mingyao Yang063fc772016-08-02 11:02:54 -0700727 }
728
Vladimir Marko2196c652017-11-30 16:16:07 +0000729 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000730 auto it = jni_stubs_map_.find(JniStubKey(method));
731 DCHECK(it != jni_stubs_map_.end())
732 << "Entry inserted in NotifyCompilationOf() should be alive.";
733 JniStubData* data = &it->second;
734 DCHECK(ContainsElement(data->GetMethods(), method))
735 << "Entry inserted in NotifyCompilationOf() should contain this method.";
736 data->SetCode(code_ptr);
Vladimir Markocce414f2019-10-07 08:51:33 +0100737 data->UpdateEntryPoints(method_header->GetEntryPoint());
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100738 } else {
Nicolas Geoffray32384402019-07-17 20:06:44 +0100739 if (method->IsPreCompiled() && IsSharedRegion(*region)) {
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100740 zygote_map_.Put(code_ptr, method);
741 } else {
742 method_code_map_.Put(code_ptr, method);
743 }
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100744 if (compilation_kind == CompilationKind::kOsr) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000745 osr_code_map_.Put(method, code_ptr);
Vladimir Marko5115a4d2019-10-17 14:56:47 +0100746 } else if (NeedsClinitCheckBeforeCall(method) &&
747 !method->GetDeclaringClass()->IsVisiblyInitialized()) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100748 // This situation currently only occurs in the jit-zygote mode.
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100749 DCHECK(!garbage_collect_code_);
Nicolas Geoffray32384402019-07-17 20:06:44 +0100750 DCHECK(method->IsPreCompiled());
751 // The shared region can easily be queried. For the private region, we
752 // use a side map.
753 if (!IsSharedRegion(*region)) {
754 saved_compiled_methods_map_.Put(method, code_ptr);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100755 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000756 } else {
757 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
758 method, method_header->GetEntryPoint());
759 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000760 }
Nicolas Geoffrayde3e51d2019-11-28 16:29:55 +0000761 if (collection_in_progress_) {
762 // We need to update the live bitmap if there is a GC to ensure it sees this new
763 // code.
764 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
765 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000766 VLOG(jit)
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100767 << "JIT added (kind=" << compilation_kind << ") "
David Sehr709b0702016-10-13 09:12:37 -0700768 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000769 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
770 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
771 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700772 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
773 method_header->GetCodeSize());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000774 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100775
David Srbeckyadb66f92019-10-10 12:59:43 +0000776 return true;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100777}
778
779size_t JitCodeCache::CodeCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100780 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000781 return CodeCacheSizeLocked();
782}
783
Orion Hodsoneced6922017-06-01 10:54:28 +0100784bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000785 // This function is used only for testing and only with non-native methods.
786 CHECK(!method->IsNative());
787
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100788 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +0100789
Vladimir Marko2196c652017-11-30 16:16:07 +0000790 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
791 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +0100792
793 if (!in_cache) {
794 return false;
795 }
796
David Srbeckye36e7f22018-11-14 14:21:23 +0000797 method->SetCounter(0);
Orion Hodsoneced6922017-06-01 10:54:28 +0100798 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
799 method, GetQuickToInterpreterBridge());
800 VLOG(jit)
801 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
802 << ArtMethod::PrettyMethod(method) << "@" << method
803 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
804 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
805 return true;
806}
807
Vladimir Marko2196c652017-11-30 16:16:07 +0000808bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
809 if (LIKELY(!method->IsNative())) {
Nicolas Geoffray095dc462020-08-17 16:40:28 +0100810 auto it = profiling_infos_.find(method);
811 if (it != profiling_infos_.end()) {
812 profiling_infos_.erase(it);
Vladimir Marko2196c652017-11-30 16:16:07 +0000813 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000814 }
815
816 bool in_cache = false;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100817 ScopedCodeCacheWrite ccw(private_region_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000818 if (UNLIKELY(method->IsNative())) {
819 auto it = jni_stubs_map_.find(JniStubKey(method));
820 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
821 in_cache = true;
822 if (it->second.GetMethods().empty()) {
823 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100824 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +0000825 }
826 jni_stubs_map_.erase(it);
827 } else {
828 it->first.UpdateShorty(it->second.GetMethods().front());
829 }
830 }
831 } else {
832 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
833 if (it->second == method) {
834 in_cache = true;
835 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100836 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +0000837 }
David Srbecky41617b12020-03-18 21:19:06 +0000838 VLOG(jit) << "JIT removed " << it->second->PrettyMethod() << ": " << it->first;
Vladimir Marko2196c652017-11-30 16:16:07 +0000839 it = method_code_map_.erase(it);
840 } else {
841 ++it;
842 }
843 }
844
845 auto osr_it = osr_code_map_.find(method);
846 if (osr_it != osr_code_map_.end()) {
847 osr_code_map_.erase(osr_it);
848 }
849 }
850
851 return in_cache;
852}
853
Alex Lightdba61482016-12-21 08:20:29 -0800854// This notifies the code cache that the given method has been redefined and that it should remove
855// any cached information it has on the method. All threads must be suspended before calling this
856// method. The compiled code for the method (if there is any) must not be in any threads call stack.
857void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100858 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700859 RemoveMethodLocked(method, /* release_memory= */ true);
Alex Lightdba61482016-12-21 08:20:29 -0800860}
861
862// This invalidates old_method. Once this function returns one can no longer use old_method to
863// execute code unless it is fixed up. This fixup will happen later in the process of installing a
864// class redefinition.
865// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
866// shouldn't be used since it is no longer logically in the jit code cache.
867// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
868void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100869 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +0000870 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000871 // Update methods in jni_stubs_map_.
872 for (auto& entry : jni_stubs_map_) {
873 JniStubData& data = entry.second;
874 data.MoveObsoleteMethod(old_method, new_method);
875 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000876 return;
877 }
Alex Lightdba61482016-12-21 08:20:29 -0800878 // Update method_code_map_ to point to the new method.
879 for (auto& it : method_code_map_) {
880 if (it.second == old_method) {
881 it.second = new_method;
882 }
883 }
884 // Update osr_code_map_ to point to the new method.
885 auto code_map = osr_code_map_.find(old_method);
886 if (code_map != osr_code_map_.end()) {
887 osr_code_map_.Put(new_method, code_map->second);
888 osr_code_map_.erase(old_method);
889 }
890}
891
Alex Lightb28e3042020-03-06 13:02:46 -0800892void JitCodeCache::TransitionToDebuggable() {
Nicolas Geoffrayc76232e2020-03-18 11:23:33 +0000893 // Check that none of our methods have an entrypoint in the zygote exec
894 // space (this should be taken care of by
895 // ClassLinker::UpdateEntryPointsClassVisitor.
Alex Lightb28e3042020-03-06 13:02:46 -0800896 {
897 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayc76232e2020-03-18 11:23:33 +0000898 if (kIsDebugBuild) {
899 for (const auto& it : method_code_map_) {
900 ArtMethod* method = it.second;
901 DCHECK(!method->IsPreCompiled());
902 DCHECK(!IsInZygoteExecSpace(method->GetEntryPointFromQuickCompiledCode()));
Nicolas Geoffrayfc47d6b2020-03-11 15:05:43 +0000903 }
Alex Lightb28e3042020-03-06 13:02:46 -0800904 }
Nicolas Geoffrayfc47d6b2020-03-11 15:05:43 +0000905 // Not strictly necessary, but this map is useless now.
906 saved_compiled_methods_map_.clear();
Alex Lightb28e3042020-03-06 13:02:46 -0800907 }
Nicolas Geoffrayc76232e2020-03-18 11:23:33 +0000908 if (kIsDebugBuild) {
909 for (const auto& entry : zygote_map_) {
910 ArtMethod* method = entry.method;
911 if (method != nullptr) {
912 DCHECK(!method->IsPreCompiled());
913 DCHECK(!IsInZygoteExecSpace(method->GetEntryPointFromQuickCompiledCode()));
914 }
Nicolas Geoffrayfc47d6b2020-03-11 15:05:43 +0000915 }
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000916 }
917}
918
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000919size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +0100920 return GetCurrentRegion()->GetUsedMemoryForCode();
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100921}
922
923size_t JitCodeCache::DataCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100924 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000925 return DataCacheSizeLocked();
926}
927
928size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +0100929 return GetCurrentRegion()->GetUsedMemoryForData();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800930}
931
David Srbeckyadb66f92019-10-10 12:59:43 +0000932bool JitCodeCache::Reserve(Thread* self,
933 JitMemoryRegion* region,
934 size_t code_size,
935 size_t stack_map_size,
936 size_t number_of_roots,
937 ArtMethod* method,
938 /*out*/ArrayRef<const uint8_t>* reserved_code,
939 /*out*/ArrayRef<const uint8_t>* reserved_data) {
940 code_size = OatQuickMethodHeader::InstructionAlignedSize() + code_size;
941 size_t data_size = RoundUp(ComputeRootTableSize(number_of_roots) + stack_map_size, sizeof(void*));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000942
David Srbeckyadb66f92019-10-10 12:59:43 +0000943 const uint8_t* code;
944 const uint8_t* data;
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100945 while (true) {
946 bool at_max_capacity = false;
David Srbeckyadb66f92019-10-10 12:59:43 +0000947 {
948 ScopedThreadSuspension sts(self, kSuspended);
949 MutexLock mu(self, *Locks::jit_lock_);
950 WaitForPotentialCollectionToComplete(self);
951 ScopedCodeCacheWrite ccw(*region);
952 code = region->AllocateCode(code_size);
953 data = region->AllocateData(data_size);
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100954 at_max_capacity = IsAtMaxCapacity();
David Srbeckyadb66f92019-10-10 12:59:43 +0000955 }
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100956 if (code != nullptr && data != nullptr) {
957 break;
David Srbeckyadb66f92019-10-10 12:59:43 +0000958 }
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100959 Free(self, region, code, data);
960 if (at_max_capacity) {
961 VLOG(jit) << "JIT failed to allocate code of size "
962 << PrettySize(code_size)
963 << ", and data of size "
964 << PrettySize(data_size);
965 return false;
966 }
967 // Run a code cache collection and try again.
968 GarbageCollectCache(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100969 }
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100970
David Srbeckyadb66f92019-10-10 12:59:43 +0000971 *reserved_code = ArrayRef<const uint8_t>(code, code_size);
972 *reserved_data = ArrayRef<const uint8_t>(data, data_size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100973
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100974 MutexLock mu(self, *Locks::jit_lock_);
David Srbeckyadb66f92019-10-10 12:59:43 +0000975 histogram_code_memory_use_.AddValue(code_size);
976 if (code_size > kCodeSizeLogThreshold) {
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000977 LOG(INFO) << "JIT allocated "
David Srbeckyadb66f92019-10-10 12:59:43 +0000978 << PrettySize(code_size)
979 << " for compiled code of "
980 << ArtMethod::PrettyMethod(method);
981 }
982 histogram_stack_map_memory_use_.AddValue(data_size);
983 if (data_size > kStackMapSizeLogThreshold) {
984 LOG(INFO) << "JIT allocated "
985 << PrettySize(data_size)
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000986 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700987 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800988 }
David Srbeckyadb66f92019-10-10 12:59:43 +0000989 return true;
990}
991
992void JitCodeCache::Free(Thread* self,
993 JitMemoryRegion* region,
994 const uint8_t* code,
995 const uint8_t* data) {
996 MutexLock mu(self, *Locks::jit_lock_);
997 ScopedCodeCacheWrite ccw(*region);
David Srbecky30fd8512020-02-20 20:27:58 +0000998 FreeLocked(region, code, data);
999}
1000
1001void JitCodeCache::FreeLocked(JitMemoryRegion* region, const uint8_t* code, const uint8_t* data) {
David Srbeckyadb66f92019-10-10 12:59:43 +00001002 if (code != nullptr) {
David Srbecky30fd8512020-02-20 20:27:58 +00001003 RemoveNativeDebugInfoForJit(reinterpret_cast<const void*>(FromAllocationToCode(code)));
David Srbeckyadb66f92019-10-10 12:59:43 +00001004 region->FreeCode(code);
1005 }
1006 if (data != nullptr) {
1007 region->FreeData(data);
1008 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001009}
1010
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001011class MarkCodeClosure final : public Closure {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001012 public:
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001013 MarkCodeClosure(JitCodeCache* code_cache, CodeCacheBitmap* bitmap, Barrier* barrier)
1014 : code_cache_(code_cache), bitmap_(bitmap), barrier_(barrier) {}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001015
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001016 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001017 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001018 DCHECK(thread == Thread::Current() || thread->IsSuspended());
Andreas Gampec7d878d2018-11-19 18:42:06 +00001019 StackVisitor::WalkStack(
1020 [&](const art::StackVisitor* stack_visitor) {
1021 const OatQuickMethodHeader* method_header =
1022 stack_visitor->GetCurrentOatQuickMethodHeader();
1023 if (method_header == nullptr) {
1024 return true;
1025 }
1026 const void* code = method_header->GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001027 if (code_cache_->ContainsPc(code) && !code_cache_->IsInZygoteExecSpace(code)) {
Andreas Gampec7d878d2018-11-19 18:42:06 +00001028 // Use the atomic set version, as multiple threads are executing this code.
1029 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1030 }
1031 return true;
1032 },
1033 thread,
1034 /* context= */ nullptr,
1035 art::StackVisitor::StackWalkKind::kSkipInlinedFrames);
1036
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001037 if (kIsDebugBuild) {
1038 // The stack walking code queries the side instrumentation stack if it
1039 // sees an instrumentation exit pc, so the JIT code of methods in that stack
Orion Hodson853fc2e2020-07-27 17:01:44 +01001040 // must have been seen. We check this below.
Nicolas Geoffraye91e7952020-01-23 10:15:56 +00001041 for (const auto& it : *thread->GetInstrumentationStack()) {
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001042 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1043 // its stack frame, it is not the method owning return_pc_. We just pass null to
1044 // LookupMethodHeader: the method is only checked against in debug builds.
1045 OatQuickMethodHeader* method_header =
Nicolas Geoffraye91e7952020-01-23 10:15:56 +00001046 code_cache_->LookupMethodHeader(it.second.return_pc_, /* method= */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001047 if (method_header != nullptr) {
1048 const void* code = method_header->GetCode();
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001049 CHECK(bitmap_->Test(FromCodeToAllocation(code)));
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001050 }
1051 }
1052 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001053 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001054 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001055
1056 private:
1057 JitCodeCache* const code_cache_;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001058 CodeCacheBitmap* const bitmap_;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001059 Barrier* const barrier_;
1060};
1061
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001062void JitCodeCache::NotifyCollectionDone(Thread* self) {
1063 collection_in_progress_ = false;
1064 lock_cond_.Broadcast(self);
1065}
1066
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001067void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1068 Barrier barrier(0);
1069 size_t threads_running_checkpoint = 0;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001070 MarkCodeClosure closure(this, GetLiveBitmap(), &barrier);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001071 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1072 // Now that we have run our checkpoint, move to a suspended state and wait
1073 // for other threads to run the checkpoint.
1074 ScopedThreadSuspension sts(self, kSuspended);
1075 if (threads_running_checkpoint != 0) {
1076 barrier.Increment(self, threads_running_checkpoint);
1077 }
1078}
1079
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +01001080bool JitCodeCache::IsAtMaxCapacity() const {
1081 return private_region_.GetCurrentCapacity() == private_region_.GetMaxCapacity();
1082}
1083
Nicolas Geoffray35122442016-03-02 12:05:30 +00001084bool JitCodeCache::ShouldDoFullCollection() {
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +01001085 if (IsAtMaxCapacity()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001086 // Always do a full collection when the code cache is full.
1087 return true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001088 } else if (private_region_.GetCurrentCapacity() < kReservedCapacity) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001089 // Always do partial collection when the code cache size is below the reserved
1090 // capacity.
1091 return false;
1092 } else if (last_collection_increased_code_cache_) {
1093 // This time do a full collection.
1094 return true;
1095 } else {
1096 // This time do a partial collection.
1097 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001098 }
1099}
1100
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001101void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001102 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001103 // Wait for an existing collection, or let everyone know we are starting one.
1104 {
1105 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001106 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001107 if (!garbage_collect_code_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001108 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001109 return;
1110 } else if (WaitForPotentialCollectionToComplete(self)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001111 return;
1112 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001113 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001114 live_bitmap_.reset(CodeCacheBitmap::Create(
1115 "code-cache-bitmap",
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001116 reinterpret_cast<uintptr_t>(private_region_.GetExecPages()->Begin()),
1117 reinterpret_cast<uintptr_t>(
1118 private_region_.GetExecPages()->Begin() + private_region_.GetCurrentCapacity() / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001119 collection_in_progress_ = true;
1120 }
1121 }
1122
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001123 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001124 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001125 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001126
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001127 bool do_full_collection = false;
1128 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001129 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001130 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001131 }
1132
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001133 VLOG(jit) << "Do "
1134 << (do_full_collection ? "full" : "partial")
1135 << " code cache collection, code="
1136 << PrettySize(CodeCacheSize())
1137 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001138
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001139 DoCollection(self, /* collect_profiling_info= */ do_full_collection);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001140
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001141 VLOG(jit) << "After code cache collection, code="
1142 << PrettySize(CodeCacheSize())
1143 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001144
1145 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001146 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001147
1148 // Increase the code cache only when we do partial collections.
1149 // TODO: base this strategy on how full the code cache is?
1150 if (do_full_collection) {
1151 last_collection_increased_code_cache_ = false;
1152 } else {
1153 last_collection_increased_code_cache_ = true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001154 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001155 }
1156
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001157 bool next_collection_will_be_full = ShouldDoFullCollection();
1158
1159 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001160 if (next_collection_will_be_full) {
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001161 for (auto it : profiling_infos_) {
1162 it.second->SetBaselineHotnessCount(0);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001163 }
1164
Vladimir Marko2196c652017-11-30 16:16:07 +00001165 // Change entry points of native methods back to the GenericJNI entrypoint.
1166 for (const auto& entry : jni_stubs_map_) {
1167 const JniStubData& data = entry.second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001168 if (!data.IsCompiled() || IsInZygoteExecSpace(data.GetCode())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001169 continue;
1170 }
1171 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1172 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1173 const OatQuickMethodHeader* method_header =
1174 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1175 for (ArtMethod* method : data.GetMethods()) {
1176 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1177 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1178 method->SetCounter(new_counter);
1179 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1180 }
1181 }
1182 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001183 }
1184 live_bitmap_.reset(nullptr);
1185 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001186 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001187 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001188 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001189}
1190
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001191void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001192 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001193 std::unordered_set<OatQuickMethodHeader*> method_headers;
1194 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001195 MutexLock mu(self, *Locks::jit_lock_);
Mingyao Yang063fc772016-08-02 11:02:54 -07001196 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001197 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1198 JniStubData* data = &it->second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001199 if (IsInZygoteExecSpace(data->GetCode()) ||
1200 !data->IsCompiled() ||
1201 GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001202 ++it;
1203 } else {
1204 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
David Srbecky41617b12020-03-18 21:19:06 +00001205 for (ArtMethod* method : data->GetMethods()) {
1206 VLOG(jit) << "JIT removed (JNI) " << method->PrettyMethod() << ": " << data->GetCode();
1207 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001208 it = jni_stubs_map_.erase(it);
1209 }
1210 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001211 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1212 const void* code_ptr = it->first;
1213 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001214 if (IsInZygoteExecSpace(code_ptr) || GetLiveBitmap()->Test(allocation)) {
Mingyao Yang063fc772016-08-02 11:02:54 -07001215 ++it;
1216 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001217 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1218 method_headers.insert(header);
David Srbecky41617b12020-03-18 21:19:06 +00001219 VLOG(jit) << "JIT removed " << it->second->PrettyMethod() << ": " << it->first;
Mingyao Yang063fc772016-08-02 11:02:54 -07001220 it = method_code_map_.erase(it);
1221 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001222 }
David Srbecky521644b2020-03-21 13:17:52 +00001223 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001224 }
1225}
1226
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001227bool JitCodeCache::GetGarbageCollectCode() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001228 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001229 return garbage_collect_code_;
1230}
1231
1232void JitCodeCache::SetGarbageCollectCode(bool value) {
1233 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001234 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray9c7b4f12020-08-03 15:22:59 +01001235 // Update the flag while holding the lock to ensure no thread will try to GC.
1236 garbage_collect_code_ = value;
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001237}
1238
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001239void JitCodeCache::RemoveMethodBeingCompiled(ArtMethod* method, CompilationKind kind) {
1240 DCHECK(IsMethodBeingCompiled(method, kind));
1241 switch (kind) {
1242 case CompilationKind::kOsr:
1243 current_osr_compilations_.erase(method);
1244 break;
1245 case CompilationKind::kBaseline:
1246 current_baseline_compilations_.erase(method);
1247 break;
1248 case CompilationKind::kOptimized:
1249 current_optimized_compilations_.erase(method);
1250 break;
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001251 }
1252}
1253
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001254void JitCodeCache::AddMethodBeingCompiled(ArtMethod* method, CompilationKind kind) {
1255 DCHECK(!IsMethodBeingCompiled(method, kind));
1256 switch (kind) {
1257 case CompilationKind::kOsr:
1258 current_osr_compilations_.insert(method);
1259 break;
1260 case CompilationKind::kBaseline:
1261 current_baseline_compilations_.insert(method);
1262 break;
1263 case CompilationKind::kOptimized:
1264 current_optimized_compilations_.insert(method);
1265 break;
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001266 }
1267}
1268
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001269bool JitCodeCache::IsMethodBeingCompiled(ArtMethod* method, CompilationKind kind) {
1270 switch (kind) {
1271 case CompilationKind::kOsr:
1272 return ContainsElement(current_osr_compilations_, method);
1273 case CompilationKind::kBaseline:
1274 return ContainsElement(current_baseline_compilations_, method);
1275 case CompilationKind::kOptimized:
1276 return ContainsElement(current_optimized_compilations_, method);
1277 }
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001278}
1279
1280bool JitCodeCache::IsMethodBeingCompiled(ArtMethod* method) {
1281 return ContainsElement(current_optimized_compilations_, method) ||
1282 ContainsElement(current_osr_compilations_, method) ||
1283 ContainsElement(current_baseline_compilations_, method);
1284}
1285
Nicolas Geoffray35122442016-03-02 12:05:30 +00001286void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001287 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001288 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001289 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001290
Nicolas Geoffray1a277a62020-07-31 16:07:17 +01001291 // Update to interpreter the methods that have baseline entrypoints and whose baseline
1292 // hotness count is zero.
1293 // Note that these methods may be in thread stack or concurrently revived
1294 // between. That's OK, as the thread executing it will mark it.
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001295 for (auto it : profiling_infos_) {
1296 ProfilingInfo* info = it.second;
Nicolas Geoffray1a277a62020-07-31 16:07:17 +01001297 if (info->GetBaselineHotnessCount() == 0) {
1298 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1299 if (ContainsPc(entry_point)) {
1300 OatQuickMethodHeader* method_header =
1301 OatQuickMethodHeader::FromEntryPoint(entry_point);
1302 if (CodeInfo::IsBaseline(method_header->GetOptimizedCodeInfoPtr())) {
1303 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001304 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001305 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001306 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001307 }
Nicolas Geoffray1a277a62020-07-31 16:07:17 +01001308 // TODO: collect profiling info
1309 // TODO: collect optimized code
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001310
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001311 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1312 // an entry point is either:
1313 // - an osr compiled code, that will be removed if not in a thread call stack.
1314 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001315 for (const auto& entry : jni_stubs_map_) {
1316 const JniStubData& data = entry.second;
1317 const void* code_ptr = data.GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001318 if (IsInZygoteExecSpace(code_ptr)) {
1319 continue;
1320 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001321 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1322 for (ArtMethod* method : data.GetMethods()) {
1323 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1324 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1325 break;
1326 }
1327 }
1328 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001329 for (const auto& it : method_code_map_) {
1330 ArtMethod* method = it.second;
1331 const void* code_ptr = it.first;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001332 if (IsInZygoteExecSpace(code_ptr)) {
1333 continue;
1334 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001335 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1336 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1337 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1338 }
1339 }
1340
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001341 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001342 // on thread stacks).
1343 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001344 }
1345
1346 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001347 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001348
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001349 // At this point, mutator threads are still running, and entrypoints of methods can
1350 // change. We do know they cannot change to a code cache entry that is not marked,
1351 // therefore we can safely remove those entries.
1352 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001353
Nicolas Geoffray35122442016-03-02 12:05:30 +00001354 if (collect_profiling_info) {
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001355 // TODO: Collect unused profiling infos.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001356 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001357}
1358
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001359OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001360 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1361 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001362 // On Thumb-2, the pc is offset by one.
1363 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001364 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001365 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1366 return nullptr;
1367 }
1368
Vladimir Marko2196c652017-11-30 16:16:07 +00001369 if (!kIsDebugBuild) {
1370 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1371 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001372 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001373
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001374 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001375 OatQuickMethodHeader* method_header = nullptr;
1376 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1377 if (method != nullptr && UNLIKELY(method->IsNative())) {
1378 auto it = jni_stubs_map_.find(JniStubKey(method));
1379 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1380 return nullptr;
1381 }
1382 const void* code_ptr = it->second.GetCode();
1383 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1384 if (!method_header->Contains(pc)) {
1385 return nullptr;
1386 }
1387 } else {
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001388 if (shared_region_.IsInExecSpace(reinterpret_cast<const void*>(pc))) {
1389 const void* code_ptr = zygote_map_.GetCodeFor(method, pc);
1390 if (code_ptr != nullptr) {
1391 return OatQuickMethodHeader::FromCodePointer(code_ptr);
1392 }
1393 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001394 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1395 if (it != method_code_map_.begin()) {
1396 --it;
1397 const void* code_ptr = it->first;
1398 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1399 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1400 found_method = it->second;
1401 }
1402 }
1403 if (method_header == nullptr && method == nullptr) {
1404 // Scan all compiled JNI stubs as well. This slow search is used only
1405 // for checks in debug build, for release builds the `method` is not null.
1406 for (auto&& entry : jni_stubs_map_) {
1407 const JniStubData& data = entry.second;
1408 if (data.IsCompiled() &&
1409 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1410 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1411 }
1412 }
1413 }
1414 if (method_header == nullptr) {
1415 return nullptr;
1416 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001417 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001418
1419 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Vladimir Markoeab02482019-05-09 10:28:17 +01001420 DCHECK_EQ(found_method, method)
1421 << ArtMethod::PrettyMethod(method) << " "
1422 << ArtMethod::PrettyMethod(found_method) << " "
David Sehr709b0702016-10-13 09:12:37 -07001423 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001424 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001425 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001426}
1427
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001428OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001429 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001430 auto it = osr_code_map_.find(method);
1431 if (it == osr_code_map_.end()) {
1432 return nullptr;
1433 }
1434 return OatQuickMethodHeader::FromCodePointer(it->second);
1435}
1436
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001437ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1438 ArtMethod* method,
Nicolas Geoffray60ef3992020-08-07 07:49:57 +00001439 const std::vector<uint32_t>& entries) {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001440 DCHECK(CanAllocateProfilingInfo());
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001441 ProfilingInfo* info = nullptr;
Nicolas Geoffray60ef3992020-08-07 07:49:57 +00001442 {
1443 MutexLock mu(self, *Locks::jit_lock_);
1444 info = AddProfilingInfoInternal(self, method, entries);
1445 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001446
Nicolas Geoffray60ef3992020-08-07 07:49:57 +00001447 if (info == nullptr) {
1448 GarbageCollectCache(self);
1449 MutexLock mu(self, *Locks::jit_lock_);
1450 info = AddProfilingInfoInternal(self, method, entries);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001451 }
1452 return info;
1453}
1454
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001455ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001456 ArtMethod* method,
1457 const std::vector<uint32_t>& entries) {
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001458 // Check whether some other thread has concurrently created it.
1459 auto it = profiling_infos_.find(method);
1460 if (it != profiling_infos_.end()) {
1461 return it->second;
1462 }
1463
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001464 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001465 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001466 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001467
David Srbecky87fb0322019-08-20 10:34:02 +01001468 const uint8_t* data = private_region_.AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001469 if (data == nullptr) {
1470 return nullptr;
1471 }
David Srbecky87fb0322019-08-20 10:34:02 +01001472 uint8_t* writable_data = private_region_.GetWritableDataAddress(data);
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001473 ProfilingInfo* info = new (writable_data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001474
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001475 profiling_infos_.Put(method, info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001476 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001477 return info;
1478}
1479
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001480void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001481 return shared_region_.OwnsSpace(mspace)
1482 ? shared_region_.MoreCore(mspace, increment)
1483 : private_region_.MoreCore(mspace, increment);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001484}
1485
Calin Juravle99629622016-04-19 16:33:46 +01001486void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001487 std::vector<ProfileMethodInfo>& methods) {
Nicolas Geoffray1afdfe62018-11-21 09:38:10 +00001488 Thread* self = Thread::Current();
1489 WaitUntilInlineCacheAccessible(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001490 MutexLock mu(self, *Locks::jit_lock_);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001491 ScopedTrace trace(__FUNCTION__);
Calin Juravlea39fd982017-05-18 10:15:52 -07001492 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001493 for (auto it : profiling_infos_) {
1494 ProfilingInfo* info = it.second;
Calin Juravle99629622016-04-19 16:33:46 +01001495 ArtMethod* method = info->GetMethod();
1496 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001497 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1498 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001499 // Skip dex files which are not profiled.
1500 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001501 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001502 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001503
1504 // If the method didn't reach the compilation threshold don't save the inline caches.
1505 // They might be incomplete and cause unnecessary deoptimizations.
1506 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1507 if (method->GetCounter() < jit_compile_threshold) {
1508 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001509 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001510 continue;
1511 }
1512
Calin Juravle940eb0c2017-01-30 19:30:44 -08001513 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001514 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001515 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001516 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001517 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001518 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1519 mirror::Class* cls = cache.classes_[k].Read();
1520 if (cls == nullptr) {
1521 break;
1522 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001523
Calin Juravle13439f02017-02-21 01:17:21 -08001524 // Check if the receiver is in the boot class path or if it's in the
1525 // same class loader as the caller. If not, skip it, as there is not
1526 // much we can do during AOT.
1527 if (!cls->IsBootStrapClassLoaded() &&
1528 caller->GetClassLoader() != cls->GetClassLoader()) {
1529 is_missing_types = true;
1530 continue;
1531 }
1532
Calin Juravle4ca70a32017-02-21 16:22:24 -08001533 const DexFile* class_dex_file = nullptr;
1534 dex::TypeIndex type_index;
1535
1536 if (cls->GetDexCache() == nullptr) {
1537 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001538 // Make a best effort to find the type index in the method's dex file.
1539 // We could search all open dex files but that might turn expensive
1540 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001541 class_dex_file = dex_file;
1542 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1543 } else {
1544 class_dex_file = &(cls->GetDexFile());
1545 type_index = cls->GetDexTypeIndex();
1546 }
1547 if (!type_index.IsValid()) {
1548 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001549 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001550 continue;
1551 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001552 if (ContainsElement(dex_base_locations,
1553 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001554 // Only consider classes from the same apk (including multidex).
1555 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001556 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001557 } else {
1558 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001559 }
1560 }
1561 if (!profile_classes.empty()) {
1562 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001563 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001564 }
1565 }
1566 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001567 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001568 }
1569}
1570
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001571bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001572 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001573 return osr_code_map_.find(method) != osr_code_map_.end();
1574}
1575
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001576bool JitCodeCache::NotifyCompilationOf(ArtMethod* method,
1577 Thread* self,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001578 CompilationKind compilation_kind,
Nicolas Geoffray60ef3992020-08-07 07:49:57 +00001579 bool prejit) {
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001580 const void* existing_entry_point = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001581 if (compilation_kind != CompilationKind::kOsr && ContainsPc(existing_entry_point)) {
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001582 OatQuickMethodHeader* method_header =
1583 OatQuickMethodHeader::FromEntryPoint(existing_entry_point);
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001584 bool is_baseline = (compilation_kind == CompilationKind::kBaseline);
1585 if (CodeInfo::IsBaseline(method_header->GetOptimizedCodeInfoPtr()) == is_baseline) {
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001586 VLOG(jit) << "Not compiling "
1587 << method->PrettyMethod()
1588 << " because it has already been compiled"
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001589 << " kind=" << compilation_kind;
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001590 return false;
1591 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001592 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001593
Vladimir Marko5115a4d2019-10-17 14:56:47 +01001594 if (NeedsClinitCheckBeforeCall(method) && !prejit) {
1595 // We do not need a synchronization barrier for checking the visibly initialized status
1596 // or checking the initialized status just for requesting visible initialization.
1597 ClassStatus status = method->GetDeclaringClass()
1598 ->GetStatus<kDefaultVerifyFlags, /*kWithSynchronizationBarrier=*/ false>();
1599 if (status != ClassStatus::kVisiblyInitialized) {
1600 // Unless we're pre-jitting, we currently don't save the JIT compiled code if we cannot
1601 // update the entrypoint due to needing an initialization check.
1602 if (status == ClassStatus::kInitialized) {
1603 // Request visible initialization but do not block to allow compiling other methods.
1604 // Hopefully, this will complete by the time the method becomes hot again.
1605 Runtime::Current()->GetClassLinker()->MakeInitializedClassesVisiblyInitialized(
1606 self, /*wait=*/ false);
1607 }
1608 VLOG(jit) << "Not compiling "
1609 << method->PrettyMethod()
1610 << " because it has the resolution stub";
1611 // Give it a new chance to be hot.
1612 ClearMethodCounter(method, /*was_warm=*/ false);
1613 return false;
Vladimir Markocce414f2019-10-07 08:51:33 +01001614 }
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01001615 }
1616
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001617 if (compilation_kind == CompilationKind::kOsr) {
Nicolas Geoffray085f7402019-12-16 16:30:48 +00001618 MutexLock mu(self, *Locks::jit_lock_);
1619 if (osr_code_map_.find(method) != osr_code_map_.end()) {
1620 return false;
1621 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001622 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001623
Vladimir Marko2196c652017-11-30 16:16:07 +00001624 if (UNLIKELY(method->IsNative())) {
Nicolas Geoffray085f7402019-12-16 16:30:48 +00001625 MutexLock mu(self, *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001626 JniStubKey key(method);
1627 auto it = jni_stubs_map_.find(key);
1628 bool new_compilation = false;
1629 if (it == jni_stubs_map_.end()) {
1630 // Create a new entry to mark the stub as being compiled.
1631 it = jni_stubs_map_.Put(key, JniStubData{});
1632 new_compilation = true;
1633 }
1634 JniStubData* data = &it->second;
1635 data->AddMethod(method);
1636 if (data->IsCompiled()) {
1637 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1638 const void* entrypoint = method_header->GetEntryPoint();
1639 // Update also entrypoints of other methods held by the JniStubData.
1640 // We could simply update the entrypoint of `method` but if the last JIT GC has
1641 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1642 // as well change them back as this stub shall not be collected anyway and this
1643 // can avoid a few expensive GenericJNI calls.
Vladimir Markocce414f2019-10-07 08:51:33 +01001644 data->UpdateEntryPoints(entrypoint);
Vladimir Marko2196c652017-11-30 16:16:07 +00001645 if (collection_in_progress_) {
David Srbeckyc45b5892019-04-24 10:32:04 +01001646 if (!IsInZygoteExecSpace(data->GetCode())) {
1647 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1648 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001649 }
1650 }
1651 return new_compilation;
1652 } else {
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001653 if (CanAllocateProfilingInfo() && (compilation_kind == CompilationKind::kBaseline)) {
1654 bool has_profiling_info = false;
1655 {
1656 MutexLock mu(self, *Locks::jit_lock_);
1657 has_profiling_info = (profiling_infos_.find(method) != profiling_infos_.end());
1658 }
1659 if (!has_profiling_info) {
1660 if (ProfilingInfo::Create(self, method) == nullptr) {
1661 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled baseline";
1662 ClearMethodCounter(method, /*was_warm=*/ false);
1663 return false;
1664 }
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001665 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001666 }
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001667 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001668 if (IsMethodBeingCompiled(method, compilation_kind)) {
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001669 return false;
1670 }
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001671 AddMethodBeingCompiled(method, compilation_kind);
Vladimir Marko2196c652017-11-30 16:16:07 +00001672 return true;
1673 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001674}
1675
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001676ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001677 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001678 auto it = profiling_infos_.find(method);
1679 if (it == profiling_infos_.end()) {
1680 return nullptr;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001681 }
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001682 if (!it->second->IncrementInlineUse()) {
1683 // Overflow of inlining uses, just bail.
1684 return nullptr;
1685 }
1686 return it->second;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001687}
1688
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001689void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001690 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001691 auto it = profiling_infos_.find(method);
1692 DCHECK(it != profiling_infos_.end());
1693 it->second->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001694}
1695
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001696void JitCodeCache::DoneCompiling(ArtMethod* method,
1697 Thread* self,
1698 CompilationKind compilation_kind) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001699 DCHECK_EQ(Thread::Current(), self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001700 MutexLock mu(self, *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001701 if (UNLIKELY(method->IsNative())) {
1702 auto it = jni_stubs_map_.find(JniStubKey(method));
1703 DCHECK(it != jni_stubs_map_.end());
1704 JniStubData* data = &it->second;
1705 DCHECK(ContainsElement(data->GetMethods(), method));
1706 if (UNLIKELY(!data->IsCompiled())) {
1707 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1708 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
David Srbeckyadb66f92019-10-10 12:59:43 +00001709 } // else Commit() updated entrypoints of all methods in the JniStubData.
Vladimir Marko2196c652017-11-30 16:16:07 +00001710 } else {
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001711 RemoveMethodBeingCompiled(method, compilation_kind);
Vladimir Marko2196c652017-11-30 16:16:07 +00001712 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001713}
1714
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001715void JitCodeCache::InvalidateAllCompiledCode() {
1716 art::MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray60ef3992020-08-07 07:49:57 +00001717 VLOG(jit) << "Invalidating all compiled code";
1718 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1719 for (auto it : method_code_map_) {
1720 ArtMethod* meth = it.second;
1721 // We were compiled, so we must be warm.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001722 ClearMethodCounter(meth, /*was_warm=*/true);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001723 if (meth->IsObsolete()) {
1724 linker->SetEntryPointsForObsoleteMethod(meth);
1725 } else {
1726 linker->SetEntryPointsToInterpreter(meth);
1727 }
1728 }
Nicolas Geoffray60ef3992020-08-07 07:49:57 +00001729 saved_compiled_methods_map_.clear();
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001730 osr_code_map_.clear();
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001731}
1732
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001733void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1734 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001735 DCHECK(!method->IsNative());
Alex Light2d441b12018-06-08 15:33:21 -07001736 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001737
Alex Light2d441b12018-06-08 15:33:21 -07001738 // Clear the method counter if we are running jitted code since we might want to jit this again in
1739 // the future.
1740 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001741 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001742 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001743 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1744 method, GetQuickToInterpreterBridge());
Nicolas Geoffray095dc462020-08-17 16:40:28 +01001745 ClearMethodCounter(method, /*was_warm=*/ true);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001746 } else {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001747 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001748 auto it = osr_code_map_.find(method);
1749 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1750 // Remove the OSR method, to avoid using it again.
1751 osr_code_map_.erase(it);
1752 }
1753 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001754
Nicolas Geoffray32384402019-07-17 20:06:44 +01001755 // In case the method was pre-compiled, clear that information so we
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001756 // can recompile it ourselves.
Nicolas Geoffray32384402019-07-17 20:06:44 +01001757 if (method->IsPreCompiled()) {
1758 method->ClearPreCompiled();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001759 }
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001760}
1761
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001762void JitCodeCache::Dump(std::ostream& os) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001763 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
David Srbecky44b977d2019-08-09 12:15:32 +01001764 os << "Current JIT code cache size (used / resident): "
1765 << GetCurrentRegion()->GetUsedMemoryForCode() / KB << "KB / "
1766 << GetCurrentRegion()->GetResidentMemoryForCode() / KB << "KB\n"
1767 << "Current JIT data cache size (used / resident): "
1768 << GetCurrentRegion()->GetUsedMemoryForData() / KB << "KB / "
1769 << GetCurrentRegion()->GetResidentMemoryForData() / KB << "KB\n";
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001770 if (!Runtime::Current()->IsZygote()) {
1771 os << "Zygote JIT code cache size (at point of fork): "
David Srbecky44b977d2019-08-09 12:15:32 +01001772 << shared_region_.GetUsedMemoryForCode() / KB << "KB / "
1773 << shared_region_.GetResidentMemoryForCode() / KB << "KB\n"
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001774 << "Zygote JIT data cache size (at point of fork): "
David Srbecky44b977d2019-08-09 12:15:32 +01001775 << shared_region_.GetUsedMemoryForData() / KB << "KB / "
1776 << shared_region_.GetResidentMemoryForData() / KB << "KB\n";
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001777 }
1778 os << "Current JIT mini-debug-info size: " << PrettySize(GetJitMiniDebugInfoMemUsage()) << "\n"
1779 << "Current JIT capacity: " << PrettySize(GetCurrentRegion()->GetCurrentCapacity()) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00001780 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001781 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
Nicolas Geoffrayc473dc72020-07-03 15:04:21 +01001782 << "Total number of JIT baseline compilations: " << number_of_baseline_compilations_ << "\n"
1783 << "Total number of JIT optimized compilations: " << number_of_optimized_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001784 << "Total number of JIT compilations for on stack replacement: "
1785 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001786 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001787 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1788 histogram_code_memory_use_.PrintMemoryUse(os);
1789 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001790}
1791
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001792void JitCodeCache::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffrayb08d5db2019-07-17 10:45:36 +01001793 Thread* self = Thread::Current();
1794
1795 // Remove potential tasks that have been inherited from the zygote.
1796 // We do this now and not in Jit::PostForkChildAction, as system server calls
1797 // JitCodeCache::PostForkChildAction first, and then does some code loading
1798 // that may result in new JIT tasks that we want to keep.
1799 ThreadPool* pool = Runtime::Current()->GetJit()->GetThreadPool();
1800 if (pool != nullptr) {
1801 pool->RemoveAllTasks(self);
1802 }
1803
1804 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray88f3fd92019-06-27 16:32:13 +01001805
1806 // Reset potential writable MemMaps inherited from the zygote. We never want
1807 // to write to them.
1808 shared_region_.ResetWritableMappings();
1809
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001810 if (is_zygote || Runtime::Current()->IsSafeMode()) {
1811 // Don't create a private region for a child zygote. Regions are usually map shared
1812 // (to satisfy dual-view), and we don't want children of a child zygote to inherit it.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001813 return;
1814 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001815
1816 // Reset all statistics to be specific to this process.
Nicolas Geoffrayc473dc72020-07-03 15:04:21 +01001817 number_of_baseline_compilations_ = 0;
1818 number_of_optimized_compilations_ = 0;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001819 number_of_osr_compilations_ = 0;
1820 number_of_collections_ = 0;
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001821 histogram_stack_map_memory_use_.Reset();
1822 histogram_code_memory_use_.Reset();
1823 histogram_profiling_info_memory_use_.Reset();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001824
1825 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
1826 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001827 std::string error_msg;
Nicolas Geoffray9c54e182019-06-18 10:42:52 +01001828 if (!private_region_.Initialize(initial_capacity,
1829 max_capacity,
1830 /* rwx_memory_allowed= */ !is_system_server,
1831 is_zygote,
1832 &error_msg)) {
1833 LOG(WARNING) << "Could not create private region after zygote fork: " << error_msg;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001834 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001835}
1836
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001837JitMemoryRegion* JitCodeCache::GetCurrentRegion() {
1838 return Runtime::Current()->IsZygote() ? &shared_region_ : &private_region_;
1839}
1840
David Srbecky41617b12020-03-18 21:19:06 +00001841void JitCodeCache::VisitAllMethods(const std::function<void(const void*, ArtMethod*)>& cb) {
1842 for (const auto& it : jni_stubs_map_) {
1843 const JniStubData& data = it.second;
1844 if (data.IsCompiled()) {
1845 for (ArtMethod* method : data.GetMethods()) {
1846 cb(data.GetCode(), method);
1847 }
1848 }
1849 }
1850 for (auto it : method_code_map_) { // Includes OSR methods.
1851 cb(it.first, it.second);
1852 }
1853 for (auto it : saved_compiled_methods_map_) {
1854 cb(it.second, it.first);
1855 }
1856 for (auto it : zygote_map_) {
1857 if (it.code_ptr != nullptr && it.method != nullptr) {
1858 cb(it.code_ptr, it.method);
1859 }
1860 }
1861}
1862
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001863void ZygoteMap::Initialize(uint32_t number_of_methods) {
1864 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
1865 // Allocate for 40-80% capacity. This will offer OK lookup times, and termination
1866 // cases.
1867 size_t capacity = RoundUpToPowerOfTwo(number_of_methods * 100 / 80);
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001868 const uint8_t* memory = region_->AllocateData(
1869 capacity * sizeof(Entry) + sizeof(ZygoteCompilationState));
1870 if (memory == nullptr) {
1871 LOG(WARNING) << "Could not allocate data for the zygote map";
1872 return;
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001873 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001874 const Entry* data = reinterpret_cast<const Entry*>(memory);
1875 region_->FillData(data, capacity, Entry { nullptr, nullptr });
1876 map_ = ArrayRef(data, capacity);
1877 compilation_state_ = reinterpret_cast<const ZygoteCompilationState*>(
1878 memory + capacity * sizeof(Entry));
1879 region_->WriteData(compilation_state_, ZygoteCompilationState::kInProgress);
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001880}
1881
1882const void* ZygoteMap::GetCodeFor(ArtMethod* method, uintptr_t pc) const {
1883 if (map_.empty()) {
1884 return nullptr;
1885 }
1886
1887 if (method == nullptr) {
1888 // Do a linear search. This should only be used in debug builds.
1889 CHECK(kIsDebugBuild);
1890 for (const Entry& entry : map_) {
1891 const void* code_ptr = entry.code_ptr;
1892 if (code_ptr != nullptr) {
1893 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1894 if (method_header->Contains(pc)) {
1895 return code_ptr;
1896 }
1897 }
1898 }
1899 return nullptr;
1900 }
1901
1902 std::hash<ArtMethod*> hf;
1903 size_t index = hf(method) & (map_.size() - 1u);
1904 size_t original_index = index;
1905 // Loop over the array: we know this loop terminates as we will either
1906 // encounter the given method, or a null entry. Both terminate the loop.
1907 // Note that the zygote may concurrently write new entries to the map. That's OK as the
1908 // map is never resized.
1909 while (true) {
1910 const Entry& entry = map_[index];
1911 if (entry.method == nullptr) {
1912 // Not compiled yet.
1913 return nullptr;
1914 }
1915 if (entry.method == method) {
1916 if (entry.code_ptr == nullptr) {
1917 // This is a race with the zygote which wrote the method, but hasn't written the
1918 // code. Just bail and wait for the next time we need the method.
1919 return nullptr;
1920 }
1921 if (pc != 0 && !OatQuickMethodHeader::FromCodePointer(entry.code_ptr)->Contains(pc)) {
1922 return nullptr;
1923 }
1924 return entry.code_ptr;
1925 }
1926 index = (index + 1) & (map_.size() - 1);
1927 DCHECK_NE(original_index, index);
1928 }
1929}
1930
1931void ZygoteMap::Put(const void* code, ArtMethod* method) {
1932 if (map_.empty()) {
1933 return;
1934 }
1935 CHECK(Runtime::Current()->IsZygote());
1936 std::hash<ArtMethod*> hf;
1937 size_t index = hf(method) & (map_.size() - 1);
1938 size_t original_index = index;
1939 // Because the size of the map is bigger than the number of methods that will
1940 // be added, we are guaranteed to find a free slot in the array, and
1941 // therefore for this loop to terminate.
1942 while (true) {
David Srbecky87fb0322019-08-20 10:34:02 +01001943 const Entry* entry = &map_[index];
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001944 if (entry->method == nullptr) {
1945 // Note that readers can read this memory concurrently, but that's OK as
1946 // we are writing pointers.
1947 region_->WriteData(entry, Entry { method, code });
1948 break;
1949 }
1950 index = (index + 1) & (map_.size() - 1);
1951 DCHECK_NE(original_index, index);
1952 }
1953 DCHECK_EQ(GetCodeFor(method), code);
1954}
1955
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001956} // namespace jit
1957} // namespace art