blob: 8f4d0d4c2f98b39ecb41298a93436607db2bf77f [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"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010040#include "entrypoints/runtime_asm_entrypoints.h"
41#include "gc/accounting/bitmap-inl.h"
Andreas Gampe88dbad32018-06-26 19:54:12 -070042#include "gc/allocator/dlmalloc.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010043#include "gc/scoped_gc_critical_section.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000044#include "handle.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070045#include "instrumentation.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070046#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000047#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000048#include "jit/profiling_info.h"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010049#include "jit/jit_scoped_code_cache_write.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010050#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080051#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070052#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070053#include "object_callbacks.h"
David Sehr82d046e2018-04-23 08:14:19 -070054#include "profile/profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070055#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070056#include "stack.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000057#include "thread-current-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010058#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080059
60namespace art {
61namespace jit {
62
Nicolas Geoffray933330a2016-03-16 14:20:06 +000063static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
64static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
65
Vladimir Marko2196c652017-11-30 16:16:07 +000066class JitCodeCache::JniStubKey {
67 public:
68 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
69 : shorty_(method->GetShorty()),
70 is_static_(method->IsStatic()),
71 is_fast_native_(method->IsFastNative()),
72 is_critical_native_(method->IsCriticalNative()),
73 is_synchronized_(method->IsSynchronized()) {
74 DCHECK(!(is_fast_native_ && is_critical_native_));
75 }
76
77 bool operator<(const JniStubKey& rhs) const {
78 if (is_static_ != rhs.is_static_) {
79 return rhs.is_static_;
80 }
81 if (is_synchronized_ != rhs.is_synchronized_) {
82 return rhs.is_synchronized_;
83 }
84 if (is_fast_native_ != rhs.is_fast_native_) {
85 return rhs.is_fast_native_;
86 }
87 if (is_critical_native_ != rhs.is_critical_native_) {
88 return rhs.is_critical_native_;
89 }
90 return strcmp(shorty_, rhs.shorty_) < 0;
91 }
92
93 // Update the shorty to point to another method's shorty. Call this function when removing
94 // the method that references the old shorty from JniCodeData and not removing the entire
95 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
96 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
97 const char* shorty = method->GetShorty();
98 DCHECK_STREQ(shorty_, shorty);
99 shorty_ = shorty;
100 }
101
102 private:
103 // The shorty points to a DexFile data and may need to change
104 // to point to the same shorty in a different DexFile.
105 mutable const char* shorty_;
106
107 const bool is_static_;
108 const bool is_fast_native_;
109 const bool is_critical_native_;
110 const bool is_synchronized_;
111};
112
113class JitCodeCache::JniStubData {
114 public:
115 JniStubData() : code_(nullptr), methods_() {}
116
117 void SetCode(const void* code) {
118 DCHECK(code != nullptr);
119 code_ = code;
120 }
121
122 const void* GetCode() const {
123 return code_;
124 }
125
126 bool IsCompiled() const {
127 return GetCode() != nullptr;
128 }
129
130 void AddMethod(ArtMethod* method) {
131 if (!ContainsElement(methods_, method)) {
132 methods_.push_back(method);
133 }
134 }
135
136 const std::vector<ArtMethod*>& GetMethods() const {
137 return methods_;
138 }
139
140 void RemoveMethodsIn(const LinearAlloc& alloc) {
141 auto kept_end = std::remove_if(
142 methods_.begin(),
143 methods_.end(),
144 [&alloc](ArtMethod* method) { return alloc.ContainsUnsafe(method); });
145 methods_.erase(kept_end, methods_.end());
146 }
147
148 bool RemoveMethod(ArtMethod* method) {
149 auto it = std::find(methods_.begin(), methods_.end(), method);
150 if (it != methods_.end()) {
151 methods_.erase(it);
152 return true;
153 } else {
154 return false;
155 }
156 }
157
158 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
159 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
160 }
161
162 private:
163 const void* code_;
164 std::vector<ArtMethod*> methods_;
165};
166
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000167JitCodeCache* JitCodeCache::Create(bool used_only_for_profile_data,
168 bool rwx_memory_allowed,
169 bool is_zygote,
170 std::string* error_msg) {
171 // Register for membarrier expedited sync core if JIT will be generating code.
172 if (!used_only_for_profile_data) {
173 if (art::membarrier(art::MembarrierCommand::kRegisterPrivateExpeditedSyncCore) != 0) {
174 // MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE ensures that CPU instruction pipelines are
175 // flushed and it's used when adding code to the JIT. The memory used by the new code may
176 // have just been released and, in theory, the old code could still be in a pipeline.
177 VLOG(jit) << "Kernel does not support membarrier sync-core";
178 }
179 }
180
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100181 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000182 // Check whether the provided max capacity in options is below 1GB.
183 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
184 // We need to have 32 bit offsets from method headers in code cache which point to things
185 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
186 // Ensure we're below 1 GB to be safe.
187 if (max_capacity > 1 * GB) {
188 std::ostringstream oss;
189 oss << "Maxium code cache capacity is limited to 1 GB, "
190 << PrettySize(max_capacity) << " is too big";
191 *error_msg = oss.str();
192 return nullptr;
193 }
194
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100195 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100196 JitMemoryRegion region;
197 if (!region.Initialize(initial_capacity,
198 max_capacity,
199 rwx_memory_allowed,
200 is_zygote,
201 error_msg)) {
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000202 return nullptr;
203 }
204
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100205 std::unique_ptr<JitCodeCache> jit_code_cache(new JitCodeCache());
206 if (is_zygote) {
207 // Zygote should never collect code to share the memory with the children.
208 jit_code_cache->garbage_collect_code_ = false;
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000209 jit_code_cache->shared_region_ = std::move(region);
210 } else {
211 jit_code_cache->private_region_ = std::move(region);
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100212 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000213
214 VLOG(jit) << "Created jit code cache: initial capacity="
215 << PrettySize(initial_capacity)
216 << ", maximum capacity="
217 << PrettySize(max_capacity);
218
219 return jit_code_cache.release();
220}
221
222JitCodeCache::JitCodeCache()
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100223 : is_weak_access_enabled_(true),
224 inline_cache_cond_("Jit inline cache condition variable", *Locks::jit_lock_),
225 lock_cond_("Jit code cache condition variable", *Locks::jit_lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100226 collection_in_progress_(false),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000227 last_collection_increased_code_cache_(false),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100228 garbage_collect_code_(true),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000229 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000230 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000231 number_of_collections_(0),
232 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
233 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100234 histogram_profiling_info_memory_use_("Memory used for profiling info", 16) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800235}
236
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000237JitCodeCache::~JitCodeCache() {}
238
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100239bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100240 return private_region_.IsInExecSpace(ptr) || shared_region_.IsInExecSpace(ptr);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800241}
242
Alex Light2d441b12018-06-08 15:33:21 -0700243bool JitCodeCache::WillExecuteJitCode(ArtMethod* method) {
244 ScopedObjectAccess soa(art::Thread::Current());
245 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
246 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
247 return true;
248 } else if (method->GetEntryPointFromQuickCompiledCode() == GetQuickInstrumentationEntryPoint()) {
249 return FindCompiledCodeForInstrumentation(method) != nullptr;
250 }
251 return false;
252}
253
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000254bool JitCodeCache::ContainsMethod(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100255 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000256 if (UNLIKELY(method->IsNative())) {
257 auto it = jni_stubs_map_.find(JniStubKey(method));
258 if (it != jni_stubs_map_.end() &&
259 it->second.IsCompiled() &&
260 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000261 return true;
262 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000263 } else {
264 for (const auto& it : method_code_map_) {
265 if (it.second == method) {
266 return true;
267 }
268 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000269 }
270 return false;
271}
272
Vladimir Marko2196c652017-11-30 16:16:07 +0000273const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
274 DCHECK(method->IsNative());
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100275 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000276 auto it = jni_stubs_map_.find(JniStubKey(method));
277 if (it != jni_stubs_map_.end()) {
278 JniStubData& data = it->second;
279 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
280 return data.GetCode();
281 }
282 }
283 return nullptr;
284}
285
Alex Light2d441b12018-06-08 15:33:21 -0700286const void* JitCodeCache::FindCompiledCodeForInstrumentation(ArtMethod* method) {
Alex Light839f53a2018-07-10 15:46:14 -0700287 // If jit-gc is still on we use the SavedEntryPoint field for doing that and so cannot use it to
288 // find the instrumentation entrypoint.
289 if (LIKELY(GetGarbageCollectCode())) {
Alex Light2d441b12018-06-08 15:33:21 -0700290 return nullptr;
291 }
292 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
293 if (info == nullptr) {
294 return nullptr;
295 }
296 // When GC is disabled for trampoline tracing we will use SavedEntrypoint to hold the actual
297 // jit-compiled version of the method. If jit-gc is disabled for other reasons this will just be
298 // nullptr.
299 return info->GetSavedEntryPoint();
300}
301
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100302const void* JitCodeCache::GetZygoteSavedEntryPoint(ArtMethod* method) {
David Srbecky3db3d372019-04-17 18:19:17 +0100303 if (Runtime::Current()->IsUsingApexBootImageLocation() &&
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100304 // Currently only applies to boot classpath
305 method->GetDeclaringClass()->GetClassLoader() == nullptr) {
306 const void* entry_point = nullptr;
307 if (method->IsNative()) {
308 const void* code_ptr = GetJniStubCode(method);
309 if (code_ptr != nullptr) {
310 entry_point = OatQuickMethodHeader::FromCodePointer(code_ptr)->GetEntryPoint();
311 }
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100312 } else {
313 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
314 if (profiling_info != nullptr) {
315 entry_point = profiling_info->GetSavedEntryPoint();
316 }
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100317 }
318 if (Runtime::Current()->IsZygote() || IsInZygoteExecSpace(entry_point)) {
319 return entry_point;
320 }
321 }
322 return nullptr;
323}
324
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100325uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100326 JitMemoryRegion* region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100327 ArtMethod* method,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100328 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000329 size_t code_size,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100330 const uint8_t* stack_map,
331 size_t stack_map_size,
332 uint8_t* roots_data,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100333 const std::vector<Handle<mirror::Object>>& roots,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100334 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700335 bool has_should_deoptimize_flag,
336 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100337 uint8_t* result = CommitCodeInternal(self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100338 region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100339 method,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100340 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000341 code_size,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100342 stack_map,
343 stack_map_size,
344 roots_data,
Mingyao Yang063fc772016-08-02 11:02:54 -0700345 roots,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100346 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700347 has_should_deoptimize_flag,
348 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100349 if (result == nullptr) {
350 // Retry.
351 GarbageCollectCache(self);
352 result = CommitCodeInternal(self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100353 region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100354 method,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100355 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000356 code_size,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100357 stack_map,
358 stack_map_size,
359 roots_data,
Mingyao Yang063fc772016-08-02 11:02:54 -0700360 roots,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100361 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700362 has_should_deoptimize_flag,
363 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100364 }
365 return result;
366}
367
368bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
369 bool in_collection = false;
370 while (collection_in_progress_) {
371 in_collection = true;
372 lock_cond_.Wait(self);
373 }
374 return in_collection;
375}
376
377static uintptr_t FromCodeToAllocation(const void* code) {
Orion Hodsone764f382019-06-27 12:56:48 +0100378 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100379 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
380}
381
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000382static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
383 // The length of the table is stored just before the stack map (and therefore at the end of
384 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
385 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
386}
387
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000388static void DCheckRootsAreValid(const std::vector<Handle<mirror::Object>>& roots,
389 bool is_shared_region)
Alex Light3e36a9c2018-06-19 09:45:05 -0700390 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
391 if (!kIsDebugBuild) {
392 return;
393 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700394 // Put all roots in `roots_data`.
Vladimir Markoac3ac682018-09-20 11:01:43 +0100395 for (Handle<mirror::Object> object : roots) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700396 // Ensure the string is strongly interned. b/32995596
397 if (object->IsString()) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100398 ObjPtr<mirror::String> str = object->AsString();
Alex Light3e36a9c2018-06-19 09:45:05 -0700399 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
400 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
401 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000402 // Ensure that we don't put movable objects in the shared region.
403 if (is_shared_region) {
404 CHECK(!Runtime::Current()->GetHeap()->IsMovableObject(object.Get()));
405 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700406 }
407}
408
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100409static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000410 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
411 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
412 uint32_t roots = GetNumberOfRoots(data);
413 if (number_of_roots != nullptr) {
414 *number_of_roots = roots;
415 }
416 return data - ComputeRootTableSize(roots);
417}
418
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100419// Use a sentinel for marking entries in the JIT table that have been cleared.
420// This helps diagnosing in case the compiled code tries to wrongly access such
421// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700422static mirror::Class* const weak_sentinel =
423 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100424
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000425// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100426static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
427 IsMarkedVisitor* visitor,
428 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000429 REQUIRES_SHARED(Locks::mutator_lock_) {
430 // This does not need a read barrier because this is called by GC.
431 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100432 if (cls != nullptr && cls != weak_sentinel) {
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700433 DCHECK((cls->IsClass<kDefaultVerifyFlags>()));
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000434 // Look at the classloader of the class to know if it has been unloaded.
435 // This does not need a read barrier because this is called by GC.
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000436 ObjPtr<mirror::Object> class_loader =
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000437 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000438 if (class_loader == nullptr || visitor->IsMarked(class_loader.Ptr()) != nullptr) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000439 // The class loader is live, update the entry if the class has moved.
440 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
441 // Note that new_object can be null for CMS and newly allocated objects.
442 if (new_cls != nullptr && new_cls != cls) {
443 *root_ptr = GcRoot<mirror::Class>(new_cls);
444 }
445 } else {
446 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100447 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000448 }
449 }
450}
451
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000452void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100453 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000454 for (const auto& entry : method_code_map_) {
455 uint32_t number_of_roots = 0;
456 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
457 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
458 for (uint32_t i = 0; i < number_of_roots; ++i) {
459 // This does not need a read barrier because this is called by GC.
460 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100461 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000462 // entry got deleted in a previous sweep.
Vladimir Markod355acf2019-03-21 17:09:40 +0000463 } else if (object->IsString<kDefaultVerifyFlags>()) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000464 mirror::Object* new_object = visitor->IsMarked(object);
465 // We know the string is marked because it's a strongly-interned string that
466 // is always alive. The IsMarked implementation of the CMS collector returns
467 // null for newly allocated objects, but we know those haven't moved. Therefore,
468 // only update the entry if we get a different non-null string.
469 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
470 // out of the weak access/creation pause. b/32167580
471 if (new_object != nullptr && new_object != object) {
472 DCHECK(new_object->IsString());
473 roots[i] = GcRoot<mirror::Object>(new_object);
474 }
475 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100476 ProcessWeakClass(
477 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000478 }
479 }
480 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000481 // Walk over inline caches to clear entries containing unloaded classes.
482 for (ProfilingInfo* info : profiling_infos_) {
483 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
484 InlineCache* cache = &info->cache_[i];
485 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100486 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000487 }
488 }
489 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000490}
491
Orion Hodson607624f2018-05-11 10:10:46 +0100492void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
Nicolas Geoffrayae982f92018-12-08 12:31:10 +0000493 if (IsInZygoteExecSpace(code_ptr)) {
494 // No need to free, this is shared memory.
495 return;
496 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100497 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000498 // Notify native debugger that we are about to remove the code.
499 // It does nothing if we are not using native debugger.
David Srbeckyafc60cd2018-12-05 11:59:31 +0000500 RemoveNativeDebugInfoForJit(Thread::Current(), code_ptr);
Vladimir Marko2196c652017-11-30 16:16:07 +0000501 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100502 private_region_.FreeData(GetRootTable(code_ptr));
Vladimir Marko2196c652017-11-30 16:16:07 +0000503 } // else this is a JNI stub without any data.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100504
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100505 private_region_.FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100506}
507
Mingyao Yang063fc772016-08-02 11:02:54 -0700508void JitCodeCache::FreeAllMethodHeaders(
509 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700510 // We need to remove entries in method_headers from CHA dependencies
511 // first since once we do FreeCode() below, the memory can be reused
512 // so it's possible for the same method_header to start representing
513 // different compile code.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100514 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000515 {
516 MutexLock mu2(Thread::Current(), *Locks::cha_lock_);
517 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
518 ->RemoveDependentsWithMethodHeaders(method_headers);
519 }
520
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100521 ScopedCodeCacheWrite scc(private_region_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700522 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodson607624f2018-05-11 10:10:46 +0100523 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700524 }
525}
526
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100527void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800528 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700529 // We use a set to first collect all method_headers whose code need to be
530 // removed. We need to free the underlying code after we remove CHA dependencies
531 // for entries in this set. And it's more efficient to iterate through
532 // the CHA dependency map just once with an unordered_set.
533 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000534 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100535 MutexLock mu(self, *Locks::jit_lock_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700536 // We do not check if a code cache GC is in progress, as this method comes
537 // with the classlinker_classes_lock_ held, and suspending ourselves could
538 // lead to a deadlock.
539 {
Vladimir Marko2196c652017-11-30 16:16:07 +0000540 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
541 it->second.RemoveMethodsIn(alloc);
542 if (it->second.GetMethods().empty()) {
543 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
544 it = jni_stubs_map_.erase(it);
545 } else {
546 it->first.UpdateShorty(it->second.GetMethods().front());
547 ++it;
548 }
549 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700550 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
551 if (alloc.ContainsUnsafe(it->second)) {
552 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
553 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);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100572 private_region_.FreeData(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 }
578 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700579 FreeAllMethodHeaders(method_headers);
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
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100656uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100657 JitMemoryRegion* region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100658 ArtMethod* method,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100659 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000660 size_t code_size,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100661 const uint8_t* stack_map,
662 size_t stack_map_size,
663 uint8_t* roots_data,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100664 const std::vector<Handle<mirror::Object>>& roots,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100665 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700666 bool has_should_deoptimize_flag,
667 const ArenaSet<ArtMethod*>&
668 cha_single_implementation_list) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000669 DCHECK(!method->IsNative() || !osr);
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
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100677 size_t root_table_size = ComputeRootTableSize(roots.size());
678 uint8_t* stack_map_data = roots_data + root_table_size;
679
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100680 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000681 // We need to make sure that there will be no jit-gcs going on and wait for any ongoing one to
682 // finish.
683 WaitForPotentialCollectionToCompleteRunnable(self);
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100684 const uint8_t* code_ptr = region->AllocateCode(
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100685 code, code_size, stack_map_data, has_should_deoptimize_flag);
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100686 if (code_ptr == nullptr) {
687 return nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100688 }
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100689 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
690
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100691 // Commit roots and stack maps before updating the entry point.
Orion Hodsonaeb02232019-06-25 14:18:18 +0100692 if (!region->CommitData(roots_data, roots, stack_map, stack_map_size)) {
693 ScopedCodeCacheWrite ccw(*region);
694 uintptr_t allocation = FromCodeToAllocation(code_ptr);
695 region->FreeCode(reinterpret_cast<uint8_t*>(allocation));
696 return nullptr;
697 }
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100698
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100699 number_of_compilations_++;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100700
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000701 // We need to update the entry point in the runnable state for the instrumentation.
702 {
Alex Light33b7b5d2018-08-07 19:13:51 +0000703 // The following needs to be guarded by cha_lock_ also. Otherwise it's possible that the
704 // compiled code is considered invalidated by some class linking, but below we still make the
705 // compiled code valid for the method. Need cha_lock_ for checking all single-implementation
706 // flags and register dependencies.
Mingyao Yang063fc772016-08-02 11:02:54 -0700707 MutexLock cha_mu(self, *Locks::cha_lock_);
708 bool single_impl_still_valid = true;
709 for (ArtMethod* single_impl : cha_single_implementation_list) {
710 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700711 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
712 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700713 single_impl_still_valid = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700714 ClearMethodCounter(method, /*was_warm=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700715 break;
716 }
717 }
718
719 // Discard the code if any single-implementation assumptions are now invalid.
Orion Hodson31492522019-06-18 12:13:49 +0100720 if (UNLIKELY(!single_impl_still_valid)) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700721 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
Orion Hodson31492522019-06-18 12:13:49 +0100722 ScopedCodeCacheWrite ccw(*region);
723 uintptr_t allocation = FromCodeToAllocation(code_ptr);
724 region->FreeCode(reinterpret_cast<uint8_t*>(allocation));
Mingyao Yang063fc772016-08-02 11:02:54 -0700725 return nullptr;
726 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000727 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800728 << "Should not be using cha on debuggable apps/runs!";
729
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100730 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mingyao Yang063fc772016-08-02 11:02:54 -0700731 for (ArtMethod* single_impl : cha_single_implementation_list) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100732 class_linker->GetClassHierarchyAnalysis()->AddDependency(single_impl, method, method_header);
Mingyao Yang063fc772016-08-02 11:02:54 -0700733 }
734
Vladimir Marko2196c652017-11-30 16:16:07 +0000735 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000736 auto it = jni_stubs_map_.find(JniStubKey(method));
737 DCHECK(it != jni_stubs_map_.end())
738 << "Entry inserted in NotifyCompilationOf() should be alive.";
739 JniStubData* data = &it->second;
740 DCHECK(ContainsElement(data->GetMethods(), method))
741 << "Entry inserted in NotifyCompilationOf() should contain this method.";
742 data->SetCode(code_ptr);
743 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
744 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100745 if (!class_linker->IsQuickResolutionStub(m->GetEntryPointFromQuickCompiledCode())) {
746 instrum->UpdateMethodsCode(m, method_header->GetEntryPoint());
747 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000748 }
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100749 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +0000750 method_code_map_.Put(code_ptr, method);
751 if (osr) {
752 number_of_osr_compilations_++;
753 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100754 } else if (class_linker->IsQuickResolutionStub(
755 method->GetEntryPointFromQuickCompiledCode())) {
756 // This situation currently only occurs in the jit-zygote mode.
David Srbecky3db3d372019-04-17 18:19:17 +0100757 DCHECK(Runtime::Current()->IsUsingApexBootImageLocation());
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100758 DCHECK(!garbage_collect_code_);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100759 // TODO(ngeoffray): In most cases, the zygote will not have a profiling
760 // info for a compiled method. Use a map instead.
761 if (method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
762 // Save the entrypoint, so it can be fetched later once the class is
763 // initialized.
764 method->GetProfilingInfo(kRuntimePointerSize)->SetSavedEntryPoint(
765 method_header->GetEntryPoint());
766 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000767 } else {
768 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
769 method, method_header->GetEntryPoint());
770 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000771 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000772 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100773 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700774 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000775 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
776 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
777 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700778 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
779 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000780 histogram_code_memory_use_.AddValue(code_size);
781 if (code_size > kCodeSizeLogThreshold) {
782 LOG(INFO) << "JIT allocated "
783 << PrettySize(code_size)
784 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700785 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000786 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000787 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100788
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100789 return reinterpret_cast<uint8_t*>(method_header);
790}
791
792size_t JitCodeCache::CodeCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100793 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000794 return CodeCacheSizeLocked();
795}
796
Orion Hodsoneced6922017-06-01 10:54:28 +0100797bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000798 // This function is used only for testing and only with non-native methods.
799 CHECK(!method->IsNative());
800
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100801 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +0100802
Vladimir Marko2196c652017-11-30 16:16:07 +0000803 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
804 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +0100805
806 if (!in_cache) {
807 return false;
808 }
809
David Srbeckye36e7f22018-11-14 14:21:23 +0000810 method->SetCounter(0);
Orion Hodsoneced6922017-06-01 10:54:28 +0100811 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
812 method, GetQuickToInterpreterBridge());
813 VLOG(jit)
814 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
815 << ArtMethod::PrettyMethod(method) << "@" << method
816 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
817 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
818 return true;
819}
820
Vladimir Marko2196c652017-11-30 16:16:07 +0000821bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
822 if (LIKELY(!method->IsNative())) {
823 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
824 if (info != nullptr) {
825 RemoveElement(profiling_infos_, info);
826 }
827 method->SetProfilingInfo(nullptr);
828 }
829
830 bool in_cache = false;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100831 ScopedCodeCacheWrite ccw(private_region_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000832 if (UNLIKELY(method->IsNative())) {
833 auto it = jni_stubs_map_.find(JniStubKey(method));
834 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
835 in_cache = true;
836 if (it->second.GetMethods().empty()) {
837 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100838 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +0000839 }
840 jni_stubs_map_.erase(it);
841 } else {
842 it->first.UpdateShorty(it->second.GetMethods().front());
843 }
844 }
845 } else {
846 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
847 if (it->second == method) {
848 in_cache = true;
849 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100850 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +0000851 }
852 it = method_code_map_.erase(it);
853 } else {
854 ++it;
855 }
856 }
857
858 auto osr_it = osr_code_map_.find(method);
859 if (osr_it != osr_code_map_.end()) {
860 osr_code_map_.erase(osr_it);
861 }
862 }
863
864 return in_cache;
865}
866
Alex Lightdba61482016-12-21 08:20:29 -0800867// This notifies the code cache that the given method has been redefined and that it should remove
868// any cached information it has on the method. All threads must be suspended before calling this
869// method. The compiled code for the method (if there is any) must not be in any threads call stack.
870void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100871 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700872 RemoveMethodLocked(method, /* release_memory= */ true);
Alex Lightdba61482016-12-21 08:20:29 -0800873}
874
875// This invalidates old_method. Once this function returns one can no longer use old_method to
876// execute code unless it is fixed up. This fixup will happen later in the process of installing a
877// class redefinition.
878// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
879// shouldn't be used since it is no longer logically in the jit code cache.
880// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
881void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100882 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +0000883 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000884 // Update methods in jni_stubs_map_.
885 for (auto& entry : jni_stubs_map_) {
886 JniStubData& data = entry.second;
887 data.MoveObsoleteMethod(old_method, new_method);
888 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000889 return;
890 }
Alex Lightdba61482016-12-21 08:20:29 -0800891 // Update ProfilingInfo to the new one and remove it from the old_method.
892 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
893 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
894 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
895 old_method->SetProfilingInfo(nullptr);
896 // Since the JIT should be paused and all threads suspended by the time this is called these
897 // checks should always pass.
898 DCHECK(!info->IsInUseByCompiler());
899 new_method->SetProfilingInfo(info);
Alex Light2d441b12018-06-08 15:33:21 -0700900 // Get rid of the old saved entrypoint if it is there.
901 info->SetSavedEntryPoint(nullptr);
Alex Lightdba61482016-12-21 08:20:29 -0800902 info->method_ = new_method;
903 }
904 // Update method_code_map_ to point to the new method.
905 for (auto& it : method_code_map_) {
906 if (it.second == old_method) {
907 it.second = new_method;
908 }
909 }
910 // Update osr_code_map_ to point to the new method.
911 auto code_map = osr_code_map_.find(old_method);
912 if (code_map != osr_code_map_.end()) {
913 osr_code_map_.Put(new_method, code_map->second);
914 osr_code_map_.erase(old_method);
915 }
916}
917
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000918void JitCodeCache::ClearEntryPointsInZygoteExecSpace() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100919 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000920 // Iterate over profiling infos to know which methods may have been JITted. Note that
921 // to be JITted, a method must have a profiling info.
922 for (ProfilingInfo* info : profiling_infos_) {
923 ArtMethod* method = info->GetMethod();
924 if (IsInZygoteExecSpace(method->GetEntryPointFromQuickCompiledCode())) {
925 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
926 }
927 // If zygote does method tracing, or in some configuration where
928 // the JIT zygote does GC, we also need to clear the saved entry point
929 // in the profiling info.
930 if (IsInZygoteExecSpace(info->GetSavedEntryPoint())) {
931 info->SetSavedEntryPoint(nullptr);
932 }
933 }
934}
935
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000936size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100937 return private_region_.GetUsedMemoryForCode();
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100938}
939
940size_t JitCodeCache::DataCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100941 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000942 return DataCacheSizeLocked();
943}
944
945size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100946 return private_region_.GetUsedMemoryForData();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800947}
948
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000949void JitCodeCache::ClearData(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100950 JitMemoryRegion* region,
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000951 uint8_t* roots_data) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100952 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100953 region->FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000954}
955
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100956uint8_t* JitCodeCache::ReserveData(Thread* self,
957 JitMemoryRegion* region,
958 size_t stack_map_size,
959 size_t number_of_roots,
960 ArtMethod* method) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000961 size_t table_size = ComputeRootTableSize(number_of_roots);
David Srbecky8cd54542018-07-15 23:58:44 +0100962 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100963 uint8_t* result = nullptr;
964
965 {
966 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100967 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100968 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100969 result = region->AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100970 }
971
972 if (result == nullptr) {
973 // Retry.
974 GarbageCollectCache(self);
975 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100976 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100977 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100978 result = region->AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100979 }
980
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100981 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000982 histogram_stack_map_memory_use_.AddValue(size);
983 if (size > kStackMapSizeLogThreshold) {
984 LOG(INFO) << "JIT allocated "
985 << PrettySize(size)
986 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700987 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800988 }
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100989 return result;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800990}
991
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100992class MarkCodeClosure final : public Closure {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100993 public:
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +0000994 MarkCodeClosure(JitCodeCache* code_cache, CodeCacheBitmap* bitmap, Barrier* barrier)
995 : code_cache_(code_cache), bitmap_(bitmap), barrier_(barrier) {}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100996
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100997 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800998 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100999 DCHECK(thread == Thread::Current() || thread->IsSuspended());
Andreas Gampec7d878d2018-11-19 18:42:06 +00001000 StackVisitor::WalkStack(
1001 [&](const art::StackVisitor* stack_visitor) {
1002 const OatQuickMethodHeader* method_header =
1003 stack_visitor->GetCurrentOatQuickMethodHeader();
1004 if (method_header == nullptr) {
1005 return true;
1006 }
1007 const void* code = method_header->GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001008 if (code_cache_->ContainsPc(code) && !code_cache_->IsInZygoteExecSpace(code)) {
Andreas Gampec7d878d2018-11-19 18:42:06 +00001009 // Use the atomic set version, as multiple threads are executing this code.
1010 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1011 }
1012 return true;
1013 },
1014 thread,
1015 /* context= */ nullptr,
1016 art::StackVisitor::StackWalkKind::kSkipInlinedFrames);
1017
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001018 if (kIsDebugBuild) {
1019 // The stack walking code queries the side instrumentation stack if it
1020 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1021 // must have been seen. We sanity check this below.
1022 for (const instrumentation::InstrumentationStackFrame& frame
1023 : *thread->GetInstrumentationStack()) {
1024 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1025 // its stack frame, it is not the method owning return_pc_. We just pass null to
1026 // LookupMethodHeader: the method is only checked against in debug builds.
1027 OatQuickMethodHeader* method_header =
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001028 code_cache_->LookupMethodHeader(frame.return_pc_, /* method= */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001029 if (method_header != nullptr) {
1030 const void* code = method_header->GetCode();
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001031 CHECK(bitmap_->Test(FromCodeToAllocation(code)));
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001032 }
1033 }
1034 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001035 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001036 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001037
1038 private:
1039 JitCodeCache* const code_cache_;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001040 CodeCacheBitmap* const bitmap_;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001041 Barrier* const barrier_;
1042};
1043
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001044void JitCodeCache::NotifyCollectionDone(Thread* self) {
1045 collection_in_progress_ = false;
1046 lock_cond_.Broadcast(self);
1047}
1048
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001049void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1050 Barrier barrier(0);
1051 size_t threads_running_checkpoint = 0;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001052 MarkCodeClosure closure(this, GetLiveBitmap(), &barrier);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001053 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1054 // Now that we have run our checkpoint, move to a suspended state and wait
1055 // for other threads to run the checkpoint.
1056 ScopedThreadSuspension sts(self, kSuspended);
1057 if (threads_running_checkpoint != 0) {
1058 barrier.Increment(self, threads_running_checkpoint);
1059 }
1060}
1061
Nicolas Geoffray35122442016-03-02 12:05:30 +00001062bool JitCodeCache::ShouldDoFullCollection() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001063 if (private_region_.GetCurrentCapacity() == private_region_.GetMaxCapacity()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001064 // Always do a full collection when the code cache is full.
1065 return true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001066 } else if (private_region_.GetCurrentCapacity() < kReservedCapacity) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001067 // Always do partial collection when the code cache size is below the reserved
1068 // capacity.
1069 return false;
1070 } else if (last_collection_increased_code_cache_) {
1071 // This time do a full collection.
1072 return true;
1073 } else {
1074 // This time do a partial collection.
1075 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001076 }
1077}
1078
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001079void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001080 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001081 // Wait for an existing collection, or let everyone know we are starting one.
1082 {
1083 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001084 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001085 if (!garbage_collect_code_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001086 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001087 return;
1088 } else if (WaitForPotentialCollectionToComplete(self)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001089 return;
1090 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001091 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001092 live_bitmap_.reset(CodeCacheBitmap::Create(
1093 "code-cache-bitmap",
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001094 reinterpret_cast<uintptr_t>(private_region_.GetExecPages()->Begin()),
1095 reinterpret_cast<uintptr_t>(
1096 private_region_.GetExecPages()->Begin() + private_region_.GetCurrentCapacity() / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001097 collection_in_progress_ = true;
1098 }
1099 }
1100
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001101 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001102 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001103 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001104
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001105 bool do_full_collection = false;
1106 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001107 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001108 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001109 }
1110
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001111 VLOG(jit) << "Do "
1112 << (do_full_collection ? "full" : "partial")
1113 << " code cache collection, code="
1114 << PrettySize(CodeCacheSize())
1115 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001116
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001117 DoCollection(self, /* collect_profiling_info= */ do_full_collection);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001118
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001119 VLOG(jit) << "After code cache collection, code="
1120 << PrettySize(CodeCacheSize())
1121 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001122
1123 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001124 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001125
1126 // Increase the code cache only when we do partial collections.
1127 // TODO: base this strategy on how full the code cache is?
1128 if (do_full_collection) {
1129 last_collection_increased_code_cache_ = false;
1130 } else {
1131 last_collection_increased_code_cache_ = true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001132 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001133 }
1134
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001135 bool next_collection_will_be_full = ShouldDoFullCollection();
1136
1137 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001138 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001139 // Save the entry point of methods we have compiled, and update the entry
1140 // point of those methods to the interpreter. If the method is invoked, the
1141 // interpreter will update its entry point to the compiled code and call it.
1142 for (ProfilingInfo* info : profiling_infos_) {
1143 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001144 if (!IsInZygoteDataSpace(info) && ContainsPc(entry_point)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001145 info->SetSavedEntryPoint(entry_point);
Vladimir Marko2196c652017-11-30 16:16:07 +00001146 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001147 // class of the method. We may be concurrently running a GC which makes accessing
1148 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1149 // checked that the current entry point is JIT compiled code.
1150 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001151 }
1152 }
1153
Vladimir Marko2196c652017-11-30 16:16:07 +00001154 // Change entry points of native methods back to the GenericJNI entrypoint.
1155 for (const auto& entry : jni_stubs_map_) {
1156 const JniStubData& data = entry.second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001157 if (!data.IsCompiled() || IsInZygoteExecSpace(data.GetCode())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001158 continue;
1159 }
1160 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1161 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1162 const OatQuickMethodHeader* method_header =
1163 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1164 for (ArtMethod* method : data.GetMethods()) {
1165 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1166 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1167 method->SetCounter(new_counter);
1168 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1169 }
1170 }
1171 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001172 }
1173 live_bitmap_.reset(nullptr);
1174 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001175 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001176 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001177 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001178}
1179
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001180void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001181 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001182 std::unordered_set<OatQuickMethodHeader*> method_headers;
1183 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001184 MutexLock mu(self, *Locks::jit_lock_);
Mingyao Yang063fc772016-08-02 11:02:54 -07001185 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001186 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1187 JniStubData* data = &it->second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001188 if (IsInZygoteExecSpace(data->GetCode()) ||
1189 !data->IsCompiled() ||
1190 GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001191 ++it;
1192 } else {
1193 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1194 it = jni_stubs_map_.erase(it);
1195 }
1196 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001197 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1198 const void* code_ptr = it->first;
1199 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001200 if (IsInZygoteExecSpace(code_ptr) || GetLiveBitmap()->Test(allocation)) {
Mingyao Yang063fc772016-08-02 11:02:54 -07001201 ++it;
1202 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001203 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1204 method_headers.insert(header);
Mingyao Yang063fc772016-08-02 11:02:54 -07001205 it = method_code_map_.erase(it);
1206 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001207 }
1208 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001209 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001210}
1211
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001212bool JitCodeCache::GetGarbageCollectCode() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001213 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001214 return garbage_collect_code_;
1215}
1216
1217void JitCodeCache::SetGarbageCollectCode(bool value) {
1218 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001219 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001220 if (garbage_collect_code_ != value) {
1221 if (garbage_collect_code_) {
1222 // When dynamically disabling the garbage collection, we neee
1223 // to make sure that a potential current collection is finished, and also
1224 // clear the saved entry point in profiling infos to avoid dangling pointers.
1225 WaitForPotentialCollectionToComplete(self);
1226 for (ProfilingInfo* info : profiling_infos_) {
1227 info->SetSavedEntryPoint(nullptr);
1228 }
1229 }
1230 // Update the flag while holding the lock to ensure no thread will try to GC.
1231 garbage_collect_code_ = value;
1232 }
1233}
1234
Nicolas Geoffray35122442016-03-02 12:05:30 +00001235void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001236 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001237 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001238 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001239 if (collect_profiling_info) {
1240 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1241 // Also remove the saved entry point from the ProfilingInfo objects.
1242 for (ProfilingInfo* info : profiling_infos_) {
1243 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001244 if (!ContainsPc(ptr) && !info->IsInUseByCompiler() && !IsInZygoteDataSpace(info)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001245 info->GetMethod()->SetProfilingInfo(nullptr);
1246 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001247
1248 if (info->GetSavedEntryPoint() != nullptr) {
1249 info->SetSavedEntryPoint(nullptr);
1250 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001251 // give it a chance to be hot again.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001252 ClearMethodCounter(info->GetMethod(), /*was_warm=*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001253 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001254 }
1255 } else if (kIsDebugBuild) {
1256 // Sanity check that the profiling infos do not have a dangling entry point.
1257 for (ProfilingInfo* info : profiling_infos_) {
David Srbecky605a5fe2019-04-24 14:05:21 +01001258 DCHECK(!Runtime::Current()->IsZygote());
1259 const void* entry_point = info->GetSavedEntryPoint();
1260 DCHECK(entry_point == nullptr || IsInZygoteExecSpace(entry_point));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001261 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001262 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001263
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001264 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1265 // an entry point is either:
1266 // - an osr compiled code, that will be removed if not in a thread call stack.
1267 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001268 for (const auto& entry : jni_stubs_map_) {
1269 const JniStubData& data = entry.second;
1270 const void* code_ptr = data.GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001271 if (IsInZygoteExecSpace(code_ptr)) {
1272 continue;
1273 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001274 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1275 for (ArtMethod* method : data.GetMethods()) {
1276 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1277 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1278 break;
1279 }
1280 }
1281 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001282 for (const auto& it : method_code_map_) {
1283 ArtMethod* method = it.second;
1284 const void* code_ptr = it.first;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001285 if (IsInZygoteExecSpace(code_ptr)) {
1286 continue;
1287 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001288 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1289 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1290 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1291 }
1292 }
1293
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001294 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001295 // on thread stacks).
1296 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001297 }
1298
1299 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001300 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001301
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001302 // At this point, mutator threads are still running, and entrypoints of methods can
1303 // change. We do know they cannot change to a code cache entry that is not marked,
1304 // therefore we can safely remove those entries.
1305 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001306
Nicolas Geoffray35122442016-03-02 12:05:30 +00001307 if (collect_profiling_info) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001308 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001309 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001310 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001311 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001312 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001313 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1314 // that the compiled code would not get revived. As mutator threads run concurrently,
1315 // they may have revived the compiled code, and now we are in the situation where
1316 // a method has compiled code but no ProfilingInfo.
1317 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1318 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001319 if (ContainsPc(ptr) &&
1320 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001321 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001322 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001323 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001324 private_region_.FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001325 return true;
1326 }
1327 return false;
1328 });
1329 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001330 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001331}
1332
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001333OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001334 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1335 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001336 // On Thumb-2, the pc is offset by one.
1337 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001338 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001339 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1340 return nullptr;
1341 }
1342
Vladimir Marko2196c652017-11-30 16:16:07 +00001343 if (!kIsDebugBuild) {
1344 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1345 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001346 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001347
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001348 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001349 OatQuickMethodHeader* method_header = nullptr;
1350 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1351 if (method != nullptr && UNLIKELY(method->IsNative())) {
1352 auto it = jni_stubs_map_.find(JniStubKey(method));
1353 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1354 return nullptr;
1355 }
1356 const void* code_ptr = it->second.GetCode();
1357 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1358 if (!method_header->Contains(pc)) {
1359 return nullptr;
1360 }
1361 } else {
1362 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1363 if (it != method_code_map_.begin()) {
1364 --it;
1365 const void* code_ptr = it->first;
1366 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1367 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1368 found_method = it->second;
1369 }
1370 }
1371 if (method_header == nullptr && method == nullptr) {
1372 // Scan all compiled JNI stubs as well. This slow search is used only
1373 // for checks in debug build, for release builds the `method` is not null.
1374 for (auto&& entry : jni_stubs_map_) {
1375 const JniStubData& data = entry.second;
1376 if (data.IsCompiled() &&
1377 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1378 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1379 }
1380 }
1381 }
1382 if (method_header == nullptr) {
1383 return nullptr;
1384 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001385 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001386
1387 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Vladimir Markoeab02482019-05-09 10:28:17 +01001388 DCHECK_EQ(found_method, method)
1389 << ArtMethod::PrettyMethod(method) << " "
1390 << ArtMethod::PrettyMethod(found_method) << " "
David Sehr709b0702016-10-13 09:12:37 -07001391 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001392 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001393 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001394}
1395
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001396OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001397 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001398 auto it = osr_code_map_.find(method);
1399 if (it == osr_code_map_.end()) {
1400 return nullptr;
1401 }
1402 return OatQuickMethodHeader::FromCodePointer(it->second);
1403}
1404
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001405ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1406 ArtMethod* method,
1407 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001408 bool retry_allocation)
1409 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1410 NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001411 DCHECK(CanAllocateProfilingInfo());
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001412 ProfilingInfo* info = nullptr;
1413 if (!retry_allocation) {
1414 // If we are allocating for the interpreter, just try to lock, to avoid
1415 // lock contention with the JIT.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001416 if (Locks::jit_lock_->ExclusiveTryLock(self)) {
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001417 info = AddProfilingInfoInternal(self, method, entries);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001418 Locks::jit_lock_->ExclusiveUnlock(self);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001419 }
1420 } else {
1421 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001422 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001423 info = AddProfilingInfoInternal(self, method, entries);
1424 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001425
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001426 if (info == nullptr) {
1427 GarbageCollectCache(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001428 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001429 info = AddProfilingInfoInternal(self, method, entries);
1430 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001431 }
1432 return info;
1433}
1434
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001435ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001436 ArtMethod* method,
1437 const std::vector<uint32_t>& entries) {
1438 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001439 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001440 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001441
1442 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001443 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001444 if (info != nullptr) {
1445 return info;
1446 }
1447
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001448 uint8_t* data = private_region_.AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001449 if (data == nullptr) {
1450 return nullptr;
1451 }
1452 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001453
1454 // Make sure other threads see the data in the profiling info object before the
1455 // store in the ArtMethod's ProfilingInfo pointer.
Orion Hodson27b96762018-03-13 16:06:57 +00001456 std::atomic_thread_fence(std::memory_order_release);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001457
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001458 method->SetProfilingInfo(info);
1459 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001460 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001461 return info;
1462}
1463
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001464void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001465 return shared_region_.OwnsSpace(mspace)
1466 ? shared_region_.MoreCore(mspace, increment)
1467 : private_region_.MoreCore(mspace, increment);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001468}
1469
Calin Juravle99629622016-04-19 16:33:46 +01001470void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001471 std::vector<ProfileMethodInfo>& methods) {
Nicolas Geoffray1afdfe62018-11-21 09:38:10 +00001472 Thread* self = Thread::Current();
1473 WaitUntilInlineCacheAccessible(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001474 MutexLock mu(self, *Locks::jit_lock_);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001475 ScopedTrace trace(__FUNCTION__);
Calin Juravlea39fd982017-05-18 10:15:52 -07001476 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001477 for (const ProfilingInfo* info : profiling_infos_) {
1478 ArtMethod* method = info->GetMethod();
1479 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001480 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1481 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001482 // Skip dex files which are not profiled.
1483 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001484 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001485 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001486
1487 // If the method didn't reach the compilation threshold don't save the inline caches.
1488 // They might be incomplete and cause unnecessary deoptimizations.
1489 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1490 if (method->GetCounter() < jit_compile_threshold) {
1491 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001492 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001493 continue;
1494 }
1495
Calin Juravle940eb0c2017-01-30 19:30:44 -08001496 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001497 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001498 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001499 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001500 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001501 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1502 mirror::Class* cls = cache.classes_[k].Read();
1503 if (cls == nullptr) {
1504 break;
1505 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001506
Calin Juravle13439f02017-02-21 01:17:21 -08001507 // Check if the receiver is in the boot class path or if it's in the
1508 // same class loader as the caller. If not, skip it, as there is not
1509 // much we can do during AOT.
1510 if (!cls->IsBootStrapClassLoaded() &&
1511 caller->GetClassLoader() != cls->GetClassLoader()) {
1512 is_missing_types = true;
1513 continue;
1514 }
1515
Calin Juravle4ca70a32017-02-21 16:22:24 -08001516 const DexFile* class_dex_file = nullptr;
1517 dex::TypeIndex type_index;
1518
1519 if (cls->GetDexCache() == nullptr) {
1520 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001521 // Make a best effort to find the type index in the method's dex file.
1522 // We could search all open dex files but that might turn expensive
1523 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001524 class_dex_file = dex_file;
1525 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1526 } else {
1527 class_dex_file = &(cls->GetDexFile());
1528 type_index = cls->GetDexTypeIndex();
1529 }
1530 if (!type_index.IsValid()) {
1531 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001532 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001533 continue;
1534 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001535 if (ContainsElement(dex_base_locations,
1536 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001537 // Only consider classes from the same apk (including multidex).
1538 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001539 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001540 } else {
1541 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001542 }
1543 }
1544 if (!profile_classes.empty()) {
1545 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001546 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001547 }
1548 }
1549 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001550 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001551 }
1552}
1553
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001554bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001555 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001556 return osr_code_map_.find(method) != osr_code_map_.end();
1557}
1558
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001559bool JitCodeCache::NotifyCompilationOf(ArtMethod* method,
1560 Thread* self,
1561 bool osr,
1562 bool prejit,
1563 JitMemoryRegion* region) {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001564 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001565 return false;
1566 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001567
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01001568 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1569 if (class_linker->IsQuickResolutionStub(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001570 if (!prejit) {
1571 // Unless we're pre-jitting, we currently don't save the JIT compiled code if we cannot
1572 // update the entrypoint due to having the resolution stub.
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001573 VLOG(jit) << "Not compiling "
1574 << method->PrettyMethod()
1575 << " because it has the resolution stub";
1576 // Give it a new chance to be hot.
1577 ClearMethodCounter(method, /*was_warm=*/ false);
1578 return false;
1579 }
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01001580 }
1581
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001582 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001583 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1584 return false;
1585 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001586
Vladimir Marko2196c652017-11-30 16:16:07 +00001587 if (UNLIKELY(method->IsNative())) {
1588 JniStubKey key(method);
1589 auto it = jni_stubs_map_.find(key);
1590 bool new_compilation = false;
1591 if (it == jni_stubs_map_.end()) {
1592 // Create a new entry to mark the stub as being compiled.
1593 it = jni_stubs_map_.Put(key, JniStubData{});
1594 new_compilation = true;
1595 }
1596 JniStubData* data = &it->second;
1597 data->AddMethod(method);
1598 if (data->IsCompiled()) {
1599 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1600 const void* entrypoint = method_header->GetEntryPoint();
1601 // Update also entrypoints of other methods held by the JniStubData.
1602 // We could simply update the entrypoint of `method` but if the last JIT GC has
1603 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1604 // as well change them back as this stub shall not be collected anyway and this
1605 // can avoid a few expensive GenericJNI calls.
1606 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1607 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +00001608 // Call the dedicated method instead of the more generic UpdateMethodsCode, because
1609 // `m` might be in the process of being deleted.
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001610 if (!class_linker->IsQuickResolutionStub(m->GetEntryPointFromQuickCompiledCode())) {
1611 instrumentation->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
1612 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001613 }
1614 if (collection_in_progress_) {
David Srbeckyc45b5892019-04-24 10:32:04 +01001615 if (!IsInZygoteExecSpace(data->GetCode())) {
1616 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1617 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001618 }
1619 }
1620 return new_compilation;
1621 } else {
1622 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1623 if (info == nullptr) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001624 // When prejitting, we don't allocate a profiling info.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001625 if (!prejit && !IsSharedRegion(*region)) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001626 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1627 // Because the counter is not atomic, there are some rare cases where we may not hit the
1628 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
1629 ClearMethodCounter(method, /*was_warm=*/ false);
1630 return false;
1631 }
1632 } else {
1633 if (info->IsMethodBeingCompiled(osr)) {
1634 return false;
1635 }
1636 info->SetIsMethodBeingCompiled(true, osr);
Vladimir Marko2196c652017-11-30 16:16:07 +00001637 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001638 return true;
1639 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001640}
1641
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001642ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001643 MutexLock mu(self, *Locks::jit_lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001644 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001645 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001646 if (!info->IncrementInlineUse()) {
1647 // Overflow of inlining uses, just bail.
1648 return nullptr;
1649 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001650 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001651 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001652}
1653
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001654void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001655 MutexLock mu(self, *Locks::jit_lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001656 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001657 DCHECK(info != nullptr);
1658 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001659}
1660
Vladimir Marko2196c652017-11-30 16:16:07 +00001661void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
1662 DCHECK_EQ(Thread::Current(), self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001663 MutexLock mu(self, *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001664 if (UNLIKELY(method->IsNative())) {
1665 auto it = jni_stubs_map_.find(JniStubKey(method));
1666 DCHECK(it != jni_stubs_map_.end());
1667 JniStubData* data = &it->second;
1668 DCHECK(ContainsElement(data->GetMethods(), method));
1669 if (UNLIKELY(!data->IsCompiled())) {
1670 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1671 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
1672 } // else CommitCodeInternal() updated entrypoints of all methods in the JniStubData.
1673 } else {
1674 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001675 if (info != nullptr) {
1676 DCHECK(info->IsMethodBeingCompiled(osr));
1677 info->SetIsMethodBeingCompiled(false, osr);
1678 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001679 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001680}
1681
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001682void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1683 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001684 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07001685 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Alex Light2d441b12018-06-08 15:33:21 -07001686 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001687 if ((profiling_info != nullptr) &&
1688 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
Alex Light2d441b12018-06-08 15:33:21 -07001689 // When instrumentation is set, the actual entrypoint is the one in the profiling info.
1690 method_entrypoint = profiling_info->GetSavedEntryPoint();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001691 // Prevent future uses of the compiled code.
1692 profiling_info->SetSavedEntryPoint(nullptr);
1693 }
1694
Alex Light2d441b12018-06-08 15:33:21 -07001695 // Clear the method counter if we are running jitted code since we might want to jit this again in
1696 // the future.
1697 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001698 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001699 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001700 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1701 method, GetQuickToInterpreterBridge());
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001702 ClearMethodCounter(method, /*was_warm=*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001703 } else {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001704 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001705 auto it = osr_code_map_.find(method);
1706 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1707 // Remove the OSR method, to avoid using it again.
1708 osr_code_map_.erase(it);
1709 }
1710 }
1711}
1712
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001713void JitCodeCache::Dump(std::ostream& os) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001714 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
1715 os << "Current JIT code cache size: " << PrettySize(private_region_.GetUsedMemoryForCode())
1716 << "\n"
1717 << "Current JIT data cache size: " << PrettySize(private_region_.GetUsedMemoryForData())
1718 << "\n"
David Srbeckyafc60cd2018-12-05 11:59:31 +00001719 << "Current JIT mini-debug-info size: " << PrettySize(GetJitMiniDebugInfoMemUsage()) << "\n"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001720 << "Current JIT capacity: " << PrettySize(private_region_.GetCurrentCapacity()) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00001721 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001722 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1723 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1724 << "Total number of JIT compilations for on stack replacement: "
1725 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001726 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001727 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1728 histogram_code_memory_use_.PrintMemoryUse(os);
1729 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001730}
1731
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001732void JitCodeCache::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffray88f3fd92019-06-27 16:32:13 +01001733 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
1734
1735 // Reset potential writable MemMaps inherited from the zygote. We never want
1736 // to write to them.
1737 shared_region_.ResetWritableMappings();
1738
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001739 if (is_zygote || Runtime::Current()->IsSafeMode()) {
1740 // Don't create a private region for a child zygote. Regions are usually map shared
1741 // (to satisfy dual-view), and we don't want children of a child zygote to inherit it.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001742 return;
1743 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001744
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001745 if (private_region_.IsValid()) {
1746 // In case the zygote was running with its own private region (happens for
1747 // unit tests), move the region to the shared one.
1748 CHECK(!shared_region_.IsValid());
1749 std::swap(shared_region_, private_region_);
1750 }
Nicolas Geoffray2fef66b2019-06-26 22:00:02 +00001751
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001752 // Reset all statistics to be specific to this process.
1753 number_of_compilations_ = 0;
1754 number_of_osr_compilations_ = 0;
1755 number_of_collections_ = 0;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001756
1757 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
1758 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001759 std::string error_msg;
Nicolas Geoffray9c54e182019-06-18 10:42:52 +01001760 if (!private_region_.Initialize(initial_capacity,
1761 max_capacity,
1762 /* rwx_memory_allowed= */ !is_system_server,
1763 is_zygote,
1764 &error_msg)) {
1765 LOG(WARNING) << "Could not create private region after zygote fork: " << error_msg;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001766 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001767}
1768
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001769JitMemoryRegion* JitCodeCache::GetCurrentRegion() {
1770 return Runtime::Current()->IsZygote() ? &shared_region_ : &private_region_;
1771}
1772
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001773} // namespace jit
1774} // namespace art