blob: 4ea61c69d8360aedfbde469ecde1079609ab46b8 [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"
Andreas Gampef0f3c592018-06-26 13:28:00 -070046#include "instrumentation.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070047#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000048#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000049#include "jit/profiling_info.h"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010050#include "jit/jit_scoped_code_cache_write.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010051#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080052#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070053#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070054#include "object_callbacks.h"
David Sehr82d046e2018-04-23 08:14:19 -070055#include "profile/profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070056#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070057#include "stack.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000058#include "thread-current-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010059#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080060
61namespace art {
62namespace jit {
63
Nicolas Geoffray933330a2016-03-16 14:20:06 +000064static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
65static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
66
Vladimir Marko2196c652017-11-30 16:16:07 +000067class JitCodeCache::JniStubKey {
68 public:
69 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
70 : shorty_(method->GetShorty()),
71 is_static_(method->IsStatic()),
72 is_fast_native_(method->IsFastNative()),
73 is_critical_native_(method->IsCriticalNative()),
74 is_synchronized_(method->IsSynchronized()) {
75 DCHECK(!(is_fast_native_ && is_critical_native_));
76 }
77
78 bool operator<(const JniStubKey& rhs) const {
79 if (is_static_ != rhs.is_static_) {
80 return rhs.is_static_;
81 }
82 if (is_synchronized_ != rhs.is_synchronized_) {
83 return rhs.is_synchronized_;
84 }
85 if (is_fast_native_ != rhs.is_fast_native_) {
86 return rhs.is_fast_native_;
87 }
88 if (is_critical_native_ != rhs.is_critical_native_) {
89 return rhs.is_critical_native_;
90 }
91 return strcmp(shorty_, rhs.shorty_) < 0;
92 }
93
94 // Update the shorty to point to another method's shorty. Call this function when removing
95 // the method that references the old shorty from JniCodeData and not removing the entire
96 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
97 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
98 const char* shorty = method->GetShorty();
99 DCHECK_STREQ(shorty_, shorty);
100 shorty_ = shorty;
101 }
102
103 private:
104 // The shorty points to a DexFile data and may need to change
105 // to point to the same shorty in a different DexFile.
106 mutable const char* shorty_;
107
108 const bool is_static_;
109 const bool is_fast_native_;
110 const bool is_critical_native_;
111 const bool is_synchronized_;
112};
113
114class JitCodeCache::JniStubData {
115 public:
116 JniStubData() : code_(nullptr), methods_() {}
117
118 void SetCode(const void* code) {
119 DCHECK(code != nullptr);
120 code_ = code;
121 }
122
Vladimir Markocce414f2019-10-07 08:51:33 +0100123 void UpdateEntryPoints(const void* entrypoint) REQUIRES_SHARED(Locks::mutator_lock_) {
124 DCHECK(IsCompiled());
125 DCHECK(entrypoint == OatQuickMethodHeader::FromCodePointer(GetCode())->GetEntryPoint());
126 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
127 for (ArtMethod* m : GetMethods()) {
128 // Because `m` might be in the process of being deleted:
129 // - Call the dedicated method instead of the more generic UpdateMethodsCode
Vladimir Marko5115a4d2019-10-17 14:56:47 +0100130 // - Check the class status without a full read barrier; use ReadBarrier::IsMarked().
131 bool can_set_entrypoint = true;
132 if (NeedsClinitCheckBeforeCall(m)) {
133 // To avoid resurrecting an unreachable object, we must not use a full read
134 // barrier but we do not want to miss updating an entrypoint under common
135 // circumstances, i.e. during a GC the class becomes visibly initialized,
136 // the method becomes hot, we compile the thunk and want to update the
137 // entrypoint while the method's declaring class field still points to the
138 // from-space class object with the old status. Therefore we read the
139 // declaring class without a read barrier and check if it's already marked.
140 // If yes, we check the status of the to-space class object as intended.
141 // Otherwise, there is no to-space object and the from-space class object
142 // contains the most recent value of the status field; even if this races
143 // with another thread doing a read barrier and updating the status, that's
144 // no different from a race with a thread that just updates the status.
145 // Such race can happen only for the zygote method pre-compilation, as we
146 // otherwise compile only thunks for methods of visibly initialized classes.
147 ObjPtr<mirror::Class> klass = m->GetDeclaringClass<kWithoutReadBarrier>();
148 ObjPtr<mirror::Class> marked = ReadBarrier::IsMarked(klass.Ptr());
149 ObjPtr<mirror::Class> checked_klass = (marked != nullptr) ? marked : klass;
150 can_set_entrypoint = checked_klass->IsVisiblyInitialized();
151 }
152 if (can_set_entrypoint) {
Vladimir Markocce414f2019-10-07 08:51:33 +0100153 instrum->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
154 }
155 }
156 }
157
Vladimir Marko2196c652017-11-30 16:16:07 +0000158 const void* GetCode() const {
159 return code_;
160 }
161
162 bool IsCompiled() const {
163 return GetCode() != nullptr;
164 }
165
166 void AddMethod(ArtMethod* method) {
167 if (!ContainsElement(methods_, method)) {
168 methods_.push_back(method);
169 }
170 }
171
172 const std::vector<ArtMethod*>& GetMethods() const {
173 return methods_;
174 }
175
David Srbecky41617b12020-03-18 21:19:06 +0000176 void RemoveMethodsIn(const LinearAlloc& alloc) REQUIRES_SHARED(Locks::mutator_lock_) {
177 auto kept_end = std::partition(
Vladimir Marko2196c652017-11-30 16:16:07 +0000178 methods_.begin(),
179 methods_.end(),
David Srbecky41617b12020-03-18 21:19:06 +0000180 [&alloc](ArtMethod* method) { return !alloc.ContainsUnsafe(method); });
181 for (auto it = kept_end; it != methods_.end(); it++) {
182 VLOG(jit) << "JIT removed (JNI) " << (*it)->PrettyMethod() << ": " << code_;
183 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000184 methods_.erase(kept_end, methods_.end());
185 }
186
David Srbecky41617b12020-03-18 21:19:06 +0000187 bool RemoveMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000188 auto it = std::find(methods_.begin(), methods_.end(), method);
189 if (it != methods_.end()) {
David Srbecky41617b12020-03-18 21:19:06 +0000190 VLOG(jit) << "JIT removed (JNI) " << (*it)->PrettyMethod() << ": " << code_;
Vladimir Marko2196c652017-11-30 16:16:07 +0000191 methods_.erase(it);
192 return true;
193 } else {
194 return false;
195 }
196 }
197
198 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
199 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
200 }
201
202 private:
203 const void* code_;
204 std::vector<ArtMethod*> methods_;
205};
206
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000207JitCodeCache* JitCodeCache::Create(bool used_only_for_profile_data,
208 bool rwx_memory_allowed,
209 bool is_zygote,
210 std::string* error_msg) {
211 // Register for membarrier expedited sync core if JIT will be generating code.
212 if (!used_only_for_profile_data) {
213 if (art::membarrier(art::MembarrierCommand::kRegisterPrivateExpeditedSyncCore) != 0) {
214 // MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE ensures that CPU instruction pipelines are
215 // flushed and it's used when adding code to the JIT. The memory used by the new code may
216 // have just been released and, in theory, the old code could still be in a pipeline.
217 VLOG(jit) << "Kernel does not support membarrier sync-core";
218 }
219 }
220
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100221 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000222 // Check whether the provided max capacity in options is below 1GB.
223 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
224 // We need to have 32 bit offsets from method headers in code cache which point to things
225 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
226 // Ensure we're below 1 GB to be safe.
227 if (max_capacity > 1 * GB) {
228 std::ostringstream oss;
229 oss << "Maxium code cache capacity is limited to 1 GB, "
230 << PrettySize(max_capacity) << " is too big";
231 *error_msg = oss.str();
232 return nullptr;
233 }
234
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100235 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100236 JitMemoryRegion region;
237 if (!region.Initialize(initial_capacity,
238 max_capacity,
239 rwx_memory_allowed,
240 is_zygote,
241 error_msg)) {
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000242 return nullptr;
243 }
244
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100245 std::unique_ptr<JitCodeCache> jit_code_cache(new JitCodeCache());
246 if (is_zygote) {
247 // Zygote should never collect code to share the memory with the children.
248 jit_code_cache->garbage_collect_code_ = false;
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000249 jit_code_cache->shared_region_ = std::move(region);
250 } else {
251 jit_code_cache->private_region_ = std::move(region);
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100252 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000253
254 VLOG(jit) << "Created jit code cache: initial capacity="
255 << PrettySize(initial_capacity)
256 << ", maximum capacity="
257 << PrettySize(max_capacity);
258
259 return jit_code_cache.release();
260}
261
262JitCodeCache::JitCodeCache()
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100263 : is_weak_access_enabled_(true),
264 inline_cache_cond_("Jit inline cache condition variable", *Locks::jit_lock_),
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100265 zygote_map_(&shared_region_),
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100266 lock_cond_("Jit code cache condition variable", *Locks::jit_lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100267 collection_in_progress_(false),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000268 last_collection_increased_code_cache_(false),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100269 garbage_collect_code_(true),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000270 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000271 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000272 number_of_collections_(0),
273 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
274 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100275 histogram_profiling_info_memory_use_("Memory used for profiling info", 16) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800276}
277
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000278JitCodeCache::~JitCodeCache() {}
279
Alex Light280e6c32020-03-03 13:52:07 -0800280bool JitCodeCache::PrivateRegionContainsPc(const void* ptr) const {
281 return private_region_.IsInExecSpace(ptr);
282}
283
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100284bool JitCodeCache::ContainsPc(const void* ptr) const {
Alex Light280e6c32020-03-03 13:52:07 -0800285 return PrivateRegionContainsPc(ptr) || shared_region_.IsInExecSpace(ptr);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800286}
287
Alex Light2d441b12018-06-08 15:33:21 -0700288bool JitCodeCache::WillExecuteJitCode(ArtMethod* method) {
289 ScopedObjectAccess soa(art::Thread::Current());
290 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
291 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
292 return true;
293 } else if (method->GetEntryPointFromQuickCompiledCode() == GetQuickInstrumentationEntryPoint()) {
294 return FindCompiledCodeForInstrumentation(method) != nullptr;
295 }
296 return false;
297}
298
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000299bool JitCodeCache::ContainsMethod(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100300 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000301 if (UNLIKELY(method->IsNative())) {
302 auto it = jni_stubs_map_.find(JniStubKey(method));
303 if (it != jni_stubs_map_.end() &&
304 it->second.IsCompiled() &&
305 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000306 return true;
307 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000308 } else {
309 for (const auto& it : method_code_map_) {
310 if (it.second == method) {
311 return true;
312 }
313 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100314 if (zygote_map_.ContainsMethod(method)) {
315 return true;
316 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000317 }
318 return false;
319}
320
Vladimir Marko2196c652017-11-30 16:16:07 +0000321const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
322 DCHECK(method->IsNative());
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100323 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000324 auto it = jni_stubs_map_.find(JniStubKey(method));
325 if (it != jni_stubs_map_.end()) {
326 JniStubData& data = it->second;
327 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
328 return data.GetCode();
329 }
330 }
331 return nullptr;
332}
333
Alex Light2d441b12018-06-08 15:33:21 -0700334const void* JitCodeCache::FindCompiledCodeForInstrumentation(ArtMethod* method) {
Alex Light839f53a2018-07-10 15:46:14 -0700335 // If jit-gc is still on we use the SavedEntryPoint field for doing that and so cannot use it to
336 // find the instrumentation entrypoint.
337 if (LIKELY(GetGarbageCollectCode())) {
Alex Light2d441b12018-06-08 15:33:21 -0700338 return nullptr;
339 }
340 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
341 if (info == nullptr) {
342 return nullptr;
343 }
344 // When GC is disabled for trampoline tracing we will use SavedEntrypoint to hold the actual
345 // jit-compiled version of the method. If jit-gc is disabled for other reasons this will just be
346 // nullptr.
347 return info->GetSavedEntryPoint();
348}
349
Nicolas Geoffray32384402019-07-17 20:06:44 +0100350const void* JitCodeCache::GetSavedEntryPointOfPreCompiledMethod(ArtMethod* method) {
Nicolas Geoffray4cbb51a2020-02-07 11:25:54 +0000351 if (method->IsPreCompiled()) {
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100352 const void* code_ptr = nullptr;
Nicolas Geoffray32384402019-07-17 20:06:44 +0100353 if (method->GetDeclaringClass()->GetClassLoader() == nullptr) {
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100354 code_ptr = zygote_map_.GetCodeFor(method);
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100355 } else {
Nicolas Geoffray32384402019-07-17 20:06:44 +0100356 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
357 auto it = saved_compiled_methods_map_.find(method);
358 if (it != saved_compiled_methods_map_.end()) {
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100359 code_ptr = it->second;
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100360 }
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100361 }
362 if (code_ptr != nullptr) {
363 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
364 return method_header->GetEntryPoint();
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100365 }
366 }
367 return nullptr;
368}
369
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100370bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
371 bool in_collection = false;
372 while (collection_in_progress_) {
373 in_collection = true;
374 lock_cond_.Wait(self);
375 }
376 return in_collection;
377}
378
379static uintptr_t FromCodeToAllocation(const void* code) {
Orion Hodsone764f382019-06-27 12:56:48 +0100380 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100381 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
382}
383
David Srbecky30fd8512020-02-20 20:27:58 +0000384static const void* FromAllocationToCode(const uint8_t* alloc) {
385 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
386 return reinterpret_cast<const void*>(alloc + RoundUp(sizeof(OatQuickMethodHeader), alignment));
387}
388
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000389static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
390 // The length of the table is stored just before the stack map (and therefore at the end of
391 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
392 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
393}
394
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000395static void DCheckRootsAreValid(const std::vector<Handle<mirror::Object>>& roots,
396 bool is_shared_region)
Alex Light3e36a9c2018-06-19 09:45:05 -0700397 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
398 if (!kIsDebugBuild) {
399 return;
400 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700401 // Put all roots in `roots_data`.
Vladimir Markoac3ac682018-09-20 11:01:43 +0100402 for (Handle<mirror::Object> object : roots) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700403 // Ensure the string is strongly interned. b/32995596
404 if (object->IsString()) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100405 ObjPtr<mirror::String> str = object->AsString();
Alex Light3e36a9c2018-06-19 09:45:05 -0700406 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
407 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
408 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000409 // Ensure that we don't put movable objects in the shared region.
410 if (is_shared_region) {
411 CHECK(!Runtime::Current()->GetHeap()->IsMovableObject(object.Get()));
412 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700413 }
414}
415
David Srbecky87fb0322019-08-20 10:34:02 +0100416static const uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000417 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
418 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
419 uint32_t roots = GetNumberOfRoots(data);
420 if (number_of_roots != nullptr) {
421 *number_of_roots = roots;
422 }
423 return data - ComputeRootTableSize(roots);
424}
425
426void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100427 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000428 for (const auto& entry : method_code_map_) {
429 uint32_t number_of_roots = 0;
David Srbecky87fb0322019-08-20 10:34:02 +0100430 const uint8_t* root_table = GetRootTable(entry.first, &number_of_roots);
431 uint8_t* roots_data = private_region_.IsInDataSpace(root_table)
432 ? private_region_.GetWritableDataAddress(root_table)
433 : shared_region_.GetWritableDataAddress(root_table);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000434 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
435 for (uint32_t i = 0; i < number_of_roots; ++i) {
436 // This does not need a read barrier because this is called by GC.
437 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffraye3f775b2019-12-04 14:41:52 +0000438 if (object == nullptr || object == Runtime::GetWeakClassSentinel()) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000439 // entry got deleted in a previous sweep.
Vladimir Markod355acf2019-03-21 17:09:40 +0000440 } else if (object->IsString<kDefaultVerifyFlags>()) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000441 mirror::Object* new_object = visitor->IsMarked(object);
442 // We know the string is marked because it's a strongly-interned string that
443 // is always alive. The IsMarked implementation of the CMS collector returns
444 // null for newly allocated objects, but we know those haven't moved. Therefore,
445 // only update the entry if we get a different non-null string.
446 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
447 // out of the weak access/creation pause. b/32167580
448 if (new_object != nullptr && new_object != object) {
449 DCHECK(new_object->IsString());
450 roots[i] = GcRoot<mirror::Object>(new_object);
451 }
452 } else {
Nicolas Geoffraye3f775b2019-12-04 14:41:52 +0000453 Runtime::ProcessWeakClass(
454 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]),
455 visitor,
456 Runtime::GetWeakClassSentinel());
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000457 }
458 }
459 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000460 // Walk over inline caches to clear entries containing unloaded classes.
461 for (ProfilingInfo* info : profiling_infos_) {
462 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
463 InlineCache* cache = &info->cache_[i];
464 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffraye3f775b2019-12-04 14:41:52 +0000465 Runtime::ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000466 }
467 }
468 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000469}
470
David Srbecky30fd8512020-02-20 20:27:58 +0000471void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
Nicolas Geoffrayae982f92018-12-08 12:31:10 +0000472 if (IsInZygoteExecSpace(code_ptr)) {
473 // No need to free, this is shared memory.
474 return;
475 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100476 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky30fd8512020-02-20 20:27:58 +0000477 const uint8_t* data = nullptr;
Vladimir Marko2196c652017-11-30 16:16:07 +0000478 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
David Srbecky30fd8512020-02-20 20:27:58 +0000479 data = GetRootTable(code_ptr);
Vladimir Marko2196c652017-11-30 16:16:07 +0000480 } // else this is a JNI stub without any data.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100481
David Srbecky30fd8512020-02-20 20:27:58 +0000482 FreeLocked(&private_region_, reinterpret_cast<uint8_t*>(allocation), data);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100483}
484
Mingyao Yang063fc772016-08-02 11:02:54 -0700485void JitCodeCache::FreeAllMethodHeaders(
486 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700487 // We need to remove entries in method_headers from CHA dependencies
488 // first since once we do FreeCode() below, the memory can be reused
489 // so it's possible for the same method_header to start representing
490 // different compile code.
Alex Light33b7b5d2018-08-07 19:13:51 +0000491 {
492 MutexLock mu2(Thread::Current(), *Locks::cha_lock_);
493 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
494 ->RemoveDependentsWithMethodHeaders(method_headers);
495 }
496
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100497 ScopedCodeCacheWrite scc(private_region_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700498 for (const OatQuickMethodHeader* method_header : method_headers) {
David Srbecky30fd8512020-02-20 20:27:58 +0000499 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700500 }
David Srbecky30fd8512020-02-20 20:27:58 +0000501
502 // We have potentially removed a lot of debug info. Do maintenance pass to save space.
503 RepackNativeDebugInfoForJit();
David Srbecky41617b12020-03-18 21:19:06 +0000504
505 // Check that the set of compiled methods exactly matches native debug information.
506 if (kIsDebugBuild) {
507 std::map<const void*, ArtMethod*> compiled_methods;
508 VisitAllMethods([&](const void* addr, ArtMethod* method) {
509 CHECK(addr != nullptr && method != nullptr);
510 compiled_methods.emplace(addr, method);
511 });
512 std::set<const void*> debug_info;
513 ForEachNativeDebugSymbol([&](const void* addr, size_t, const char* name) {
514 addr = AlignDown(addr, GetInstructionSetInstructionAlignment(kRuntimeISA)); // Thumb-bit.
515 CHECK(debug_info.emplace(addr).second) << "Duplicate debug info: " << addr << " " << name;
516 CHECK_EQ(compiled_methods.count(addr), 1u) << "Extra debug info: " << addr << " " << name;
517 });
518 if (!debug_info.empty()) { // If debug-info generation is enabled.
519 for (auto it : compiled_methods) {
520 CHECK_EQ(debug_info.count(it.first), 1u) << "No debug info: " << it.second->PrettyMethod();
521 }
522 }
523 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700524}
525
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100526void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800527 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700528 // We use a set to first collect all method_headers whose code need to be
529 // removed. We need to free the underlying code after we remove CHA dependencies
530 // for entries in this set. And it's more efficient to iterate through
531 // the CHA dependency map just once with an unordered_set.
532 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000533 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100534 MutexLock mu(self, *Locks::jit_lock_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700535 // We do not check if a code cache GC is in progress, as this method comes
536 // with the classlinker_classes_lock_ held, and suspending ourselves could
537 // lead to a deadlock.
538 {
Vladimir Marko2196c652017-11-30 16:16:07 +0000539 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
540 it->second.RemoveMethodsIn(alloc);
541 if (it->second.GetMethods().empty()) {
542 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
543 it = jni_stubs_map_.erase(it);
544 } else {
545 it->first.UpdateShorty(it->second.GetMethods().front());
546 ++it;
547 }
548 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700549 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
550 if (alloc.ContainsUnsafe(it->second)) {
551 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
David Srbecky41617b12020-03-18 21:19:06 +0000552 VLOG(jit) << "JIT removed " << it->second->PrettyMethod() << ": " << it->first;
Mingyao Yang063fc772016-08-02 11:02:54 -0700553 it = method_code_map_.erase(it);
554 } else {
555 ++it;
556 }
557 }
558 }
559 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
560 if (alloc.ContainsUnsafe(it->first)) {
561 // Note that the code has already been pushed to method_headers in the loop
562 // above and is going to be removed in FreeCode() below.
563 it = osr_code_map_.erase(it);
564 } else {
565 ++it;
566 }
567 }
568 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
569 ProfilingInfo* info = *it;
570 if (alloc.ContainsUnsafe(info->GetMethod())) {
571 info->GetMethod()->SetProfilingInfo(nullptr);
David Srbecky87fb0322019-08-20 10:34:02 +0100572 private_region_.FreeWritableData(reinterpret_cast<uint8_t*>(info));
Mingyao Yang063fc772016-08-02 11:02:54 -0700573 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000574 } else {
575 ++it;
576 }
577 }
David Srbecky521644b2020-03-21 13:17:52 +0000578 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000579 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100580}
581
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000582bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
583 return kUseReadBarrier
584 ? self->GetWeakRefAccessEnabled()
Orion Hodson88591fe2018-03-06 13:35:43 +0000585 : is_weak_access_enabled_.load(std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000586}
587
588void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
589 if (IsWeakAccessEnabled(self)) {
590 return;
591 }
592 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100593 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000594 while (!IsWeakAccessEnabled(self)) {
595 inline_cache_cond_.Wait(self);
596 }
597}
598
599void JitCodeCache::BroadcastForInlineCacheAccess() {
600 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100601 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000602 inline_cache_cond_.Broadcast(self);
603}
604
605void JitCodeCache::AllowInlineCacheAccess() {
606 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000607 is_weak_access_enabled_.store(true, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000608 BroadcastForInlineCacheAccess();
609}
610
611void JitCodeCache::DisallowInlineCacheAccess() {
612 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000613 is_weak_access_enabled_.store(false, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000614}
615
616void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
617 Handle<mirror::ObjectArray<mirror::Class>> array) {
618 WaitUntilInlineCacheAccessible(Thread::Current());
619 // Note that we don't need to lock `lock_` here, the compiler calling
620 // this method has already ensured the inline cache will not be deleted.
621 for (size_t in_cache = 0, in_array = 0;
622 in_cache < InlineCache::kIndividualCacheSize;
623 ++in_cache) {
624 mirror::Class* object = ic.classes_[in_cache].Read();
625 if (object != nullptr) {
626 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000627 }
628 }
629}
630
David Srbeckye36e7f22018-11-14 14:21:23 +0000631static void ClearMethodCounter(ArtMethod* method, bool was_warm)
632 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf044c222017-05-31 15:27:54 -0700633 if (was_warm) {
Vladimir Markoc945e0d2018-07-18 17:26:45 +0100634 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700635 }
636 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
637 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100638 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
639 // the warmup threshold is 1.
640 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
641 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700642}
643
Alex Light33b7b5d2018-08-07 19:13:51 +0000644void JitCodeCache::WaitForPotentialCollectionToCompleteRunnable(Thread* self) {
645 while (collection_in_progress_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100646 Locks::jit_lock_->Unlock(self);
Alex Light33b7b5d2018-08-07 19:13:51 +0000647 {
648 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100649 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000650 WaitForPotentialCollectionToComplete(self);
651 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100652 Locks::jit_lock_->Lock(self);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100653 }
654}
655
David Srbeckyadb66f92019-10-10 12:59:43 +0000656bool JitCodeCache::Commit(Thread* self,
657 JitMemoryRegion* region,
658 ArtMethod* method,
659 ArrayRef<const uint8_t> reserved_code,
660 ArrayRef<const uint8_t> code,
661 ArrayRef<const uint8_t> reserved_data,
662 const std::vector<Handle<mirror::Object>>& roots,
663 ArrayRef<const uint8_t> stack_map,
David Srbecky41617b12020-03-18 21:19:06 +0000664 const std::vector<uint8_t>& debug_info,
665 bool is_full_debug_info,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100666 CompilationKind compilation_kind,
David Srbeckyadb66f92019-10-10 12:59:43 +0000667 bool has_should_deoptimize_flag,
668 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100669 DCHECK(!method->IsNative() || (compilation_kind != CompilationKind::kOsr));
Alex Light33b7b5d2018-08-07 19:13:51 +0000670
671 if (!method->IsNative()) {
672 // We need to do this before grabbing the lock_ because it needs to be able to see the string
673 // InternTable. Native methods do not have roots.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000674 DCheckRootsAreValid(roots, IsSharedRegion(*region));
Alex Light33b7b5d2018-08-07 19:13:51 +0000675 }
676
David Srbeckyadb66f92019-10-10 12:59:43 +0000677 const uint8_t* roots_data = reserved_data.data();
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100678 size_t root_table_size = ComputeRootTableSize(roots.size());
David Srbecky87fb0322019-08-20 10:34:02 +0100679 const uint8_t* stack_map_data = roots_data + root_table_size;
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100680
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100681 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000682 // We need to make sure that there will be no jit-gcs going on and wait for any ongoing one to
683 // finish.
684 WaitForPotentialCollectionToCompleteRunnable(self);
David Srbeckyadb66f92019-10-10 12:59:43 +0000685 const uint8_t* code_ptr = region->CommitCode(
686 reserved_code, code, stack_map_data, has_should_deoptimize_flag);
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100687 if (code_ptr == nullptr) {
David Srbeckyadb66f92019-10-10 12:59:43 +0000688 return false;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100689 }
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100690 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
691
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100692 // Commit roots and stack maps before updating the entry point.
David Srbeckyadb66f92019-10-10 12:59:43 +0000693 if (!region->CommitData(reserved_data, roots, stack_map)) {
694 return false;
Orion Hodsonaeb02232019-06-25 14:18:18 +0100695 }
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100696
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100697 number_of_compilations_++;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100698
David Srbecky41617b12020-03-18 21:19:06 +0000699 // We need to update the debug info before the entry point gets set.
700 // At the same time we want to do under JIT lock so that debug info and JIT maps are in sync.
701 if (!debug_info.empty()) {
702 // NB: Don't allow packing of full info since it would remove non-backtrace data.
703 AddNativeDebugInfoForJit(code_ptr, debug_info, /*allow_packing=*/ !is_full_debug_info);
704 }
705
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000706 // We need to update the entry point in the runnable state for the instrumentation.
707 {
Alex Light33b7b5d2018-08-07 19:13:51 +0000708 // The following needs to be guarded by cha_lock_ also. Otherwise it's possible that the
709 // compiled code is considered invalidated by some class linking, but below we still make the
710 // compiled code valid for the method. Need cha_lock_ for checking all single-implementation
711 // flags and register dependencies.
Mingyao Yang063fc772016-08-02 11:02:54 -0700712 MutexLock cha_mu(self, *Locks::cha_lock_);
713 bool single_impl_still_valid = true;
714 for (ArtMethod* single_impl : cha_single_implementation_list) {
715 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700716 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
717 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700718 single_impl_still_valid = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700719 ClearMethodCounter(method, /*was_warm=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700720 break;
721 }
722 }
723
724 // Discard the code if any single-implementation assumptions are now invalid.
Orion Hodson31492522019-06-18 12:13:49 +0100725 if (UNLIKELY(!single_impl_still_valid)) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700726 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
David Srbeckyadb66f92019-10-10 12:59:43 +0000727 return false;
Mingyao Yang063fc772016-08-02 11:02:54 -0700728 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000729 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800730 << "Should not be using cha on debuggable apps/runs!";
731
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100732 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mingyao Yang063fc772016-08-02 11:02:54 -0700733 for (ArtMethod* single_impl : cha_single_implementation_list) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100734 class_linker->GetClassHierarchyAnalysis()->AddDependency(single_impl, method, method_header);
Mingyao Yang063fc772016-08-02 11:02:54 -0700735 }
736
Vladimir Marko2196c652017-11-30 16:16:07 +0000737 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000738 auto it = jni_stubs_map_.find(JniStubKey(method));
739 DCHECK(it != jni_stubs_map_.end())
740 << "Entry inserted in NotifyCompilationOf() should be alive.";
741 JniStubData* data = &it->second;
742 DCHECK(ContainsElement(data->GetMethods(), method))
743 << "Entry inserted in NotifyCompilationOf() should contain this method.";
744 data->SetCode(code_ptr);
Vladimir Markocce414f2019-10-07 08:51:33 +0100745 data->UpdateEntryPoints(method_header->GetEntryPoint());
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100746 } else {
Nicolas Geoffray32384402019-07-17 20:06:44 +0100747 if (method->IsPreCompiled() && IsSharedRegion(*region)) {
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100748 zygote_map_.Put(code_ptr, method);
749 } else {
750 method_code_map_.Put(code_ptr, method);
751 }
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100752 if (compilation_kind == CompilationKind::kOsr) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000753 number_of_osr_compilations_++;
754 osr_code_map_.Put(method, code_ptr);
Vladimir Marko5115a4d2019-10-17 14:56:47 +0100755 } else if (NeedsClinitCheckBeforeCall(method) &&
756 !method->GetDeclaringClass()->IsVisiblyInitialized()) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100757 // This situation currently only occurs in the jit-zygote mode.
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100758 DCHECK(!garbage_collect_code_);
Nicolas Geoffray32384402019-07-17 20:06:44 +0100759 DCHECK(method->IsPreCompiled());
760 // The shared region can easily be queried. For the private region, we
761 // use a side map.
762 if (!IsSharedRegion(*region)) {
763 saved_compiled_methods_map_.Put(method, code_ptr);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100764 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000765 } else {
766 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
767 method, method_header->GetEntryPoint());
768 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000769 }
Nicolas Geoffrayde3e51d2019-11-28 16:29:55 +0000770 if (collection_in_progress_) {
771 // We need to update the live bitmap if there is a GC to ensure it sees this new
772 // code.
773 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
774 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000775 VLOG(jit)
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100776 << "JIT added (kind=" << compilation_kind << ") "
David Sehr709b0702016-10-13 09:12:37 -0700777 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000778 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
779 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
780 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700781 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
782 method_header->GetCodeSize());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000783 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100784
David Srbeckyadb66f92019-10-10 12:59:43 +0000785 return true;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100786}
787
788size_t JitCodeCache::CodeCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100789 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000790 return CodeCacheSizeLocked();
791}
792
Orion Hodsoneced6922017-06-01 10:54:28 +0100793bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000794 // This function is used only for testing and only with non-native methods.
795 CHECK(!method->IsNative());
796
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100797 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +0100798
Vladimir Marko2196c652017-11-30 16:16:07 +0000799 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
800 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +0100801
802 if (!in_cache) {
803 return false;
804 }
805
David Srbeckye36e7f22018-11-14 14:21:23 +0000806 method->SetCounter(0);
Orion Hodsoneced6922017-06-01 10:54:28 +0100807 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
808 method, GetQuickToInterpreterBridge());
809 VLOG(jit)
810 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
811 << ArtMethod::PrettyMethod(method) << "@" << method
812 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
813 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
814 return true;
815}
816
Vladimir Marko2196c652017-11-30 16:16:07 +0000817bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
818 if (LIKELY(!method->IsNative())) {
819 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
820 if (info != nullptr) {
821 RemoveElement(profiling_infos_, info);
822 }
823 method->SetProfilingInfo(nullptr);
824 }
825
826 bool in_cache = false;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100827 ScopedCodeCacheWrite ccw(private_region_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000828 if (UNLIKELY(method->IsNative())) {
829 auto it = jni_stubs_map_.find(JniStubKey(method));
830 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
831 in_cache = true;
832 if (it->second.GetMethods().empty()) {
833 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100834 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +0000835 }
836 jni_stubs_map_.erase(it);
837 } else {
838 it->first.UpdateShorty(it->second.GetMethods().front());
839 }
840 }
841 } else {
842 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
843 if (it->second == method) {
844 in_cache = true;
845 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100846 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +0000847 }
David Srbecky41617b12020-03-18 21:19:06 +0000848 VLOG(jit) << "JIT removed " << it->second->PrettyMethod() << ": " << it->first;
Vladimir Marko2196c652017-11-30 16:16:07 +0000849 it = method_code_map_.erase(it);
850 } else {
851 ++it;
852 }
853 }
854
855 auto osr_it = osr_code_map_.find(method);
856 if (osr_it != osr_code_map_.end()) {
857 osr_code_map_.erase(osr_it);
858 }
859 }
860
861 return in_cache;
862}
863
Alex Lightdba61482016-12-21 08:20:29 -0800864// This notifies the code cache that the given method has been redefined and that it should remove
865// any cached information it has on the method. All threads must be suspended before calling this
866// method. The compiled code for the method (if there is any) must not be in any threads call stack.
867void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100868 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700869 RemoveMethodLocked(method, /* release_memory= */ true);
Alex Lightdba61482016-12-21 08:20:29 -0800870}
871
872// This invalidates old_method. Once this function returns one can no longer use old_method to
873// execute code unless it is fixed up. This fixup will happen later in the process of installing a
874// class redefinition.
875// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
876// shouldn't be used since it is no longer logically in the jit code cache.
877// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
878void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100879 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +0000880 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000881 // Update methods in jni_stubs_map_.
882 for (auto& entry : jni_stubs_map_) {
883 JniStubData& data = entry.second;
884 data.MoveObsoleteMethod(old_method, new_method);
885 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000886 return;
887 }
Alex Lightdba61482016-12-21 08:20:29 -0800888 // Update ProfilingInfo to the new one and remove it from the old_method.
889 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
890 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
891 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
892 old_method->SetProfilingInfo(nullptr);
893 // Since the JIT should be paused and all threads suspended by the time this is called these
894 // checks should always pass.
895 DCHECK(!info->IsInUseByCompiler());
896 new_method->SetProfilingInfo(info);
Alex Light2d441b12018-06-08 15:33:21 -0700897 // Get rid of the old saved entrypoint if it is there.
898 info->SetSavedEntryPoint(nullptr);
Alex Lightdba61482016-12-21 08:20:29 -0800899 info->method_ = new_method;
900 }
901 // Update method_code_map_ to point to the new method.
902 for (auto& it : method_code_map_) {
903 if (it.second == old_method) {
904 it.second = new_method;
905 }
906 }
907 // Update osr_code_map_ to point to the new method.
908 auto code_map = osr_code_map_.find(old_method);
909 if (code_map != osr_code_map_.end()) {
910 osr_code_map_.Put(new_method, code_map->second);
911 osr_code_map_.erase(old_method);
912 }
913}
914
Alex Lightb28e3042020-03-06 13:02:46 -0800915void JitCodeCache::TransitionToDebuggable() {
Nicolas Geoffrayc76232e2020-03-18 11:23:33 +0000916 // Check that none of our methods have an entrypoint in the zygote exec
917 // space (this should be taken care of by
918 // ClassLinker::UpdateEntryPointsClassVisitor.
Alex Lightb28e3042020-03-06 13:02:46 -0800919 {
920 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayc76232e2020-03-18 11:23:33 +0000921 if (kIsDebugBuild) {
922 for (const auto& it : method_code_map_) {
923 ArtMethod* method = it.second;
924 DCHECK(!method->IsPreCompiled());
925 DCHECK(!IsInZygoteExecSpace(method->GetEntryPointFromQuickCompiledCode()));
Nicolas Geoffrayfc47d6b2020-03-11 15:05:43 +0000926 }
Alex Lightb28e3042020-03-06 13:02:46 -0800927 }
Nicolas Geoffrayfc47d6b2020-03-11 15:05:43 +0000928 // Not strictly necessary, but this map is useless now.
929 saved_compiled_methods_map_.clear();
Alex Lightb28e3042020-03-06 13:02:46 -0800930 }
Nicolas Geoffrayc76232e2020-03-18 11:23:33 +0000931 if (kIsDebugBuild) {
932 for (const auto& entry : zygote_map_) {
933 ArtMethod* method = entry.method;
934 if (method != nullptr) {
935 DCHECK(!method->IsPreCompiled());
936 DCHECK(!IsInZygoteExecSpace(method->GetEntryPointFromQuickCompiledCode()));
937 }
Nicolas Geoffrayfc47d6b2020-03-11 15:05:43 +0000938 }
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000939 }
940}
941
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000942size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +0100943 return GetCurrentRegion()->GetUsedMemoryForCode();
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100944}
945
946size_t JitCodeCache::DataCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100947 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000948 return DataCacheSizeLocked();
949}
950
951size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +0100952 return GetCurrentRegion()->GetUsedMemoryForData();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800953}
954
David Srbeckyadb66f92019-10-10 12:59:43 +0000955bool JitCodeCache::Reserve(Thread* self,
956 JitMemoryRegion* region,
957 size_t code_size,
958 size_t stack_map_size,
959 size_t number_of_roots,
960 ArtMethod* method,
961 /*out*/ArrayRef<const uint8_t>* reserved_code,
962 /*out*/ArrayRef<const uint8_t>* reserved_data) {
963 code_size = OatQuickMethodHeader::InstructionAlignedSize() + code_size;
964 size_t data_size = RoundUp(ComputeRootTableSize(number_of_roots) + stack_map_size, sizeof(void*));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000965
David Srbeckyadb66f92019-10-10 12:59:43 +0000966 const uint8_t* code;
967 const uint8_t* data;
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100968 while (true) {
969 bool at_max_capacity = false;
David Srbeckyadb66f92019-10-10 12:59:43 +0000970 {
971 ScopedThreadSuspension sts(self, kSuspended);
972 MutexLock mu(self, *Locks::jit_lock_);
973 WaitForPotentialCollectionToComplete(self);
974 ScopedCodeCacheWrite ccw(*region);
975 code = region->AllocateCode(code_size);
976 data = region->AllocateData(data_size);
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100977 at_max_capacity = IsAtMaxCapacity();
David Srbeckyadb66f92019-10-10 12:59:43 +0000978 }
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100979 if (code != nullptr && data != nullptr) {
980 break;
David Srbeckyadb66f92019-10-10 12:59:43 +0000981 }
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100982 Free(self, region, code, data);
983 if (at_max_capacity) {
984 VLOG(jit) << "JIT failed to allocate code of size "
985 << PrettySize(code_size)
986 << ", and data of size "
987 << PrettySize(data_size);
988 return false;
989 }
990 // Run a code cache collection and try again.
991 GarbageCollectCache(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100992 }
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +0100993
David Srbeckyadb66f92019-10-10 12:59:43 +0000994 *reserved_code = ArrayRef<const uint8_t>(code, code_size);
995 *reserved_data = ArrayRef<const uint8_t>(data, data_size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100996
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100997 MutexLock mu(self, *Locks::jit_lock_);
David Srbeckyadb66f92019-10-10 12:59:43 +0000998 histogram_code_memory_use_.AddValue(code_size);
999 if (code_size > kCodeSizeLogThreshold) {
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001000 LOG(INFO) << "JIT allocated "
David Srbeckyadb66f92019-10-10 12:59:43 +00001001 << PrettySize(code_size)
1002 << " for compiled code of "
1003 << ArtMethod::PrettyMethod(method);
1004 }
1005 histogram_stack_map_memory_use_.AddValue(data_size);
1006 if (data_size > kStackMapSizeLogThreshold) {
1007 LOG(INFO) << "JIT allocated "
1008 << PrettySize(data_size)
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001009 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001010 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001011 }
David Srbeckyadb66f92019-10-10 12:59:43 +00001012 return true;
1013}
1014
1015void JitCodeCache::Free(Thread* self,
1016 JitMemoryRegion* region,
1017 const uint8_t* code,
1018 const uint8_t* data) {
1019 MutexLock mu(self, *Locks::jit_lock_);
1020 ScopedCodeCacheWrite ccw(*region);
David Srbecky30fd8512020-02-20 20:27:58 +00001021 FreeLocked(region, code, data);
1022}
1023
1024void JitCodeCache::FreeLocked(JitMemoryRegion* region, const uint8_t* code, const uint8_t* data) {
David Srbeckyadb66f92019-10-10 12:59:43 +00001025 if (code != nullptr) {
David Srbecky30fd8512020-02-20 20:27:58 +00001026 RemoveNativeDebugInfoForJit(reinterpret_cast<const void*>(FromAllocationToCode(code)));
David Srbeckyadb66f92019-10-10 12:59:43 +00001027 region->FreeCode(code);
1028 }
1029 if (data != nullptr) {
1030 region->FreeData(data);
1031 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001032}
1033
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001034class MarkCodeClosure final : public Closure {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001035 public:
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001036 MarkCodeClosure(JitCodeCache* code_cache, CodeCacheBitmap* bitmap, Barrier* barrier)
1037 : code_cache_(code_cache), bitmap_(bitmap), barrier_(barrier) {}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001038
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001039 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001040 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001041 DCHECK(thread == Thread::Current() || thread->IsSuspended());
Andreas Gampec7d878d2018-11-19 18:42:06 +00001042 StackVisitor::WalkStack(
1043 [&](const art::StackVisitor* stack_visitor) {
1044 const OatQuickMethodHeader* method_header =
1045 stack_visitor->GetCurrentOatQuickMethodHeader();
1046 if (method_header == nullptr) {
1047 return true;
1048 }
1049 const void* code = method_header->GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001050 if (code_cache_->ContainsPc(code) && !code_cache_->IsInZygoteExecSpace(code)) {
Andreas Gampec7d878d2018-11-19 18:42:06 +00001051 // Use the atomic set version, as multiple threads are executing this code.
1052 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1053 }
1054 return true;
1055 },
1056 thread,
1057 /* context= */ nullptr,
1058 art::StackVisitor::StackWalkKind::kSkipInlinedFrames);
1059
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001060 if (kIsDebugBuild) {
1061 // The stack walking code queries the side instrumentation stack if it
1062 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1063 // must have been seen. We sanity check this below.
Nicolas Geoffraye91e7952020-01-23 10:15:56 +00001064 for (const auto& it : *thread->GetInstrumentationStack()) {
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001065 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1066 // its stack frame, it is not the method owning return_pc_. We just pass null to
1067 // LookupMethodHeader: the method is only checked against in debug builds.
1068 OatQuickMethodHeader* method_header =
Nicolas Geoffraye91e7952020-01-23 10:15:56 +00001069 code_cache_->LookupMethodHeader(it.second.return_pc_, /* method= */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001070 if (method_header != nullptr) {
1071 const void* code = method_header->GetCode();
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001072 CHECK(bitmap_->Test(FromCodeToAllocation(code)));
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001073 }
1074 }
1075 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001076 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001077 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001078
1079 private:
1080 JitCodeCache* const code_cache_;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001081 CodeCacheBitmap* const bitmap_;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001082 Barrier* const barrier_;
1083};
1084
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001085void JitCodeCache::NotifyCollectionDone(Thread* self) {
1086 collection_in_progress_ = false;
1087 lock_cond_.Broadcast(self);
1088}
1089
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001090void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1091 Barrier barrier(0);
1092 size_t threads_running_checkpoint = 0;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001093 MarkCodeClosure closure(this, GetLiveBitmap(), &barrier);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001094 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1095 // Now that we have run our checkpoint, move to a suspended state and wait
1096 // for other threads to run the checkpoint.
1097 ScopedThreadSuspension sts(self, kSuspended);
1098 if (threads_running_checkpoint != 0) {
1099 barrier.Increment(self, threads_running_checkpoint);
1100 }
1101}
1102
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +01001103bool JitCodeCache::IsAtMaxCapacity() const {
1104 return private_region_.GetCurrentCapacity() == private_region_.GetMaxCapacity();
1105}
1106
Nicolas Geoffray35122442016-03-02 12:05:30 +00001107bool JitCodeCache::ShouldDoFullCollection() {
Nicolas Geoffray62dd4e82020-05-10 15:00:56 +01001108 if (IsAtMaxCapacity()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001109 // Always do a full collection when the code cache is full.
1110 return true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001111 } else if (private_region_.GetCurrentCapacity() < kReservedCapacity) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001112 // Always do partial collection when the code cache size is below the reserved
1113 // capacity.
1114 return false;
1115 } else if (last_collection_increased_code_cache_) {
1116 // This time do a full collection.
1117 return true;
1118 } else {
1119 // This time do a partial collection.
1120 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001121 }
1122}
1123
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001124void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001125 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001126 // Wait for an existing collection, or let everyone know we are starting one.
1127 {
1128 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001129 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001130 if (!garbage_collect_code_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001131 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001132 return;
1133 } else if (WaitForPotentialCollectionToComplete(self)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001134 return;
1135 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001136 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001137 live_bitmap_.reset(CodeCacheBitmap::Create(
1138 "code-cache-bitmap",
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001139 reinterpret_cast<uintptr_t>(private_region_.GetExecPages()->Begin()),
1140 reinterpret_cast<uintptr_t>(
1141 private_region_.GetExecPages()->Begin() + private_region_.GetCurrentCapacity() / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001142 collection_in_progress_ = true;
1143 }
1144 }
1145
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001146 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001147 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001148 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001149
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001150 bool do_full_collection = false;
1151 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001152 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001153 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001154 }
1155
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001156 VLOG(jit) << "Do "
1157 << (do_full_collection ? "full" : "partial")
1158 << " code cache collection, code="
1159 << PrettySize(CodeCacheSize())
1160 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001161
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001162 DoCollection(self, /* collect_profiling_info= */ do_full_collection);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001163
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001164 VLOG(jit) << "After code cache collection, code="
1165 << PrettySize(CodeCacheSize())
1166 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001167
1168 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001169 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001170
1171 // Increase the code cache only when we do partial collections.
1172 // TODO: base this strategy on how full the code cache is?
1173 if (do_full_collection) {
1174 last_collection_increased_code_cache_ = false;
1175 } else {
1176 last_collection_increased_code_cache_ = true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001177 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001178 }
1179
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001180 bool next_collection_will_be_full = ShouldDoFullCollection();
1181
1182 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001183 if (next_collection_will_be_full) {
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001184 if (Runtime::Current()->GetJITOptions()->CanCompileBaseline()) {
1185 for (ProfilingInfo* info : profiling_infos_) {
1186 info->SetBaselineHotnessCount(0);
1187 }
1188 } else {
1189 // Save the entry point of methods we have compiled, and update the entry
1190 // point of those methods to the interpreter. If the method is invoked, the
1191 // interpreter will update its entry point to the compiled code and call it.
1192 for (ProfilingInfo* info : profiling_infos_) {
1193 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1194 if (!IsInZygoteDataSpace(info) && ContainsPc(entry_point)) {
1195 info->SetSavedEntryPoint(entry_point);
1196 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
1197 // class of the method. We may be concurrently running a GC which makes accessing
1198 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1199 // checked that the current entry point is JIT compiled code.
1200 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1201 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001202 }
1203 }
1204
Vladimir Marko2196c652017-11-30 16:16:07 +00001205 // Change entry points of native methods back to the GenericJNI entrypoint.
1206 for (const auto& entry : jni_stubs_map_) {
1207 const JniStubData& data = entry.second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001208 if (!data.IsCompiled() || IsInZygoteExecSpace(data.GetCode())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001209 continue;
1210 }
1211 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1212 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1213 const OatQuickMethodHeader* method_header =
1214 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1215 for (ArtMethod* method : data.GetMethods()) {
1216 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1217 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1218 method->SetCounter(new_counter);
1219 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1220 }
1221 }
1222 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001223 }
1224 live_bitmap_.reset(nullptr);
1225 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001226 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001227 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001228 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001229}
1230
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001231void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001232 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001233 std::unordered_set<OatQuickMethodHeader*> method_headers;
1234 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001235 MutexLock mu(self, *Locks::jit_lock_);
Mingyao Yang063fc772016-08-02 11:02:54 -07001236 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001237 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1238 JniStubData* data = &it->second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001239 if (IsInZygoteExecSpace(data->GetCode()) ||
1240 !data->IsCompiled() ||
1241 GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001242 ++it;
1243 } else {
1244 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
David Srbecky41617b12020-03-18 21:19:06 +00001245 for (ArtMethod* method : data->GetMethods()) {
1246 VLOG(jit) << "JIT removed (JNI) " << method->PrettyMethod() << ": " << data->GetCode();
1247 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001248 it = jni_stubs_map_.erase(it);
1249 }
1250 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001251 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1252 const void* code_ptr = it->first;
1253 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001254 if (IsInZygoteExecSpace(code_ptr) || GetLiveBitmap()->Test(allocation)) {
Mingyao Yang063fc772016-08-02 11:02:54 -07001255 ++it;
1256 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001257 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1258 method_headers.insert(header);
David Srbecky41617b12020-03-18 21:19:06 +00001259 VLOG(jit) << "JIT removed " << it->second->PrettyMethod() << ": " << it->first;
Mingyao Yang063fc772016-08-02 11:02:54 -07001260 it = method_code_map_.erase(it);
1261 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001262 }
David Srbecky521644b2020-03-21 13:17:52 +00001263 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001264 }
1265}
1266
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001267bool JitCodeCache::GetGarbageCollectCode() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001268 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001269 return garbage_collect_code_;
1270}
1271
1272void JitCodeCache::SetGarbageCollectCode(bool value) {
1273 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001274 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001275 if (garbage_collect_code_ != value) {
1276 if (garbage_collect_code_) {
1277 // When dynamically disabling the garbage collection, we neee
1278 // to make sure that a potential current collection is finished, and also
1279 // clear the saved entry point in profiling infos to avoid dangling pointers.
1280 WaitForPotentialCollectionToComplete(self);
1281 for (ProfilingInfo* info : profiling_infos_) {
1282 info->SetSavedEntryPoint(nullptr);
1283 }
1284 }
1285 // Update the flag while holding the lock to ensure no thread will try to GC.
1286 garbage_collect_code_ = value;
1287 }
1288}
1289
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001290void JitCodeCache::RemoveMethodBeingCompiled(ArtMethod* method, CompilationKind kind) {
1291 DCHECK(IsMethodBeingCompiled(method, kind));
1292 switch (kind) {
1293 case CompilationKind::kOsr:
1294 current_osr_compilations_.erase(method);
1295 break;
1296 case CompilationKind::kBaseline:
1297 current_baseline_compilations_.erase(method);
1298 break;
1299 case CompilationKind::kOptimized:
1300 current_optimized_compilations_.erase(method);
1301 break;
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001302 }
1303}
1304
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001305void JitCodeCache::AddMethodBeingCompiled(ArtMethod* method, CompilationKind kind) {
1306 DCHECK(!IsMethodBeingCompiled(method, kind));
1307 switch (kind) {
1308 case CompilationKind::kOsr:
1309 current_osr_compilations_.insert(method);
1310 break;
1311 case CompilationKind::kBaseline:
1312 current_baseline_compilations_.insert(method);
1313 break;
1314 case CompilationKind::kOptimized:
1315 current_optimized_compilations_.insert(method);
1316 break;
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001317 }
1318}
1319
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001320bool JitCodeCache::IsMethodBeingCompiled(ArtMethod* method, CompilationKind kind) {
1321 switch (kind) {
1322 case CompilationKind::kOsr:
1323 return ContainsElement(current_osr_compilations_, method);
1324 case CompilationKind::kBaseline:
1325 return ContainsElement(current_baseline_compilations_, method);
1326 case CompilationKind::kOptimized:
1327 return ContainsElement(current_optimized_compilations_, method);
1328 }
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001329}
1330
1331bool JitCodeCache::IsMethodBeingCompiled(ArtMethod* method) {
1332 return ContainsElement(current_optimized_compilations_, method) ||
1333 ContainsElement(current_osr_compilations_, method) ||
1334 ContainsElement(current_baseline_compilations_, method);
1335}
1336
Nicolas Geoffray35122442016-03-02 12:05:30 +00001337void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001338 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001339 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001340 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001341
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001342 if (Runtime::Current()->GetJITOptions()->CanCompileBaseline()) {
1343 // Update to interpreter the methods that have baseline entrypoints and whose baseline
1344 // hotness count is zero.
1345 // Note that these methods may be in thread stack or concurrently revived
1346 // between. That's OK, as the thread executing it will mark it.
1347 for (ProfilingInfo* info : profiling_infos_) {
1348 if (info->GetBaselineHotnessCount() == 0) {
1349 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1350 if (ContainsPc(entry_point)) {
1351 OatQuickMethodHeader* method_header =
1352 OatQuickMethodHeader::FromEntryPoint(entry_point);
1353 if (CodeInfo::IsBaseline(method_header->GetOptimizedCodeInfoPtr())) {
1354 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1355 }
1356 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001357 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001358 }
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001359 // TODO: collect profiling info
1360 // TODO: collect optimized code?
1361 } else {
1362 if (collect_profiling_info) {
1363 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1364 // Also remove the saved entry point from the ProfilingInfo objects.
1365 for (ProfilingInfo* info : profiling_infos_) {
1366 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001367 if (!ContainsPc(ptr) &&
1368 !IsMethodBeingCompiled(info->GetMethod()) &&
1369 !info->IsInUseByCompiler() &&
1370 !IsInZygoteDataSpace(info)) {
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001371 info->GetMethod()->SetProfilingInfo(nullptr);
1372 }
1373
1374 if (info->GetSavedEntryPoint() != nullptr) {
1375 info->SetSavedEntryPoint(nullptr);
1376 // We are going to move this method back to interpreter. Clear the counter now to
1377 // give it a chance to be hot again.
1378 ClearMethodCounter(info->GetMethod(), /*was_warm=*/ true);
1379 }
1380 }
1381 } else if (kIsDebugBuild) {
1382 // Sanity check that the profiling infos do not have a dangling entry point.
1383 for (ProfilingInfo* info : profiling_infos_) {
1384 DCHECK(!Runtime::Current()->IsZygote());
1385 const void* entry_point = info->GetSavedEntryPoint();
1386 DCHECK(entry_point == nullptr || IsInZygoteExecSpace(entry_point));
1387 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001388 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001389 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001390
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001391 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1392 // an entry point is either:
1393 // - an osr compiled code, that will be removed if not in a thread call stack.
1394 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001395 for (const auto& entry : jni_stubs_map_) {
1396 const JniStubData& data = entry.second;
1397 const void* code_ptr = data.GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001398 if (IsInZygoteExecSpace(code_ptr)) {
1399 continue;
1400 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001401 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1402 for (ArtMethod* method : data.GetMethods()) {
1403 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1404 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1405 break;
1406 }
1407 }
1408 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001409 for (const auto& it : method_code_map_) {
1410 ArtMethod* method = it.second;
1411 const void* code_ptr = it.first;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001412 if (IsInZygoteExecSpace(code_ptr)) {
1413 continue;
1414 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001415 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1416 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1417 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1418 }
1419 }
1420
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001421 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001422 // on thread stacks).
1423 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001424 }
1425
1426 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001427 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001428
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001429 // At this point, mutator threads are still running, and entrypoints of methods can
1430 // change. We do know they cannot change to a code cache entry that is not marked,
1431 // therefore we can safely remove those entries.
1432 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001433
Nicolas Geoffray35122442016-03-02 12:05:30 +00001434 if (collect_profiling_info) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001435 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001436 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001437 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001438 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001439 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001440 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1441 // that the compiled code would not get revived. As mutator threads run concurrently,
1442 // they may have revived the compiled code, and now we are in the situation where
1443 // a method has compiled code but no ProfilingInfo.
1444 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1445 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001446 if (ContainsPc(ptr) &&
1447 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001448 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001449 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001450 // No need for this ProfilingInfo object anymore.
David Srbecky87fb0322019-08-20 10:34:02 +01001451 private_region_.FreeWritableData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001452 return true;
1453 }
1454 return false;
1455 });
1456 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001457 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001458}
1459
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001460OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001461 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1462 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001463 // On Thumb-2, the pc is offset by one.
1464 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001465 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001466 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1467 return nullptr;
1468 }
1469
Vladimir Marko2196c652017-11-30 16:16:07 +00001470 if (!kIsDebugBuild) {
1471 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1472 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001473 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001474
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001475 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001476 OatQuickMethodHeader* method_header = nullptr;
1477 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1478 if (method != nullptr && UNLIKELY(method->IsNative())) {
1479 auto it = jni_stubs_map_.find(JniStubKey(method));
1480 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1481 return nullptr;
1482 }
1483 const void* code_ptr = it->second.GetCode();
1484 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1485 if (!method_header->Contains(pc)) {
1486 return nullptr;
1487 }
1488 } else {
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001489 if (shared_region_.IsInExecSpace(reinterpret_cast<const void*>(pc))) {
1490 const void* code_ptr = zygote_map_.GetCodeFor(method, pc);
1491 if (code_ptr != nullptr) {
1492 return OatQuickMethodHeader::FromCodePointer(code_ptr);
1493 }
1494 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001495 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1496 if (it != method_code_map_.begin()) {
1497 --it;
1498 const void* code_ptr = it->first;
1499 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1500 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1501 found_method = it->second;
1502 }
1503 }
1504 if (method_header == nullptr && method == nullptr) {
1505 // Scan all compiled JNI stubs as well. This slow search is used only
1506 // for checks in debug build, for release builds the `method` is not null.
1507 for (auto&& entry : jni_stubs_map_) {
1508 const JniStubData& data = entry.second;
1509 if (data.IsCompiled() &&
1510 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1511 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1512 }
1513 }
1514 }
1515 if (method_header == nullptr) {
1516 return nullptr;
1517 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001518 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001519
1520 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Vladimir Markoeab02482019-05-09 10:28:17 +01001521 DCHECK_EQ(found_method, method)
1522 << ArtMethod::PrettyMethod(method) << " "
1523 << ArtMethod::PrettyMethod(found_method) << " "
David Sehr709b0702016-10-13 09:12:37 -07001524 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001525 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001526 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001527}
1528
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001529OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001530 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001531 auto it = osr_code_map_.find(method);
1532 if (it == osr_code_map_.end()) {
1533 return nullptr;
1534 }
1535 return OatQuickMethodHeader::FromCodePointer(it->second);
1536}
1537
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001538ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1539 ArtMethod* method,
1540 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001541 bool retry_allocation)
1542 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1543 NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001544 DCHECK(CanAllocateProfilingInfo());
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001545 ProfilingInfo* info = nullptr;
1546 if (!retry_allocation) {
1547 // If we are allocating for the interpreter, just try to lock, to avoid
1548 // lock contention with the JIT.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001549 if (Locks::jit_lock_->ExclusiveTryLock(self)) {
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001550 info = AddProfilingInfoInternal(self, method, entries);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001551 Locks::jit_lock_->ExclusiveUnlock(self);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001552 }
1553 } else {
1554 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001555 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001556 info = AddProfilingInfoInternal(self, method, entries);
1557 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001558
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001559 if (info == nullptr) {
1560 GarbageCollectCache(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001561 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001562 info = AddProfilingInfoInternal(self, method, entries);
1563 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001564 }
1565 return info;
1566}
1567
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001568ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001569 ArtMethod* method,
1570 const std::vector<uint32_t>& entries) {
1571 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001572 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001573 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001574
1575 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001576 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001577 if (info != nullptr) {
1578 return info;
1579 }
1580
David Srbecky87fb0322019-08-20 10:34:02 +01001581 const uint8_t* data = private_region_.AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001582 if (data == nullptr) {
1583 return nullptr;
1584 }
David Srbecky87fb0322019-08-20 10:34:02 +01001585 uint8_t* writable_data = private_region_.GetWritableDataAddress(data);
1586 info = new (writable_data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001587
1588 // Make sure other threads see the data in the profiling info object before the
1589 // store in the ArtMethod's ProfilingInfo pointer.
Orion Hodson27b96762018-03-13 16:06:57 +00001590 std::atomic_thread_fence(std::memory_order_release);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001591
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001592 method->SetProfilingInfo(info);
1593 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001594 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001595 return info;
1596}
1597
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001598void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001599 return shared_region_.OwnsSpace(mspace)
1600 ? shared_region_.MoreCore(mspace, increment)
1601 : private_region_.MoreCore(mspace, increment);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001602}
1603
Calin Juravle99629622016-04-19 16:33:46 +01001604void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001605 std::vector<ProfileMethodInfo>& methods) {
Nicolas Geoffray1afdfe62018-11-21 09:38:10 +00001606 Thread* self = Thread::Current();
1607 WaitUntilInlineCacheAccessible(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001608 MutexLock mu(self, *Locks::jit_lock_);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001609 ScopedTrace trace(__FUNCTION__);
Calin Juravlea39fd982017-05-18 10:15:52 -07001610 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001611 for (const ProfilingInfo* info : profiling_infos_) {
1612 ArtMethod* method = info->GetMethod();
1613 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001614 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1615 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001616 // Skip dex files which are not profiled.
1617 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001618 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001619 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001620
1621 // If the method didn't reach the compilation threshold don't save the inline caches.
1622 // They might be incomplete and cause unnecessary deoptimizations.
1623 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1624 if (method->GetCounter() < jit_compile_threshold) {
1625 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001626 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001627 continue;
1628 }
1629
Calin Juravle940eb0c2017-01-30 19:30:44 -08001630 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001631 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001632 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001633 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001634 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001635 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1636 mirror::Class* cls = cache.classes_[k].Read();
1637 if (cls == nullptr) {
1638 break;
1639 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001640
Calin Juravle13439f02017-02-21 01:17:21 -08001641 // Check if the receiver is in the boot class path or if it's in the
1642 // same class loader as the caller. If not, skip it, as there is not
1643 // much we can do during AOT.
1644 if (!cls->IsBootStrapClassLoaded() &&
1645 caller->GetClassLoader() != cls->GetClassLoader()) {
1646 is_missing_types = true;
1647 continue;
1648 }
1649
Calin Juravle4ca70a32017-02-21 16:22:24 -08001650 const DexFile* class_dex_file = nullptr;
1651 dex::TypeIndex type_index;
1652
1653 if (cls->GetDexCache() == nullptr) {
1654 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001655 // Make a best effort to find the type index in the method's dex file.
1656 // We could search all open dex files but that might turn expensive
1657 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001658 class_dex_file = dex_file;
1659 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1660 } else {
1661 class_dex_file = &(cls->GetDexFile());
1662 type_index = cls->GetDexTypeIndex();
1663 }
1664 if (!type_index.IsValid()) {
1665 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001666 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001667 continue;
1668 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001669 if (ContainsElement(dex_base_locations,
1670 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001671 // Only consider classes from the same apk (including multidex).
1672 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001673 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001674 } else {
1675 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001676 }
1677 }
1678 if (!profile_classes.empty()) {
1679 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001680 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001681 }
1682 }
1683 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001684 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001685 }
1686}
1687
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001688bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001689 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001690 return osr_code_map_.find(method) != osr_code_map_.end();
1691}
1692
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001693bool JitCodeCache::NotifyCompilationOf(ArtMethod* method,
1694 Thread* self,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001695 CompilationKind compilation_kind,
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001696 bool prejit,
1697 JitMemoryRegion* region) {
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001698 const void* existing_entry_point = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001699 if (compilation_kind != CompilationKind::kOsr && ContainsPc(existing_entry_point)) {
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001700 OatQuickMethodHeader* method_header =
1701 OatQuickMethodHeader::FromEntryPoint(existing_entry_point);
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001702 bool is_baseline = (compilation_kind == CompilationKind::kBaseline);
1703 if (CodeInfo::IsBaseline(method_header->GetOptimizedCodeInfoPtr()) == is_baseline) {
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001704 VLOG(jit) << "Not compiling "
1705 << method->PrettyMethod()
1706 << " because it has already been compiled"
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001707 << " kind=" << compilation_kind;
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001708 return false;
1709 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001710 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001711
Vladimir Marko5115a4d2019-10-17 14:56:47 +01001712 if (NeedsClinitCheckBeforeCall(method) && !prejit) {
1713 // We do not need a synchronization barrier for checking the visibly initialized status
1714 // or checking the initialized status just for requesting visible initialization.
1715 ClassStatus status = method->GetDeclaringClass()
1716 ->GetStatus<kDefaultVerifyFlags, /*kWithSynchronizationBarrier=*/ false>();
1717 if (status != ClassStatus::kVisiblyInitialized) {
1718 // Unless we're pre-jitting, we currently don't save the JIT compiled code if we cannot
1719 // update the entrypoint due to needing an initialization check.
1720 if (status == ClassStatus::kInitialized) {
1721 // Request visible initialization but do not block to allow compiling other methods.
1722 // Hopefully, this will complete by the time the method becomes hot again.
1723 Runtime::Current()->GetClassLinker()->MakeInitializedClassesVisiblyInitialized(
1724 self, /*wait=*/ false);
1725 }
1726 VLOG(jit) << "Not compiling "
1727 << method->PrettyMethod()
1728 << " because it has the resolution stub";
1729 // Give it a new chance to be hot.
1730 ClearMethodCounter(method, /*was_warm=*/ false);
1731 return false;
Vladimir Markocce414f2019-10-07 08:51:33 +01001732 }
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01001733 }
1734
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001735 if (compilation_kind == CompilationKind::kOsr) {
Nicolas Geoffray085f7402019-12-16 16:30:48 +00001736 MutexLock mu(self, *Locks::jit_lock_);
1737 if (osr_code_map_.find(method) != osr_code_map_.end()) {
1738 return false;
1739 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001740 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001741
Vladimir Marko2196c652017-11-30 16:16:07 +00001742 if (UNLIKELY(method->IsNative())) {
Nicolas Geoffray085f7402019-12-16 16:30:48 +00001743 MutexLock mu(self, *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001744 JniStubKey key(method);
1745 auto it = jni_stubs_map_.find(key);
1746 bool new_compilation = false;
1747 if (it == jni_stubs_map_.end()) {
1748 // Create a new entry to mark the stub as being compiled.
1749 it = jni_stubs_map_.Put(key, JniStubData{});
1750 new_compilation = true;
1751 }
1752 JniStubData* data = &it->second;
1753 data->AddMethod(method);
1754 if (data->IsCompiled()) {
1755 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1756 const void* entrypoint = method_header->GetEntryPoint();
1757 // Update also entrypoints of other methods held by the JniStubData.
1758 // We could simply update the entrypoint of `method` but if the last JIT GC has
1759 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1760 // as well change them back as this stub shall not be collected anyway and this
1761 // can avoid a few expensive GenericJNI calls.
Vladimir Markocce414f2019-10-07 08:51:33 +01001762 data->UpdateEntryPoints(entrypoint);
Vladimir Marko2196c652017-11-30 16:16:07 +00001763 if (collection_in_progress_) {
David Srbeckyc45b5892019-04-24 10:32:04 +01001764 if (!IsInZygoteExecSpace(data->GetCode())) {
1765 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1766 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001767 }
1768 }
1769 return new_compilation;
1770 } else {
1771 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001772 if (CanAllocateProfilingInfo() &&
1773 (compilation_kind == CompilationKind::kBaseline) &&
1774 (info == nullptr)) {
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001775 // We can retry allocation here as we're the JIT thread.
1776 if (ProfilingInfo::Create(self, method, /* retry_allocation= */ true)) {
1777 info = method->GetProfilingInfo(kRuntimePointerSize);
1778 }
1779 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001780 if (info == nullptr) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001781 // When prejitting, we don't allocate a profiling info.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001782 if (!prejit && !IsSharedRegion(*region)) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001783 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1784 // Because the counter is not atomic, there are some rare cases where we may not hit the
1785 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
1786 ClearMethodCounter(method, /*was_warm=*/ false);
1787 return false;
1788 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001789 }
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001790 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001791 if (IsMethodBeingCompiled(method, compilation_kind)) {
Nicolas Geoffrayf8cc26e2020-06-10 15:37:37 +01001792 return false;
1793 }
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001794 AddMethodBeingCompiled(method, compilation_kind);
Vladimir Marko2196c652017-11-30 16:16:07 +00001795 return true;
1796 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001797}
1798
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001799ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001800 MutexLock mu(self, *Locks::jit_lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001801 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001802 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001803 if (!info->IncrementInlineUse()) {
1804 // Overflow of inlining uses, just bail.
1805 return nullptr;
1806 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001807 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001808 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001809}
1810
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001811void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001812 MutexLock mu(self, *Locks::jit_lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001813 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001814 DCHECK(info != nullptr);
1815 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001816}
1817
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001818void JitCodeCache::DoneCompiling(ArtMethod* method,
1819 Thread* self,
1820 CompilationKind compilation_kind) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001821 DCHECK_EQ(Thread::Current(), self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001822 MutexLock mu(self, *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001823 if (UNLIKELY(method->IsNative())) {
1824 auto it = jni_stubs_map_.find(JniStubKey(method));
1825 DCHECK(it != jni_stubs_map_.end());
1826 JniStubData* data = &it->second;
1827 DCHECK(ContainsElement(data->GetMethods(), method));
1828 if (UNLIKELY(!data->IsCompiled())) {
1829 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1830 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
David Srbeckyadb66f92019-10-10 12:59:43 +00001831 } // else Commit() updated entrypoints of all methods in the JniStubData.
Vladimir Marko2196c652017-11-30 16:16:07 +00001832 } else {
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001833 RemoveMethodBeingCompiled(method, compilation_kind);
Vladimir Marko2196c652017-11-30 16:16:07 +00001834 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001835}
1836
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001837void JitCodeCache::InvalidateAllCompiledCode() {
1838 art::MutexLock mu(Thread::Current(), *Locks::jit_lock_);
1839 size_t cnt = profiling_infos_.size();
1840 size_t osr_size = osr_code_map_.size();
1841 for (ProfilingInfo* pi : profiling_infos_) {
1842 // NB Due to OSR we might run this on some methods multiple times but this should be fine.
1843 ArtMethod* meth = pi->GetMethod();
1844 pi->SetSavedEntryPoint(nullptr);
1845 // We had a ProfilingInfo so we must be warm.
1846 ClearMethodCounter(meth, /*was_warm=*/true);
1847 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1848 if (meth->IsObsolete()) {
1849 linker->SetEntryPointsForObsoleteMethod(meth);
1850 } else {
1851 linker->SetEntryPointsToInterpreter(meth);
1852 }
1853 }
1854 osr_code_map_.clear();
1855 VLOG(jit) << "Invalidated the compiled code of " << (cnt - osr_size) << " methods and "
1856 << osr_size << " OSRs.";
1857}
1858
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001859void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1860 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001861 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07001862 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Alex Light2d441b12018-06-08 15:33:21 -07001863 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001864 if ((profiling_info != nullptr) &&
1865 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
Alex Light2d441b12018-06-08 15:33:21 -07001866 // When instrumentation is set, the actual entrypoint is the one in the profiling info.
1867 method_entrypoint = profiling_info->GetSavedEntryPoint();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001868 // Prevent future uses of the compiled code.
1869 profiling_info->SetSavedEntryPoint(nullptr);
1870 }
1871
Alex Light2d441b12018-06-08 15:33:21 -07001872 // Clear the method counter if we are running jitted code since we might want to jit this again in
1873 // the future.
1874 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001875 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001876 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001877 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1878 method, GetQuickToInterpreterBridge());
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001879 ClearMethodCounter(method, /*was_warm=*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001880 } else {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001881 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001882 auto it = osr_code_map_.find(method);
1883 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1884 // Remove the OSR method, to avoid using it again.
1885 osr_code_map_.erase(it);
1886 }
1887 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001888
Nicolas Geoffray32384402019-07-17 20:06:44 +01001889 // In case the method was pre-compiled, clear that information so we
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001890 // can recompile it ourselves.
Nicolas Geoffray32384402019-07-17 20:06:44 +01001891 if (method->IsPreCompiled()) {
1892 method->ClearPreCompiled();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001893 }
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001894}
1895
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001896void JitCodeCache::Dump(std::ostream& os) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001897 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
David Srbecky44b977d2019-08-09 12:15:32 +01001898 os << "Current JIT code cache size (used / resident): "
1899 << GetCurrentRegion()->GetUsedMemoryForCode() / KB << "KB / "
1900 << GetCurrentRegion()->GetResidentMemoryForCode() / KB << "KB\n"
1901 << "Current JIT data cache size (used / resident): "
1902 << GetCurrentRegion()->GetUsedMemoryForData() / KB << "KB / "
1903 << GetCurrentRegion()->GetResidentMemoryForData() / KB << "KB\n";
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001904 if (!Runtime::Current()->IsZygote()) {
1905 os << "Zygote JIT code cache size (at point of fork): "
David Srbecky44b977d2019-08-09 12:15:32 +01001906 << shared_region_.GetUsedMemoryForCode() / KB << "KB / "
1907 << shared_region_.GetResidentMemoryForCode() / KB << "KB\n"
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001908 << "Zygote JIT data cache size (at point of fork): "
David Srbecky44b977d2019-08-09 12:15:32 +01001909 << shared_region_.GetUsedMemoryForData() / KB << "KB / "
1910 << shared_region_.GetResidentMemoryForData() / KB << "KB\n";
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001911 }
1912 os << "Current JIT mini-debug-info size: " << PrettySize(GetJitMiniDebugInfoMemUsage()) << "\n"
1913 << "Current JIT capacity: " << PrettySize(GetCurrentRegion()->GetCurrentCapacity()) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00001914 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001915 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1916 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1917 << "Total number of JIT compilations for on stack replacement: "
1918 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001919 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001920 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1921 histogram_code_memory_use_.PrintMemoryUse(os);
1922 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001923}
1924
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001925void JitCodeCache::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffrayb08d5db2019-07-17 10:45:36 +01001926 Thread* self = Thread::Current();
1927
1928 // Remove potential tasks that have been inherited from the zygote.
1929 // We do this now and not in Jit::PostForkChildAction, as system server calls
1930 // JitCodeCache::PostForkChildAction first, and then does some code loading
1931 // that may result in new JIT tasks that we want to keep.
1932 ThreadPool* pool = Runtime::Current()->GetJit()->GetThreadPool();
1933 if (pool != nullptr) {
1934 pool->RemoveAllTasks(self);
1935 }
1936
1937 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray88f3fd92019-06-27 16:32:13 +01001938
1939 // Reset potential writable MemMaps inherited from the zygote. We never want
1940 // to write to them.
1941 shared_region_.ResetWritableMappings();
1942
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001943 if (is_zygote || Runtime::Current()->IsSafeMode()) {
1944 // Don't create a private region for a child zygote. Regions are usually map shared
1945 // (to satisfy dual-view), and we don't want children of a child zygote to inherit it.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001946 return;
1947 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001948
1949 // Reset all statistics to be specific to this process.
1950 number_of_compilations_ = 0;
1951 number_of_osr_compilations_ = 0;
1952 number_of_collections_ = 0;
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001953 histogram_stack_map_memory_use_.Reset();
1954 histogram_code_memory_use_.Reset();
1955 histogram_profiling_info_memory_use_.Reset();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001956
1957 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
1958 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001959 std::string error_msg;
Nicolas Geoffray9c54e182019-06-18 10:42:52 +01001960 if (!private_region_.Initialize(initial_capacity,
1961 max_capacity,
1962 /* rwx_memory_allowed= */ !is_system_server,
1963 is_zygote,
1964 &error_msg)) {
1965 LOG(WARNING) << "Could not create private region after zygote fork: " << error_msg;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001966 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001967}
1968
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001969JitMemoryRegion* JitCodeCache::GetCurrentRegion() {
1970 return Runtime::Current()->IsZygote() ? &shared_region_ : &private_region_;
1971}
1972
David Srbecky41617b12020-03-18 21:19:06 +00001973void JitCodeCache::VisitAllMethods(const std::function<void(const void*, ArtMethod*)>& cb) {
1974 for (const auto& it : jni_stubs_map_) {
1975 const JniStubData& data = it.second;
1976 if (data.IsCompiled()) {
1977 for (ArtMethod* method : data.GetMethods()) {
1978 cb(data.GetCode(), method);
1979 }
1980 }
1981 }
1982 for (auto it : method_code_map_) { // Includes OSR methods.
1983 cb(it.first, it.second);
1984 }
1985 for (auto it : saved_compiled_methods_map_) {
1986 cb(it.second, it.first);
1987 }
1988 for (auto it : zygote_map_) {
1989 if (it.code_ptr != nullptr && it.method != nullptr) {
1990 cb(it.code_ptr, it.method);
1991 }
1992 }
1993}
1994
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001995void ZygoteMap::Initialize(uint32_t number_of_methods) {
1996 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
1997 // Allocate for 40-80% capacity. This will offer OK lookup times, and termination
1998 // cases.
1999 size_t capacity = RoundUpToPowerOfTwo(number_of_methods * 100 / 80);
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00002000 const uint8_t* memory = region_->AllocateData(
2001 capacity * sizeof(Entry) + sizeof(ZygoteCompilationState));
2002 if (memory == nullptr) {
2003 LOG(WARNING) << "Could not allocate data for the zygote map";
2004 return;
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01002005 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00002006 const Entry* data = reinterpret_cast<const Entry*>(memory);
2007 region_->FillData(data, capacity, Entry { nullptr, nullptr });
2008 map_ = ArrayRef(data, capacity);
2009 compilation_state_ = reinterpret_cast<const ZygoteCompilationState*>(
2010 memory + capacity * sizeof(Entry));
2011 region_->WriteData(compilation_state_, ZygoteCompilationState::kInProgress);
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01002012}
2013
2014const void* ZygoteMap::GetCodeFor(ArtMethod* method, uintptr_t pc) const {
2015 if (map_.empty()) {
2016 return nullptr;
2017 }
2018
2019 if (method == nullptr) {
2020 // Do a linear search. This should only be used in debug builds.
2021 CHECK(kIsDebugBuild);
2022 for (const Entry& entry : map_) {
2023 const void* code_ptr = entry.code_ptr;
2024 if (code_ptr != nullptr) {
2025 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
2026 if (method_header->Contains(pc)) {
2027 return code_ptr;
2028 }
2029 }
2030 }
2031 return nullptr;
2032 }
2033
2034 std::hash<ArtMethod*> hf;
2035 size_t index = hf(method) & (map_.size() - 1u);
2036 size_t original_index = index;
2037 // Loop over the array: we know this loop terminates as we will either
2038 // encounter the given method, or a null entry. Both terminate the loop.
2039 // Note that the zygote may concurrently write new entries to the map. That's OK as the
2040 // map is never resized.
2041 while (true) {
2042 const Entry& entry = map_[index];
2043 if (entry.method == nullptr) {
2044 // Not compiled yet.
2045 return nullptr;
2046 }
2047 if (entry.method == method) {
2048 if (entry.code_ptr == nullptr) {
2049 // This is a race with the zygote which wrote the method, but hasn't written the
2050 // code. Just bail and wait for the next time we need the method.
2051 return nullptr;
2052 }
2053 if (pc != 0 && !OatQuickMethodHeader::FromCodePointer(entry.code_ptr)->Contains(pc)) {
2054 return nullptr;
2055 }
2056 return entry.code_ptr;
2057 }
2058 index = (index + 1) & (map_.size() - 1);
2059 DCHECK_NE(original_index, index);
2060 }
2061}
2062
2063void ZygoteMap::Put(const void* code, ArtMethod* method) {
2064 if (map_.empty()) {
2065 return;
2066 }
2067 CHECK(Runtime::Current()->IsZygote());
2068 std::hash<ArtMethod*> hf;
2069 size_t index = hf(method) & (map_.size() - 1);
2070 size_t original_index = index;
2071 // Because the size of the map is bigger than the number of methods that will
2072 // be added, we are guaranteed to find a free slot in the array, and
2073 // therefore for this loop to terminate.
2074 while (true) {
David Srbecky87fb0322019-08-20 10:34:02 +01002075 const Entry* entry = &map_[index];
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01002076 if (entry->method == nullptr) {
2077 // Note that readers can read this memory concurrently, but that's OK as
2078 // we are writing pointers.
2079 region_->WriteData(entry, Entry { method, code });
2080 break;
2081 }
2082 index = (index + 1) & (map_.size() - 1);
2083 DCHECK_NE(original_index, index);
2084 }
2085 DCHECK_EQ(GetCodeFor(method), code);
2086}
2087
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002088} // namespace jit
2089} // namespace art