blob: 519655d843b050731463712c64e8953f23e65a68 [file] [log] [blame]
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001/*
2 * Copyright 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "jit_code_cache.h"
18
19#include <sstream>
20
Andreas Gampec7d878d2018-11-19 18:42:06 +000021#include <android-base/logging.h>
Orion Hodson1d3fd082018-09-28 09:38:35 +010022
Andreas Gampe5629d2d2017-05-15 16:28:13 -070023#include "arch/context.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070024#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070025#include "base/enums.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070026#include "base/histogram-inl.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080027#include "base/logging.h" // For VLOG.
Orion Hodson563ada22018-09-04 11:28:31 +010028#include "base/membarrier.h"
Orion Hodson1d3fd082018-09-28 09:38:35 +010029#include "base/memfd.h"
David Sehr79e26072018-04-06 17:58:50 -070030#include "base/mem_map.h"
David Sehrc431b9d2018-03-02 12:01:51 -080031#include "base/quasi_atomic.h"
Calin Juravle66f55232015-12-08 15:09:10 +000032#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080033#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010034#include "base/time_utils.h"
Orion Hodsonf2331362018-07-11 15:14:10 +010035#include "base/utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070036#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000037#include "debugger_interface.h"
David Sehr9e734c72018-01-04 17:56:19 -080038#include "dex/dex_file_loader.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070039#include "dex/method_reference.h"
Vladimir Marko5115a4d2019-10-17 14:56:47 +010040#include "entrypoints/entrypoint_utils-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010041#include "entrypoints/runtime_asm_entrypoints.h"
42#include "gc/accounting/bitmap-inl.h"
Andreas Gampe88dbad32018-06-26 19:54:12 -070043#include "gc/allocator/dlmalloc.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010044#include "gc/scoped_gc_critical_section.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000045#include "handle.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070046#include "instrumentation.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070047#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000048#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000049#include "jit/profiling_info.h"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010050#include "jit/jit_scoped_code_cache_write.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010051#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080052#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070053#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070054#include "object_callbacks.h"
David Sehr82d046e2018-04-23 08:14:19 -070055#include "profile/profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070056#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070057#include "stack.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000058#include "thread-current-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010059#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080060
61namespace art {
62namespace jit {
63
Nicolas Geoffray933330a2016-03-16 14:20:06 +000064static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
65static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
66
Vladimir Marko2196c652017-11-30 16:16:07 +000067class JitCodeCache::JniStubKey {
68 public:
69 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
70 : shorty_(method->GetShorty()),
71 is_static_(method->IsStatic()),
72 is_fast_native_(method->IsFastNative()),
73 is_critical_native_(method->IsCriticalNative()),
74 is_synchronized_(method->IsSynchronized()) {
75 DCHECK(!(is_fast_native_ && is_critical_native_));
76 }
77
78 bool operator<(const JniStubKey& rhs) const {
79 if (is_static_ != rhs.is_static_) {
80 return rhs.is_static_;
81 }
82 if (is_synchronized_ != rhs.is_synchronized_) {
83 return rhs.is_synchronized_;
84 }
85 if (is_fast_native_ != rhs.is_fast_native_) {
86 return rhs.is_fast_native_;
87 }
88 if (is_critical_native_ != rhs.is_critical_native_) {
89 return rhs.is_critical_native_;
90 }
91 return strcmp(shorty_, rhs.shorty_) < 0;
92 }
93
94 // Update the shorty to point to another method's shorty. Call this function when removing
95 // the method that references the old shorty from JniCodeData and not removing the entire
96 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
97 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
98 const char* shorty = method->GetShorty();
99 DCHECK_STREQ(shorty_, shorty);
100 shorty_ = shorty;
101 }
102
103 private:
104 // The shorty points to a DexFile data and may need to change
105 // to point to the same shorty in a different DexFile.
106 mutable const char* shorty_;
107
108 const bool is_static_;
109 const bool is_fast_native_;
110 const bool is_critical_native_;
111 const bool is_synchronized_;
112};
113
114class JitCodeCache::JniStubData {
115 public:
116 JniStubData() : code_(nullptr), methods_() {}
117
118 void SetCode(const void* code) {
119 DCHECK(code != nullptr);
120 code_ = code;
121 }
122
Vladimir Markocce414f2019-10-07 08:51:33 +0100123 void UpdateEntryPoints(const void* entrypoint) REQUIRES_SHARED(Locks::mutator_lock_) {
124 DCHECK(IsCompiled());
125 DCHECK(entrypoint == OatQuickMethodHeader::FromCodePointer(GetCode())->GetEntryPoint());
126 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
127 for (ArtMethod* m : GetMethods()) {
128 // Because `m` might be in the process of being deleted:
129 // - Call the dedicated method instead of the more generic UpdateMethodsCode
Vladimir Marko5115a4d2019-10-17 14:56:47 +0100130 // - Check the class status without a full read barrier; use ReadBarrier::IsMarked().
131 bool can_set_entrypoint = true;
132 if (NeedsClinitCheckBeforeCall(m)) {
133 // To avoid resurrecting an unreachable object, we must not use a full read
134 // barrier but we do not want to miss updating an entrypoint under common
135 // circumstances, i.e. during a GC the class becomes visibly initialized,
136 // the method becomes hot, we compile the thunk and want to update the
137 // entrypoint while the method's declaring class field still points to the
138 // from-space class object with the old status. Therefore we read the
139 // declaring class without a read barrier and check if it's already marked.
140 // If yes, we check the status of the to-space class object as intended.
141 // Otherwise, there is no to-space object and the from-space class object
142 // contains the most recent value of the status field; even if this races
143 // with another thread doing a read barrier and updating the status, that's
144 // no different from a race with a thread that just updates the status.
145 // Such race can happen only for the zygote method pre-compilation, as we
146 // otherwise compile only thunks for methods of visibly initialized classes.
147 ObjPtr<mirror::Class> klass = m->GetDeclaringClass<kWithoutReadBarrier>();
148 ObjPtr<mirror::Class> marked = ReadBarrier::IsMarked(klass.Ptr());
149 ObjPtr<mirror::Class> checked_klass = (marked != nullptr) ? marked : klass;
150 can_set_entrypoint = checked_klass->IsVisiblyInitialized();
151 }
152 if (can_set_entrypoint) {
Vladimir Markocce414f2019-10-07 08:51:33 +0100153 instrum->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
154 }
155 }
156 }
157
Vladimir Marko2196c652017-11-30 16:16:07 +0000158 const void* GetCode() const {
159 return code_;
160 }
161
162 bool IsCompiled() const {
163 return GetCode() != nullptr;
164 }
165
166 void AddMethod(ArtMethod* method) {
167 if (!ContainsElement(methods_, method)) {
168 methods_.push_back(method);
169 }
170 }
171
172 const std::vector<ArtMethod*>& GetMethods() const {
173 return methods_;
174 }
175
176 void RemoveMethodsIn(const LinearAlloc& alloc) {
177 auto kept_end = std::remove_if(
178 methods_.begin(),
179 methods_.end(),
180 [&alloc](ArtMethod* method) { return alloc.ContainsUnsafe(method); });
181 methods_.erase(kept_end, methods_.end());
182 }
183
184 bool RemoveMethod(ArtMethod* method) {
185 auto it = std::find(methods_.begin(), methods_.end(), method);
186 if (it != methods_.end()) {
187 methods_.erase(it);
188 return true;
189 } else {
190 return false;
191 }
192 }
193
194 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
195 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
196 }
197
198 private:
199 const void* code_;
200 std::vector<ArtMethod*> methods_;
201};
202
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000203JitCodeCache* JitCodeCache::Create(bool used_only_for_profile_data,
204 bool rwx_memory_allowed,
205 bool is_zygote,
206 std::string* error_msg) {
207 // Register for membarrier expedited sync core if JIT will be generating code.
208 if (!used_only_for_profile_data) {
209 if (art::membarrier(art::MembarrierCommand::kRegisterPrivateExpeditedSyncCore) != 0) {
210 // MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE ensures that CPU instruction pipelines are
211 // flushed and it's used when adding code to the JIT. The memory used by the new code may
212 // have just been released and, in theory, the old code could still be in a pipeline.
213 VLOG(jit) << "Kernel does not support membarrier sync-core";
214 }
215 }
216
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100217 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000218 // Check whether the provided max capacity in options is below 1GB.
219 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
220 // We need to have 32 bit offsets from method headers in code cache which point to things
221 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
222 // Ensure we're below 1 GB to be safe.
223 if (max_capacity > 1 * GB) {
224 std::ostringstream oss;
225 oss << "Maxium code cache capacity is limited to 1 GB, "
226 << PrettySize(max_capacity) << " is too big";
227 *error_msg = oss.str();
228 return nullptr;
229 }
230
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100231 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100232 JitMemoryRegion region;
233 if (!region.Initialize(initial_capacity,
234 max_capacity,
235 rwx_memory_allowed,
236 is_zygote,
237 error_msg)) {
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000238 return nullptr;
239 }
240
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100241 std::unique_ptr<JitCodeCache> jit_code_cache(new JitCodeCache());
242 if (is_zygote) {
243 // Zygote should never collect code to share the memory with the children.
244 jit_code_cache->garbage_collect_code_ = false;
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000245 jit_code_cache->shared_region_ = std::move(region);
246 } else {
247 jit_code_cache->private_region_ = std::move(region);
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100248 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000249
250 VLOG(jit) << "Created jit code cache: initial capacity="
251 << PrettySize(initial_capacity)
252 << ", maximum capacity="
253 << PrettySize(max_capacity);
254
255 return jit_code_cache.release();
256}
257
258JitCodeCache::JitCodeCache()
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100259 : is_weak_access_enabled_(true),
260 inline_cache_cond_("Jit inline cache condition variable", *Locks::jit_lock_),
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100261 zygote_map_(&shared_region_),
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100262 lock_cond_("Jit code cache condition variable", *Locks::jit_lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100263 collection_in_progress_(false),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000264 last_collection_increased_code_cache_(false),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100265 garbage_collect_code_(true),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000266 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000267 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000268 number_of_collections_(0),
269 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
270 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100271 histogram_profiling_info_memory_use_("Memory used for profiling info", 16) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800272}
273
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000274JitCodeCache::~JitCodeCache() {}
275
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100276bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100277 return private_region_.IsInExecSpace(ptr) || shared_region_.IsInExecSpace(ptr);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800278}
279
Alex Light2d441b12018-06-08 15:33:21 -0700280bool JitCodeCache::WillExecuteJitCode(ArtMethod* method) {
281 ScopedObjectAccess soa(art::Thread::Current());
282 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
283 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
284 return true;
285 } else if (method->GetEntryPointFromQuickCompiledCode() == GetQuickInstrumentationEntryPoint()) {
286 return FindCompiledCodeForInstrumentation(method) != nullptr;
287 }
288 return false;
289}
290
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000291bool JitCodeCache::ContainsMethod(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100292 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000293 if (UNLIKELY(method->IsNative())) {
294 auto it = jni_stubs_map_.find(JniStubKey(method));
295 if (it != jni_stubs_map_.end() &&
296 it->second.IsCompiled() &&
297 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000298 return true;
299 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000300 } else {
301 for (const auto& it : method_code_map_) {
302 if (it.second == method) {
303 return true;
304 }
305 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100306 if (zygote_map_.ContainsMethod(method)) {
307 return true;
308 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000309 }
310 return false;
311}
312
Vladimir Marko2196c652017-11-30 16:16:07 +0000313const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
314 DCHECK(method->IsNative());
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100315 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000316 auto it = jni_stubs_map_.find(JniStubKey(method));
317 if (it != jni_stubs_map_.end()) {
318 JniStubData& data = it->second;
319 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
320 return data.GetCode();
321 }
322 }
323 return nullptr;
324}
325
Alex Light2d441b12018-06-08 15:33:21 -0700326const void* JitCodeCache::FindCompiledCodeForInstrumentation(ArtMethod* method) {
Alex Light839f53a2018-07-10 15:46:14 -0700327 // If jit-gc is still on we use the SavedEntryPoint field for doing that and so cannot use it to
328 // find the instrumentation entrypoint.
329 if (LIKELY(GetGarbageCollectCode())) {
Alex Light2d441b12018-06-08 15:33:21 -0700330 return nullptr;
331 }
332 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
333 if (info == nullptr) {
334 return nullptr;
335 }
336 // When GC is disabled for trampoline tracing we will use SavedEntrypoint to hold the actual
337 // jit-compiled version of the method. If jit-gc is disabled for other reasons this will just be
338 // nullptr.
339 return info->GetSavedEntryPoint();
340}
341
Nicolas Geoffray32384402019-07-17 20:06:44 +0100342const void* JitCodeCache::GetSavedEntryPointOfPreCompiledMethod(ArtMethod* method) {
343 if (Runtime::Current()->IsUsingApexBootImageLocation() && method->IsPreCompiled()) {
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100344 const void* code_ptr = nullptr;
Nicolas Geoffray32384402019-07-17 20:06:44 +0100345 if (method->GetDeclaringClass()->GetClassLoader() == nullptr) {
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100346 code_ptr = zygote_map_.GetCodeFor(method);
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100347 } else {
Nicolas Geoffray32384402019-07-17 20:06:44 +0100348 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
349 auto it = saved_compiled_methods_map_.find(method);
350 if (it != saved_compiled_methods_map_.end()) {
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100351 code_ptr = it->second;
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100352 }
Nicolas Geoffrayde0ccff2019-07-19 10:54:05 +0100353 }
354 if (code_ptr != nullptr) {
355 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
356 return method_header->GetEntryPoint();
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100357 }
358 }
359 return nullptr;
360}
361
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100362bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
363 bool in_collection = false;
364 while (collection_in_progress_) {
365 in_collection = true;
366 lock_cond_.Wait(self);
367 }
368 return in_collection;
369}
370
371static uintptr_t FromCodeToAllocation(const void* code) {
Orion Hodsone764f382019-06-27 12:56:48 +0100372 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100373 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
374}
375
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000376static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
377 // The length of the table is stored just before the stack map (and therefore at the end of
378 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
379 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
380}
381
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000382static void DCheckRootsAreValid(const std::vector<Handle<mirror::Object>>& roots,
383 bool is_shared_region)
Alex Light3e36a9c2018-06-19 09:45:05 -0700384 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
385 if (!kIsDebugBuild) {
386 return;
387 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700388 // Put all roots in `roots_data`.
Vladimir Markoac3ac682018-09-20 11:01:43 +0100389 for (Handle<mirror::Object> object : roots) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700390 // Ensure the string is strongly interned. b/32995596
391 if (object->IsString()) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100392 ObjPtr<mirror::String> str = object->AsString();
Alex Light3e36a9c2018-06-19 09:45:05 -0700393 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
394 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
395 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000396 // Ensure that we don't put movable objects in the shared region.
397 if (is_shared_region) {
398 CHECK(!Runtime::Current()->GetHeap()->IsMovableObject(object.Get()));
399 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700400 }
401}
402
David Srbecky87fb0322019-08-20 10:34:02 +0100403static const uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000404 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
405 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
406 uint32_t roots = GetNumberOfRoots(data);
407 if (number_of_roots != nullptr) {
408 *number_of_roots = roots;
409 }
410 return data - ComputeRootTableSize(roots);
411}
412
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100413// Use a sentinel for marking entries in the JIT table that have been cleared.
414// This helps diagnosing in case the compiled code tries to wrongly access such
415// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700416static mirror::Class* const weak_sentinel =
417 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100418
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000419// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100420static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
421 IsMarkedVisitor* visitor,
422 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000423 REQUIRES_SHARED(Locks::mutator_lock_) {
424 // This does not need a read barrier because this is called by GC.
425 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100426 if (cls != nullptr && cls != weak_sentinel) {
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700427 DCHECK((cls->IsClass<kDefaultVerifyFlags>()));
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000428 // Look at the classloader of the class to know if it has been unloaded.
429 // This does not need a read barrier because this is called by GC.
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000430 ObjPtr<mirror::Object> class_loader =
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000431 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000432 if (class_loader == nullptr || visitor->IsMarked(class_loader.Ptr()) != nullptr) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000433 // The class loader is live, update the entry if the class has moved.
434 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
435 // Note that new_object can be null for CMS and newly allocated objects.
436 if (new_cls != nullptr && new_cls != cls) {
437 *root_ptr = GcRoot<mirror::Class>(new_cls);
438 }
439 } else {
440 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100441 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000442 }
443 }
444}
445
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000446void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100447 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000448 for (const auto& entry : method_code_map_) {
449 uint32_t number_of_roots = 0;
David Srbecky87fb0322019-08-20 10:34:02 +0100450 const uint8_t* root_table = GetRootTable(entry.first, &number_of_roots);
451 uint8_t* roots_data = private_region_.IsInDataSpace(root_table)
452 ? private_region_.GetWritableDataAddress(root_table)
453 : shared_region_.GetWritableDataAddress(root_table);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000454 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
455 for (uint32_t i = 0; i < number_of_roots; ++i) {
456 // This does not need a read barrier because this is called by GC.
457 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100458 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000459 // entry got deleted in a previous sweep.
Vladimir Markod355acf2019-03-21 17:09:40 +0000460 } else if (object->IsString<kDefaultVerifyFlags>()) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000461 mirror::Object* new_object = visitor->IsMarked(object);
462 // We know the string is marked because it's a strongly-interned string that
463 // is always alive. The IsMarked implementation of the CMS collector returns
464 // null for newly allocated objects, but we know those haven't moved. Therefore,
465 // only update the entry if we get a different non-null string.
466 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
467 // out of the weak access/creation pause. b/32167580
468 if (new_object != nullptr && new_object != object) {
469 DCHECK(new_object->IsString());
470 roots[i] = GcRoot<mirror::Object>(new_object);
471 }
472 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100473 ProcessWeakClass(
474 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000475 }
476 }
477 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000478 // Walk over inline caches to clear entries containing unloaded classes.
479 for (ProfilingInfo* info : profiling_infos_) {
480 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
481 InlineCache* cache = &info->cache_[i];
482 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100483 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000484 }
485 }
486 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000487}
488
David Srbecky8fc2f952019-07-31 18:40:09 +0100489void JitCodeCache::FreeCodeAndData(const void* code_ptr, bool free_debug_info) {
Nicolas Geoffrayae982f92018-12-08 12:31:10 +0000490 if (IsInZygoteExecSpace(code_ptr)) {
491 // No need to free, this is shared memory.
492 return;
493 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100494 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky8fc2f952019-07-31 18:40:09 +0100495 if (free_debug_info) {
496 // Remove compressed mini-debug info for the method.
497 // TODO: This is expensive, so we should always do it in the caller in bulk.
498 RemoveNativeDebugInfoForJit(ArrayRef<const void*>(&code_ptr, 1));
499 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000500 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100501 private_region_.FreeData(GetRootTable(code_ptr));
Vladimir Marko2196c652017-11-30 16:16:07 +0000502 } // else this is a JNI stub without any data.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100503
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100504 private_region_.FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100505}
506
Mingyao Yang063fc772016-08-02 11:02:54 -0700507void JitCodeCache::FreeAllMethodHeaders(
508 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700509 // We need to remove entries in method_headers from CHA dependencies
510 // first since once we do FreeCode() below, the memory can be reused
511 // so it's possible for the same method_header to start representing
512 // different compile code.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100513 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000514 {
515 MutexLock mu2(Thread::Current(), *Locks::cha_lock_);
516 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
517 ->RemoveDependentsWithMethodHeaders(method_headers);
518 }
519
David Srbecky8fc2f952019-07-31 18:40:09 +0100520 // Remove compressed mini-debug info for the methods.
521 std::vector<const void*> removed_symbols;
522 removed_symbols.reserve(method_headers.size());
523 for (const OatQuickMethodHeader* method_header : method_headers) {
524 removed_symbols.push_back(method_header->GetCode());
525 }
526 std::sort(removed_symbols.begin(), removed_symbols.end());
527 RemoveNativeDebugInfoForJit(ArrayRef<const void*>(removed_symbols));
528
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100529 ScopedCodeCacheWrite scc(private_region_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700530 for (const OatQuickMethodHeader* method_header : method_headers) {
David Srbecky8fc2f952019-07-31 18:40:09 +0100531 FreeCodeAndData(method_header->GetCode(), /*free_debug_info=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700532 }
533}
534
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100535void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800536 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700537 // We use a set to first collect all method_headers whose code need to be
538 // removed. We need to free the underlying code after we remove CHA dependencies
539 // for entries in this set. And it's more efficient to iterate through
540 // the CHA dependency map just once with an unordered_set.
541 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000542 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100543 MutexLock mu(self, *Locks::jit_lock_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700544 // We do not check if a code cache GC is in progress, as this method comes
545 // with the classlinker_classes_lock_ held, and suspending ourselves could
546 // lead to a deadlock.
547 {
Vladimir Marko2196c652017-11-30 16:16:07 +0000548 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
549 it->second.RemoveMethodsIn(alloc);
550 if (it->second.GetMethods().empty()) {
551 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
552 it = jni_stubs_map_.erase(it);
553 } else {
554 it->first.UpdateShorty(it->second.GetMethods().front());
555 ++it;
556 }
557 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700558 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
559 if (alloc.ContainsUnsafe(it->second)) {
560 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
561 it = method_code_map_.erase(it);
562 } else {
563 ++it;
564 }
565 }
566 }
567 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
568 if (alloc.ContainsUnsafe(it->first)) {
569 // Note that the code has already been pushed to method_headers in the loop
570 // above and is going to be removed in FreeCode() below.
571 it = osr_code_map_.erase(it);
572 } else {
573 ++it;
574 }
575 }
576 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
577 ProfilingInfo* info = *it;
578 if (alloc.ContainsUnsafe(info->GetMethod())) {
579 info->GetMethod()->SetProfilingInfo(nullptr);
David Srbecky87fb0322019-08-20 10:34:02 +0100580 private_region_.FreeWritableData(reinterpret_cast<uint8_t*>(info));
Mingyao Yang063fc772016-08-02 11:02:54 -0700581 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000582 } else {
583 ++it;
584 }
585 }
586 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700587 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100588}
589
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000590bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
591 return kUseReadBarrier
592 ? self->GetWeakRefAccessEnabled()
Orion Hodson88591fe2018-03-06 13:35:43 +0000593 : is_weak_access_enabled_.load(std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000594}
595
596void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
597 if (IsWeakAccessEnabled(self)) {
598 return;
599 }
600 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100601 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000602 while (!IsWeakAccessEnabled(self)) {
603 inline_cache_cond_.Wait(self);
604 }
605}
606
607void JitCodeCache::BroadcastForInlineCacheAccess() {
608 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100609 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000610 inline_cache_cond_.Broadcast(self);
611}
612
613void JitCodeCache::AllowInlineCacheAccess() {
614 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000615 is_weak_access_enabled_.store(true, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000616 BroadcastForInlineCacheAccess();
617}
618
619void JitCodeCache::DisallowInlineCacheAccess() {
620 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000621 is_weak_access_enabled_.store(false, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000622}
623
624void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
625 Handle<mirror::ObjectArray<mirror::Class>> array) {
626 WaitUntilInlineCacheAccessible(Thread::Current());
627 // Note that we don't need to lock `lock_` here, the compiler calling
628 // this method has already ensured the inline cache will not be deleted.
629 for (size_t in_cache = 0, in_array = 0;
630 in_cache < InlineCache::kIndividualCacheSize;
631 ++in_cache) {
632 mirror::Class* object = ic.classes_[in_cache].Read();
633 if (object != nullptr) {
634 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000635 }
636 }
637}
638
David Srbeckye36e7f22018-11-14 14:21:23 +0000639static void ClearMethodCounter(ArtMethod* method, bool was_warm)
640 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf044c222017-05-31 15:27:54 -0700641 if (was_warm) {
Vladimir Markoc945e0d2018-07-18 17:26:45 +0100642 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700643 }
644 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
645 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100646 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
647 // the warmup threshold is 1.
648 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
649 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700650}
651
Alex Light33b7b5d2018-08-07 19:13:51 +0000652void JitCodeCache::WaitForPotentialCollectionToCompleteRunnable(Thread* self) {
653 while (collection_in_progress_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100654 Locks::jit_lock_->Unlock(self);
Alex Light33b7b5d2018-08-07 19:13:51 +0000655 {
656 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100657 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000658 WaitForPotentialCollectionToComplete(self);
659 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100660 Locks::jit_lock_->Lock(self);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100661 }
662}
663
David Srbeckyadb66f92019-10-10 12:59:43 +0000664bool JitCodeCache::Commit(Thread* self,
665 JitMemoryRegion* region,
666 ArtMethod* method,
667 ArrayRef<const uint8_t> reserved_code,
668 ArrayRef<const uint8_t> code,
669 ArrayRef<const uint8_t> reserved_data,
670 const std::vector<Handle<mirror::Object>>& roots,
671 ArrayRef<const uint8_t> stack_map,
672 bool osr,
673 bool has_should_deoptimize_flag,
674 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000675 DCHECK(!method->IsNative() || !osr);
Alex Light33b7b5d2018-08-07 19:13:51 +0000676
677 if (!method->IsNative()) {
678 // We need to do this before grabbing the lock_ because it needs to be able to see the string
679 // InternTable. Native methods do not have roots.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000680 DCheckRootsAreValid(roots, IsSharedRegion(*region));
Alex Light33b7b5d2018-08-07 19:13:51 +0000681 }
682
David Srbeckyadb66f92019-10-10 12:59:43 +0000683 const uint8_t* roots_data = reserved_data.data();
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100684 size_t root_table_size = ComputeRootTableSize(roots.size());
David Srbecky87fb0322019-08-20 10:34:02 +0100685 const uint8_t* stack_map_data = roots_data + root_table_size;
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100686
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100687 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000688 // We need to make sure that there will be no jit-gcs going on and wait for any ongoing one to
689 // finish.
690 WaitForPotentialCollectionToCompleteRunnable(self);
David Srbeckyadb66f92019-10-10 12:59:43 +0000691 const uint8_t* code_ptr = region->CommitCode(
692 reserved_code, code, stack_map_data, has_should_deoptimize_flag);
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100693 if (code_ptr == nullptr) {
David Srbeckyadb66f92019-10-10 12:59:43 +0000694 return false;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100695 }
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100696 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
697
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100698 // Commit roots and stack maps before updating the entry point.
David Srbeckyadb66f92019-10-10 12:59:43 +0000699 if (!region->CommitData(reserved_data, roots, stack_map)) {
700 return false;
Orion Hodsonaeb02232019-06-25 14:18:18 +0100701 }
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100702
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100703 number_of_compilations_++;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100704
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000705 // We need to update the entry point in the runnable state for the instrumentation.
706 {
Alex Light33b7b5d2018-08-07 19:13:51 +0000707 // The following needs to be guarded by cha_lock_ also. Otherwise it's possible that the
708 // compiled code is considered invalidated by some class linking, but below we still make the
709 // compiled code valid for the method. Need cha_lock_ for checking all single-implementation
710 // flags and register dependencies.
Mingyao Yang063fc772016-08-02 11:02:54 -0700711 MutexLock cha_mu(self, *Locks::cha_lock_);
712 bool single_impl_still_valid = true;
713 for (ArtMethod* single_impl : cha_single_implementation_list) {
714 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700715 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
716 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700717 single_impl_still_valid = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700718 ClearMethodCounter(method, /*was_warm=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700719 break;
720 }
721 }
722
723 // Discard the code if any single-implementation assumptions are now invalid.
Orion Hodson31492522019-06-18 12:13:49 +0100724 if (UNLIKELY(!single_impl_still_valid)) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700725 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
David Srbeckyadb66f92019-10-10 12:59:43 +0000726 return false;
Mingyao Yang063fc772016-08-02 11:02:54 -0700727 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000728 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800729 << "Should not be using cha on debuggable apps/runs!";
730
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100731 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mingyao Yang063fc772016-08-02 11:02:54 -0700732 for (ArtMethod* single_impl : cha_single_implementation_list) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100733 class_linker->GetClassHierarchyAnalysis()->AddDependency(single_impl, method, method_header);
Mingyao Yang063fc772016-08-02 11:02:54 -0700734 }
735
Vladimir Marko2196c652017-11-30 16:16:07 +0000736 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000737 auto it = jni_stubs_map_.find(JniStubKey(method));
738 DCHECK(it != jni_stubs_map_.end())
739 << "Entry inserted in NotifyCompilationOf() should be alive.";
740 JniStubData* data = &it->second;
741 DCHECK(ContainsElement(data->GetMethods(), method))
742 << "Entry inserted in NotifyCompilationOf() should contain this method.";
743 data->SetCode(code_ptr);
Vladimir Markocce414f2019-10-07 08:51:33 +0100744 data->UpdateEntryPoints(method_header->GetEntryPoint());
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100745 } else {
Nicolas Geoffray32384402019-07-17 20:06:44 +0100746 if (method->IsPreCompiled() && IsSharedRegion(*region)) {
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100747 zygote_map_.Put(code_ptr, method);
748 } else {
749 method_code_map_.Put(code_ptr, method);
750 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000751 if (osr) {
752 number_of_osr_compilations_++;
753 osr_code_map_.Put(method, code_ptr);
Vladimir Marko5115a4d2019-10-17 14:56:47 +0100754 } else if (NeedsClinitCheckBeforeCall(method) &&
755 !method->GetDeclaringClass()->IsVisiblyInitialized()) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100756 // 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 Geoffray32384402019-07-17 20:06:44 +0100759 DCHECK(method->IsPreCompiled());
760 // The shared region can easily be queried. For the private region, we
761 // use a side map.
762 if (!IsSharedRegion(*region)) {
763 saved_compiled_methods_map_.Put(method, code_ptr);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100764 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000765 } else {
766 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
767 method, method_header->GetEntryPoint());
768 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000769 }
Nicolas Geoffrayde3e51d2019-11-28 16:29:55 +0000770 if (collection_in_progress_) {
771 // We need to update the live bitmap if there is a GC to ensure it sees this new
772 // code.
773 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
774 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000775 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100776 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700777 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000778 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
779 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
780 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700781 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
782 method_header->GetCodeSize());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000783 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100784
David Srbeckyadb66f92019-10-10 12:59:43 +0000785 return true;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100786}
787
788size_t JitCodeCache::CodeCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100789 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000790 return CodeCacheSizeLocked();
791}
792
Orion Hodsoneced6922017-06-01 10:54:28 +0100793bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000794 // This function is used only for testing and only with non-native methods.
795 CHECK(!method->IsNative());
796
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100797 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +0100798
Vladimir Marko2196c652017-11-30 16:16:07 +0000799 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
800 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +0100801
802 if (!in_cache) {
803 return false;
804 }
805
David Srbeckye36e7f22018-11-14 14:21:23 +0000806 method->SetCounter(0);
Orion Hodsoneced6922017-06-01 10:54:28 +0100807 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
808 method, GetQuickToInterpreterBridge());
809 VLOG(jit)
810 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
811 << ArtMethod::PrettyMethod(method) << "@" << method
812 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
813 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
814 return true;
815}
816
Vladimir Marko2196c652017-11-30 16:16:07 +0000817bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
818 if (LIKELY(!method->IsNative())) {
819 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
820 if (info != nullptr) {
821 RemoveElement(profiling_infos_, info);
822 }
823 method->SetProfilingInfo(nullptr);
824 }
825
826 bool in_cache = false;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100827 ScopedCodeCacheWrite ccw(private_region_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000828 if (UNLIKELY(method->IsNative())) {
829 auto it = jni_stubs_map_.find(JniStubKey(method));
830 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
831 in_cache = true;
832 if (it->second.GetMethods().empty()) {
833 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100834 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +0000835 }
836 jni_stubs_map_.erase(it);
837 } else {
838 it->first.UpdateShorty(it->second.GetMethods().front());
839 }
840 }
841 } else {
842 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
843 if (it->second == method) {
844 in_cache = true;
845 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100846 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +0000847 }
848 it = method_code_map_.erase(it);
849 } else {
850 ++it;
851 }
852 }
853
854 auto osr_it = osr_code_map_.find(method);
855 if (osr_it != osr_code_map_.end()) {
856 osr_code_map_.erase(osr_it);
857 }
858 }
859
860 return in_cache;
861}
862
Alex Lightdba61482016-12-21 08:20:29 -0800863// This notifies the code cache that the given method has been redefined and that it should remove
864// any cached information it has on the method. All threads must be suspended before calling this
865// method. The compiled code for the method (if there is any) must not be in any threads call stack.
866void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100867 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700868 RemoveMethodLocked(method, /* release_memory= */ true);
Alex Lightdba61482016-12-21 08:20:29 -0800869}
870
871// This invalidates old_method. Once this function returns one can no longer use old_method to
872// execute code unless it is fixed up. This fixup will happen later in the process of installing a
873// class redefinition.
874// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
875// shouldn't be used since it is no longer logically in the jit code cache.
876// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
877void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100878 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +0000879 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000880 // Update methods in jni_stubs_map_.
881 for (auto& entry : jni_stubs_map_) {
882 JniStubData& data = entry.second;
883 data.MoveObsoleteMethod(old_method, new_method);
884 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000885 return;
886 }
Alex Lightdba61482016-12-21 08:20:29 -0800887 // Update ProfilingInfo to the new one and remove it from the old_method.
888 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
889 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
890 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
891 old_method->SetProfilingInfo(nullptr);
892 // Since the JIT should be paused and all threads suspended by the time this is called these
893 // checks should always pass.
894 DCHECK(!info->IsInUseByCompiler());
895 new_method->SetProfilingInfo(info);
Alex Light2d441b12018-06-08 15:33:21 -0700896 // Get rid of the old saved entrypoint if it is there.
897 info->SetSavedEntryPoint(nullptr);
Alex Lightdba61482016-12-21 08:20:29 -0800898 info->method_ = new_method;
899 }
900 // Update method_code_map_ to point to the new method.
901 for (auto& it : method_code_map_) {
902 if (it.second == old_method) {
903 it.second = new_method;
904 }
905 }
906 // Update osr_code_map_ to point to the new method.
907 auto code_map = osr_code_map_.find(old_method);
908 if (code_map != osr_code_map_.end()) {
909 osr_code_map_.Put(new_method, code_map->second);
910 osr_code_map_.erase(old_method);
911 }
912}
913
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000914void JitCodeCache::ClearEntryPointsInZygoteExecSpace() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100915 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayaf213cc2019-07-01 10:50:55 +0100916 for (const auto& it : method_code_map_) {
917 ArtMethod* method = it.second;
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000918 if (IsInZygoteExecSpace(method->GetEntryPointFromQuickCompiledCode())) {
919 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
920 }
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000921 }
922}
923
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000924size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +0100925 return GetCurrentRegion()->GetUsedMemoryForCode();
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100926}
927
928size_t JitCodeCache::DataCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100929 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000930 return DataCacheSizeLocked();
931}
932
933size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +0100934 return GetCurrentRegion()->GetUsedMemoryForData();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800935}
936
David Srbeckyadb66f92019-10-10 12:59:43 +0000937bool JitCodeCache::Reserve(Thread* self,
938 JitMemoryRegion* region,
939 size_t code_size,
940 size_t stack_map_size,
941 size_t number_of_roots,
942 ArtMethod* method,
943 /*out*/ArrayRef<const uint8_t>* reserved_code,
944 /*out*/ArrayRef<const uint8_t>* reserved_data) {
945 code_size = OatQuickMethodHeader::InstructionAlignedSize() + code_size;
946 size_t data_size = RoundUp(ComputeRootTableSize(number_of_roots) + stack_map_size, sizeof(void*));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000947
David Srbeckyadb66f92019-10-10 12:59:43 +0000948 const uint8_t* code;
949 const uint8_t* data;
950 // We might need to try the allocation twice (with GC in between to free up memory).
951 for (int i = 0; i < 2; i++) {
952 {
953 ScopedThreadSuspension sts(self, kSuspended);
954 MutexLock mu(self, *Locks::jit_lock_);
955 WaitForPotentialCollectionToComplete(self);
956 ScopedCodeCacheWrite ccw(*region);
957 code = region->AllocateCode(code_size);
958 data = region->AllocateData(data_size);
959 }
960 if (code == nullptr || data == nullptr) {
961 Free(self, region, code, data);
962 if (i == 0) {
963 GarbageCollectCache(self);
964 continue; // Retry after GC.
965 } else {
966 return false; // Fail.
967 }
968 }
969 break; // Success.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100970 }
David Srbeckyadb66f92019-10-10 12:59:43 +0000971 *reserved_code = ArrayRef<const uint8_t>(code, code_size);
972 *reserved_data = ArrayRef<const uint8_t>(data, data_size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100973
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100974 MutexLock mu(self, *Locks::jit_lock_);
David Srbeckyadb66f92019-10-10 12:59:43 +0000975 histogram_code_memory_use_.AddValue(code_size);
976 if (code_size > kCodeSizeLogThreshold) {
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000977 LOG(INFO) << "JIT allocated "
David Srbeckyadb66f92019-10-10 12:59:43 +0000978 << PrettySize(code_size)
979 << " for compiled code of "
980 << ArtMethod::PrettyMethod(method);
981 }
982 histogram_stack_map_memory_use_.AddValue(data_size);
983 if (data_size > kStackMapSizeLogThreshold) {
984 LOG(INFO) << "JIT allocated "
985 << PrettySize(data_size)
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000986 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700987 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800988 }
David Srbeckyadb66f92019-10-10 12:59:43 +0000989 return true;
990}
991
992void JitCodeCache::Free(Thread* self,
993 JitMemoryRegion* region,
994 const uint8_t* code,
995 const uint8_t* data) {
996 MutexLock mu(self, *Locks::jit_lock_);
997 ScopedCodeCacheWrite ccw(*region);
998 if (code != nullptr) {
999 region->FreeCode(code);
1000 }
1001 if (data != nullptr) {
1002 region->FreeData(data);
1003 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001004}
1005
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001006class MarkCodeClosure final : public Closure {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001007 public:
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001008 MarkCodeClosure(JitCodeCache* code_cache, CodeCacheBitmap* bitmap, Barrier* barrier)
1009 : code_cache_(code_cache), bitmap_(bitmap), barrier_(barrier) {}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001010
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001011 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001012 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001013 DCHECK(thread == Thread::Current() || thread->IsSuspended());
Andreas Gampec7d878d2018-11-19 18:42:06 +00001014 StackVisitor::WalkStack(
1015 [&](const art::StackVisitor* stack_visitor) {
1016 const OatQuickMethodHeader* method_header =
1017 stack_visitor->GetCurrentOatQuickMethodHeader();
1018 if (method_header == nullptr) {
1019 return true;
1020 }
1021 const void* code = method_header->GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001022 if (code_cache_->ContainsPc(code) && !code_cache_->IsInZygoteExecSpace(code)) {
Andreas Gampec7d878d2018-11-19 18:42:06 +00001023 // Use the atomic set version, as multiple threads are executing this code.
1024 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1025 }
1026 return true;
1027 },
1028 thread,
1029 /* context= */ nullptr,
1030 art::StackVisitor::StackWalkKind::kSkipInlinedFrames);
1031
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001032 if (kIsDebugBuild) {
1033 // The stack walking code queries the side instrumentation stack if it
1034 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1035 // must have been seen. We sanity check this below.
1036 for (const instrumentation::InstrumentationStackFrame& frame
1037 : *thread->GetInstrumentationStack()) {
1038 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1039 // its stack frame, it is not the method owning return_pc_. We just pass null to
1040 // LookupMethodHeader: the method is only checked against in debug builds.
1041 OatQuickMethodHeader* method_header =
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001042 code_cache_->LookupMethodHeader(frame.return_pc_, /* method= */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001043 if (method_header != nullptr) {
1044 const void* code = method_header->GetCode();
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001045 CHECK(bitmap_->Test(FromCodeToAllocation(code)));
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001046 }
1047 }
1048 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001049 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001050 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001051
1052 private:
1053 JitCodeCache* const code_cache_;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001054 CodeCacheBitmap* const bitmap_;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001055 Barrier* const barrier_;
1056};
1057
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001058void JitCodeCache::NotifyCollectionDone(Thread* self) {
1059 collection_in_progress_ = false;
1060 lock_cond_.Broadcast(self);
1061}
1062
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001063void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1064 Barrier barrier(0);
1065 size_t threads_running_checkpoint = 0;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001066 MarkCodeClosure closure(this, GetLiveBitmap(), &barrier);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001067 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1068 // Now that we have run our checkpoint, move to a suspended state and wait
1069 // for other threads to run the checkpoint.
1070 ScopedThreadSuspension sts(self, kSuspended);
1071 if (threads_running_checkpoint != 0) {
1072 barrier.Increment(self, threads_running_checkpoint);
1073 }
1074}
1075
Nicolas Geoffray35122442016-03-02 12:05:30 +00001076bool JitCodeCache::ShouldDoFullCollection() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001077 if (private_region_.GetCurrentCapacity() == private_region_.GetMaxCapacity()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001078 // Always do a full collection when the code cache is full.
1079 return true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001080 } else if (private_region_.GetCurrentCapacity() < kReservedCapacity) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001081 // Always do partial collection when the code cache size is below the reserved
1082 // capacity.
1083 return false;
1084 } else if (last_collection_increased_code_cache_) {
1085 // This time do a full collection.
1086 return true;
1087 } else {
1088 // This time do a partial collection.
1089 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001090 }
1091}
1092
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001093void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001094 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001095 // Wait for an existing collection, or let everyone know we are starting one.
1096 {
1097 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001098 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001099 if (!garbage_collect_code_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001100 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001101 return;
1102 } else if (WaitForPotentialCollectionToComplete(self)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001103 return;
1104 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001105 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001106 live_bitmap_.reset(CodeCacheBitmap::Create(
1107 "code-cache-bitmap",
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001108 reinterpret_cast<uintptr_t>(private_region_.GetExecPages()->Begin()),
1109 reinterpret_cast<uintptr_t>(
1110 private_region_.GetExecPages()->Begin() + private_region_.GetCurrentCapacity() / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001111 collection_in_progress_ = true;
1112 }
1113 }
1114
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001115 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001116 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001117 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001118
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001119 bool do_full_collection = false;
1120 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001121 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001122 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001123 }
1124
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001125 VLOG(jit) << "Do "
1126 << (do_full_collection ? "full" : "partial")
1127 << " code cache collection, code="
1128 << PrettySize(CodeCacheSize())
1129 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001130
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001131 DoCollection(self, /* collect_profiling_info= */ do_full_collection);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001132
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001133 VLOG(jit) << "After code cache collection, code="
1134 << PrettySize(CodeCacheSize())
1135 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001136
1137 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001138 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001139
1140 // Increase the code cache only when we do partial collections.
1141 // TODO: base this strategy on how full the code cache is?
1142 if (do_full_collection) {
1143 last_collection_increased_code_cache_ = false;
1144 } else {
1145 last_collection_increased_code_cache_ = true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001146 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001147 }
1148
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001149 bool next_collection_will_be_full = ShouldDoFullCollection();
1150
1151 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001152 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001153 // Save the entry point of methods we have compiled, and update the entry
1154 // point of those methods to the interpreter. If the method is invoked, the
1155 // interpreter will update its entry point to the compiled code and call it.
1156 for (ProfilingInfo* info : profiling_infos_) {
1157 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001158 if (!IsInZygoteDataSpace(info) && ContainsPc(entry_point)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001159 info->SetSavedEntryPoint(entry_point);
Vladimir Marko2196c652017-11-30 16:16:07 +00001160 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001161 // class of the method. We may be concurrently running a GC which makes accessing
1162 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1163 // checked that the current entry point is JIT compiled code.
1164 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001165 }
1166 }
1167
Vladimir Marko2196c652017-11-30 16:16:07 +00001168 // Change entry points of native methods back to the GenericJNI entrypoint.
1169 for (const auto& entry : jni_stubs_map_) {
1170 const JniStubData& data = entry.second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001171 if (!data.IsCompiled() || IsInZygoteExecSpace(data.GetCode())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001172 continue;
1173 }
1174 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1175 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1176 const OatQuickMethodHeader* method_header =
1177 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1178 for (ArtMethod* method : data.GetMethods()) {
1179 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1180 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1181 method->SetCounter(new_counter);
1182 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1183 }
1184 }
1185 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001186 }
1187 live_bitmap_.reset(nullptr);
1188 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001189 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001190 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001191 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001192}
1193
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001194void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001195 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001196 std::unordered_set<OatQuickMethodHeader*> method_headers;
1197 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001198 MutexLock mu(self, *Locks::jit_lock_);
Mingyao Yang063fc772016-08-02 11:02:54 -07001199 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001200 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1201 JniStubData* data = &it->second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001202 if (IsInZygoteExecSpace(data->GetCode()) ||
1203 !data->IsCompiled() ||
1204 GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001205 ++it;
1206 } else {
1207 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1208 it = jni_stubs_map_.erase(it);
1209 }
1210 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001211 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1212 const void* code_ptr = it->first;
1213 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001214 if (IsInZygoteExecSpace(code_ptr) || GetLiveBitmap()->Test(allocation)) {
Mingyao Yang063fc772016-08-02 11:02:54 -07001215 ++it;
1216 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001217 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1218 method_headers.insert(header);
Mingyao Yang063fc772016-08-02 11:02:54 -07001219 it = method_code_map_.erase(it);
1220 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001221 }
1222 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001223 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001224}
1225
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001226bool JitCodeCache::GetGarbageCollectCode() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001227 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001228 return garbage_collect_code_;
1229}
1230
1231void JitCodeCache::SetGarbageCollectCode(bool value) {
1232 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001233 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001234 if (garbage_collect_code_ != value) {
1235 if (garbage_collect_code_) {
1236 // When dynamically disabling the garbage collection, we neee
1237 // to make sure that a potential current collection is finished, and also
1238 // clear the saved entry point in profiling infos to avoid dangling pointers.
1239 WaitForPotentialCollectionToComplete(self);
1240 for (ProfilingInfo* info : profiling_infos_) {
1241 info->SetSavedEntryPoint(nullptr);
1242 }
1243 }
1244 // Update the flag while holding the lock to ensure no thread will try to GC.
1245 garbage_collect_code_ = value;
1246 }
1247}
1248
Nicolas Geoffray35122442016-03-02 12:05:30 +00001249void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001250 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001251 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001252 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001253 if (collect_profiling_info) {
1254 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1255 // Also remove the saved entry point from the ProfilingInfo objects.
1256 for (ProfilingInfo* info : profiling_infos_) {
1257 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001258 if (!ContainsPc(ptr) && !info->IsInUseByCompiler() && !IsInZygoteDataSpace(info)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001259 info->GetMethod()->SetProfilingInfo(nullptr);
1260 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001261
1262 if (info->GetSavedEntryPoint() != nullptr) {
1263 info->SetSavedEntryPoint(nullptr);
1264 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001265 // give it a chance to be hot again.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001266 ClearMethodCounter(info->GetMethod(), /*was_warm=*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001267 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001268 }
1269 } else if (kIsDebugBuild) {
1270 // Sanity check that the profiling infos do not have a dangling entry point.
1271 for (ProfilingInfo* info : profiling_infos_) {
David Srbecky605a5fe2019-04-24 14:05:21 +01001272 DCHECK(!Runtime::Current()->IsZygote());
1273 const void* entry_point = info->GetSavedEntryPoint();
1274 DCHECK(entry_point == nullptr || IsInZygoteExecSpace(entry_point));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001275 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001276 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001277
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001278 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1279 // an entry point is either:
1280 // - an osr compiled code, that will be removed if not in a thread call stack.
1281 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001282 for (const auto& entry : jni_stubs_map_) {
1283 const JniStubData& data = entry.second;
1284 const void* code_ptr = data.GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001285 if (IsInZygoteExecSpace(code_ptr)) {
1286 continue;
1287 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001288 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1289 for (ArtMethod* method : data.GetMethods()) {
1290 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1291 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1292 break;
1293 }
1294 }
1295 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001296 for (const auto& it : method_code_map_) {
1297 ArtMethod* method = it.second;
1298 const void* code_ptr = it.first;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001299 if (IsInZygoteExecSpace(code_ptr)) {
1300 continue;
1301 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001302 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1303 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1304 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1305 }
1306 }
1307
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001308 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001309 // on thread stacks).
1310 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001311 }
1312
1313 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001314 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001315
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001316 // At this point, mutator threads are still running, and entrypoints of methods can
1317 // change. We do know they cannot change to a code cache entry that is not marked,
1318 // therefore we can safely remove those entries.
1319 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001320
Nicolas Geoffray35122442016-03-02 12:05:30 +00001321 if (collect_profiling_info) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001322 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001323 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001324 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001325 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001326 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001327 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1328 // that the compiled code would not get revived. As mutator threads run concurrently,
1329 // they may have revived the compiled code, and now we are in the situation where
1330 // a method has compiled code but no ProfilingInfo.
1331 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1332 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001333 if (ContainsPc(ptr) &&
1334 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001335 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001336 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001337 // No need for this ProfilingInfo object anymore.
David Srbecky87fb0322019-08-20 10:34:02 +01001338 private_region_.FreeWritableData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001339 return true;
1340 }
1341 return false;
1342 });
1343 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001344 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001345}
1346
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001347OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001348 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1349 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001350 // On Thumb-2, the pc is offset by one.
1351 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001352 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001353 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1354 return nullptr;
1355 }
1356
Vladimir Marko2196c652017-11-30 16:16:07 +00001357 if (!kIsDebugBuild) {
1358 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1359 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001360 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001361
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001362 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001363 OatQuickMethodHeader* method_header = nullptr;
1364 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1365 if (method != nullptr && UNLIKELY(method->IsNative())) {
1366 auto it = jni_stubs_map_.find(JniStubKey(method));
1367 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1368 return nullptr;
1369 }
1370 const void* code_ptr = it->second.GetCode();
1371 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1372 if (!method_header->Contains(pc)) {
1373 return nullptr;
1374 }
1375 } else {
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001376 if (shared_region_.IsInExecSpace(reinterpret_cast<const void*>(pc))) {
1377 const void* code_ptr = zygote_map_.GetCodeFor(method, pc);
1378 if (code_ptr != nullptr) {
1379 return OatQuickMethodHeader::FromCodePointer(code_ptr);
1380 }
1381 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001382 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1383 if (it != method_code_map_.begin()) {
1384 --it;
1385 const void* code_ptr = it->first;
1386 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1387 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1388 found_method = it->second;
1389 }
1390 }
1391 if (method_header == nullptr && method == nullptr) {
1392 // Scan all compiled JNI stubs as well. This slow search is used only
1393 // for checks in debug build, for release builds the `method` is not null.
1394 for (auto&& entry : jni_stubs_map_) {
1395 const JniStubData& data = entry.second;
1396 if (data.IsCompiled() &&
1397 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1398 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1399 }
1400 }
1401 }
1402 if (method_header == nullptr) {
1403 return nullptr;
1404 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001405 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001406
1407 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Vladimir Markoeab02482019-05-09 10:28:17 +01001408 DCHECK_EQ(found_method, method)
1409 << ArtMethod::PrettyMethod(method) << " "
1410 << ArtMethod::PrettyMethod(found_method) << " "
David Sehr709b0702016-10-13 09:12:37 -07001411 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001412 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001413 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001414}
1415
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001416OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001417 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001418 auto it = osr_code_map_.find(method);
1419 if (it == osr_code_map_.end()) {
1420 return nullptr;
1421 }
1422 return OatQuickMethodHeader::FromCodePointer(it->second);
1423}
1424
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001425ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1426 ArtMethod* method,
1427 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001428 bool retry_allocation)
1429 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1430 NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001431 DCHECK(CanAllocateProfilingInfo());
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001432 ProfilingInfo* info = nullptr;
1433 if (!retry_allocation) {
1434 // If we are allocating for the interpreter, just try to lock, to avoid
1435 // lock contention with the JIT.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001436 if (Locks::jit_lock_->ExclusiveTryLock(self)) {
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001437 info = AddProfilingInfoInternal(self, method, entries);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001438 Locks::jit_lock_->ExclusiveUnlock(self);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001439 }
1440 } else {
1441 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001442 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001443 info = AddProfilingInfoInternal(self, method, entries);
1444 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001445
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001446 if (info == nullptr) {
1447 GarbageCollectCache(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001448 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001449 info = AddProfilingInfoInternal(self, method, entries);
1450 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001451 }
1452 return info;
1453}
1454
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001455ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001456 ArtMethod* method,
1457 const std::vector<uint32_t>& entries) {
1458 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001459 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001460 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001461
1462 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001463 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001464 if (info != nullptr) {
1465 return info;
1466 }
1467
David Srbecky87fb0322019-08-20 10:34:02 +01001468 const uint8_t* data = private_region_.AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001469 if (data == nullptr) {
1470 return nullptr;
1471 }
David Srbecky87fb0322019-08-20 10:34:02 +01001472 uint8_t* writable_data = private_region_.GetWritableDataAddress(data);
1473 info = new (writable_data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001474
1475 // Make sure other threads see the data in the profiling info object before the
1476 // store in the ArtMethod's ProfilingInfo pointer.
Orion Hodson27b96762018-03-13 16:06:57 +00001477 std::atomic_thread_fence(std::memory_order_release);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001478
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001479 method->SetProfilingInfo(info);
1480 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001481 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001482 return info;
1483}
1484
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001485void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001486 return shared_region_.OwnsSpace(mspace)
1487 ? shared_region_.MoreCore(mspace, increment)
1488 : private_region_.MoreCore(mspace, increment);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001489}
1490
Calin Juravle99629622016-04-19 16:33:46 +01001491void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001492 std::vector<ProfileMethodInfo>& methods) {
Nicolas Geoffray1afdfe62018-11-21 09:38:10 +00001493 Thread* self = Thread::Current();
1494 WaitUntilInlineCacheAccessible(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001495 MutexLock mu(self, *Locks::jit_lock_);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001496 ScopedTrace trace(__FUNCTION__);
Calin Juravlea39fd982017-05-18 10:15:52 -07001497 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001498 for (const ProfilingInfo* info : profiling_infos_) {
1499 ArtMethod* method = info->GetMethod();
1500 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001501 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1502 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001503 // Skip dex files which are not profiled.
1504 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001505 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001506 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001507
1508 // If the method didn't reach the compilation threshold don't save the inline caches.
1509 // They might be incomplete and cause unnecessary deoptimizations.
1510 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1511 if (method->GetCounter() < jit_compile_threshold) {
1512 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001513 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001514 continue;
1515 }
1516
Calin Juravle940eb0c2017-01-30 19:30:44 -08001517 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001518 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001519 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001520 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001521 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001522 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1523 mirror::Class* cls = cache.classes_[k].Read();
1524 if (cls == nullptr) {
1525 break;
1526 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001527
Calin Juravle13439f02017-02-21 01:17:21 -08001528 // Check if the receiver is in the boot class path or if it's in the
1529 // same class loader as the caller. If not, skip it, as there is not
1530 // much we can do during AOT.
1531 if (!cls->IsBootStrapClassLoaded() &&
1532 caller->GetClassLoader() != cls->GetClassLoader()) {
1533 is_missing_types = true;
1534 continue;
1535 }
1536
Calin Juravle4ca70a32017-02-21 16:22:24 -08001537 const DexFile* class_dex_file = nullptr;
1538 dex::TypeIndex type_index;
1539
1540 if (cls->GetDexCache() == nullptr) {
1541 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001542 // Make a best effort to find the type index in the method's dex file.
1543 // We could search all open dex files but that might turn expensive
1544 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001545 class_dex_file = dex_file;
1546 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1547 } else {
1548 class_dex_file = &(cls->GetDexFile());
1549 type_index = cls->GetDexTypeIndex();
1550 }
1551 if (!type_index.IsValid()) {
1552 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001553 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001554 continue;
1555 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001556 if (ContainsElement(dex_base_locations,
1557 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001558 // Only consider classes from the same apk (including multidex).
1559 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001560 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001561 } else {
1562 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001563 }
1564 }
1565 if (!profile_classes.empty()) {
1566 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001567 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001568 }
1569 }
1570 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001571 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001572 }
1573}
1574
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001575bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001576 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001577 return osr_code_map_.find(method) != osr_code_map_.end();
1578}
1579
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001580bool JitCodeCache::NotifyCompilationOf(ArtMethod* method,
1581 Thread* self,
1582 bool osr,
1583 bool prejit,
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001584 bool baseline,
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001585 JitMemoryRegion* region) {
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001586 const void* existing_entry_point = method->GetEntryPointFromQuickCompiledCode();
1587 if (!osr && ContainsPc(existing_entry_point)) {
1588 OatQuickMethodHeader* method_header =
1589 OatQuickMethodHeader::FromEntryPoint(existing_entry_point);
1590 if (CodeInfo::IsBaseline(method_header->GetOptimizedCodeInfoPtr()) == baseline) {
1591 VLOG(jit) << "Not compiling "
1592 << method->PrettyMethod()
1593 << " because it has already been compiled"
1594 << " baseline=" << std::boolalpha << baseline;
1595 return false;
1596 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001597 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001598
Vladimir Marko5115a4d2019-10-17 14:56:47 +01001599 if (NeedsClinitCheckBeforeCall(method) && !prejit) {
1600 // We do not need a synchronization barrier for checking the visibly initialized status
1601 // or checking the initialized status just for requesting visible initialization.
1602 ClassStatus status = method->GetDeclaringClass()
1603 ->GetStatus<kDefaultVerifyFlags, /*kWithSynchronizationBarrier=*/ false>();
1604 if (status != ClassStatus::kVisiblyInitialized) {
1605 // Unless we're pre-jitting, we currently don't save the JIT compiled code if we cannot
1606 // update the entrypoint due to needing an initialization check.
1607 if (status == ClassStatus::kInitialized) {
1608 // Request visible initialization but do not block to allow compiling other methods.
1609 // Hopefully, this will complete by the time the method becomes hot again.
1610 Runtime::Current()->GetClassLinker()->MakeInitializedClassesVisiblyInitialized(
1611 self, /*wait=*/ false);
1612 }
1613 VLOG(jit) << "Not compiling "
1614 << method->PrettyMethod()
1615 << " because it has the resolution stub";
1616 // Give it a new chance to be hot.
1617 ClearMethodCounter(method, /*was_warm=*/ false);
1618 return false;
Vladimir Markocce414f2019-10-07 08:51:33 +01001619 }
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01001620 }
1621
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001622 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001623 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1624 return false;
1625 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001626
Vladimir Marko2196c652017-11-30 16:16:07 +00001627 if (UNLIKELY(method->IsNative())) {
1628 JniStubKey key(method);
1629 auto it = jni_stubs_map_.find(key);
1630 bool new_compilation = false;
1631 if (it == jni_stubs_map_.end()) {
1632 // Create a new entry to mark the stub as being compiled.
1633 it = jni_stubs_map_.Put(key, JniStubData{});
1634 new_compilation = true;
1635 }
1636 JniStubData* data = &it->second;
1637 data->AddMethod(method);
1638 if (data->IsCompiled()) {
1639 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1640 const void* entrypoint = method_header->GetEntryPoint();
1641 // Update also entrypoints of other methods held by the JniStubData.
1642 // We could simply update the entrypoint of `method` but if the last JIT GC has
1643 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1644 // as well change them back as this stub shall not be collected anyway and this
1645 // can avoid a few expensive GenericJNI calls.
Vladimir Markocce414f2019-10-07 08:51:33 +01001646 data->UpdateEntryPoints(entrypoint);
Vladimir Marko2196c652017-11-30 16:16:07 +00001647 if (collection_in_progress_) {
David Srbeckyc45b5892019-04-24 10:32:04 +01001648 if (!IsInZygoteExecSpace(data->GetCode())) {
1649 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1650 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001651 }
1652 }
1653 return new_compilation;
1654 } else {
1655 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1656 if (info == nullptr) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001657 // When prejitting, we don't allocate a profiling info.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001658 if (!prejit && !IsSharedRegion(*region)) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001659 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1660 // Because the counter is not atomic, there are some rare cases where we may not hit the
1661 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
1662 ClearMethodCounter(method, /*was_warm=*/ false);
1663 return false;
1664 }
1665 } else {
1666 if (info->IsMethodBeingCompiled(osr)) {
1667 return false;
1668 }
1669 info->SetIsMethodBeingCompiled(true, osr);
Vladimir Marko2196c652017-11-30 16:16:07 +00001670 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001671 return true;
1672 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001673}
1674
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001675ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001676 MutexLock mu(self, *Locks::jit_lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001677 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001678 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001679 if (!info->IncrementInlineUse()) {
1680 // Overflow of inlining uses, just bail.
1681 return nullptr;
1682 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001683 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001684 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001685}
1686
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001687void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001688 MutexLock mu(self, *Locks::jit_lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001689 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001690 DCHECK(info != nullptr);
1691 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001692}
1693
Vladimir Marko2196c652017-11-30 16:16:07 +00001694void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
1695 DCHECK_EQ(Thread::Current(), self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001696 MutexLock mu(self, *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001697 if (UNLIKELY(method->IsNative())) {
1698 auto it = jni_stubs_map_.find(JniStubKey(method));
1699 DCHECK(it != jni_stubs_map_.end());
1700 JniStubData* data = &it->second;
1701 DCHECK(ContainsElement(data->GetMethods(), method));
1702 if (UNLIKELY(!data->IsCompiled())) {
1703 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1704 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
David Srbeckyadb66f92019-10-10 12:59:43 +00001705 } // else Commit() updated entrypoints of all methods in the JniStubData.
Vladimir Marko2196c652017-11-30 16:16:07 +00001706 } else {
1707 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001708 if (info != nullptr) {
1709 DCHECK(info->IsMethodBeingCompiled(osr));
1710 info->SetIsMethodBeingCompiled(false, osr);
1711 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001712 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001713}
1714
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001715void JitCodeCache::InvalidateAllCompiledCode() {
1716 art::MutexLock mu(Thread::Current(), *Locks::jit_lock_);
1717 size_t cnt = profiling_infos_.size();
1718 size_t osr_size = osr_code_map_.size();
1719 for (ProfilingInfo* pi : profiling_infos_) {
1720 // NB Due to OSR we might run this on some methods multiple times but this should be fine.
1721 ArtMethod* meth = pi->GetMethod();
1722 pi->SetSavedEntryPoint(nullptr);
1723 // We had a ProfilingInfo so we must be warm.
1724 ClearMethodCounter(meth, /*was_warm=*/true);
1725 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1726 if (meth->IsObsolete()) {
1727 linker->SetEntryPointsForObsoleteMethod(meth);
1728 } else {
1729 linker->SetEntryPointsToInterpreter(meth);
1730 }
1731 }
1732 osr_code_map_.clear();
1733 VLOG(jit) << "Invalidated the compiled code of " << (cnt - osr_size) << " methods and "
1734 << osr_size << " OSRs.";
1735}
1736
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001737void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1738 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001739 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07001740 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Alex Light2d441b12018-06-08 15:33:21 -07001741 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001742 if ((profiling_info != nullptr) &&
1743 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
Alex Light2d441b12018-06-08 15:33:21 -07001744 // When instrumentation is set, the actual entrypoint is the one in the profiling info.
1745 method_entrypoint = profiling_info->GetSavedEntryPoint();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001746 // Prevent future uses of the compiled code.
1747 profiling_info->SetSavedEntryPoint(nullptr);
1748 }
1749
Alex Light2d441b12018-06-08 15:33:21 -07001750 // Clear the method counter if we are running jitted code since we might want to jit this again in
1751 // the future.
1752 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001753 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001754 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001755 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1756 method, GetQuickToInterpreterBridge());
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001757 ClearMethodCounter(method, /*was_warm=*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001758 } else {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001759 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001760 auto it = osr_code_map_.find(method);
1761 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1762 // Remove the OSR method, to avoid using it again.
1763 osr_code_map_.erase(it);
1764 }
1765 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001766
Nicolas Geoffray32384402019-07-17 20:06:44 +01001767 // In case the method was pre-compiled, clear that information so we
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001768 // can recompile it ourselves.
Nicolas Geoffray32384402019-07-17 20:06:44 +01001769 if (method->IsPreCompiled()) {
1770 method->ClearPreCompiled();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001771 }
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001772}
1773
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001774void JitCodeCache::Dump(std::ostream& os) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001775 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
David Srbecky44b977d2019-08-09 12:15:32 +01001776 os << "Current JIT code cache size (used / resident): "
1777 << GetCurrentRegion()->GetUsedMemoryForCode() / KB << "KB / "
1778 << GetCurrentRegion()->GetResidentMemoryForCode() / KB << "KB\n"
1779 << "Current JIT data cache size (used / resident): "
1780 << GetCurrentRegion()->GetUsedMemoryForData() / KB << "KB / "
1781 << GetCurrentRegion()->GetResidentMemoryForData() / KB << "KB\n";
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001782 if (!Runtime::Current()->IsZygote()) {
1783 os << "Zygote JIT code cache size (at point of fork): "
David Srbecky44b977d2019-08-09 12:15:32 +01001784 << shared_region_.GetUsedMemoryForCode() / KB << "KB / "
1785 << shared_region_.GetResidentMemoryForCode() / KB << "KB\n"
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001786 << "Zygote JIT data cache size (at point of fork): "
David Srbecky44b977d2019-08-09 12:15:32 +01001787 << shared_region_.GetUsedMemoryForData() / KB << "KB / "
1788 << shared_region_.GetResidentMemoryForData() / KB << "KB\n";
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001789 }
1790 os << "Current JIT mini-debug-info size: " << PrettySize(GetJitMiniDebugInfoMemUsage()) << "\n"
1791 << "Current JIT capacity: " << PrettySize(GetCurrentRegion()->GetCurrentCapacity()) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00001792 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001793 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1794 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1795 << "Total number of JIT compilations for on stack replacement: "
1796 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001797 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001798 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1799 histogram_code_memory_use_.PrintMemoryUse(os);
1800 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001801}
1802
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001803void JitCodeCache::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffrayb08d5db2019-07-17 10:45:36 +01001804 Thread* self = Thread::Current();
1805
1806 // Remove potential tasks that have been inherited from the zygote.
1807 // We do this now and not in Jit::PostForkChildAction, as system server calls
1808 // JitCodeCache::PostForkChildAction first, and then does some code loading
1809 // that may result in new JIT tasks that we want to keep.
1810 ThreadPool* pool = Runtime::Current()->GetJit()->GetThreadPool();
1811 if (pool != nullptr) {
1812 pool->RemoveAllTasks(self);
1813 }
1814
1815 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray88f3fd92019-06-27 16:32:13 +01001816
1817 // Reset potential writable MemMaps inherited from the zygote. We never want
1818 // to write to them.
1819 shared_region_.ResetWritableMappings();
1820
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001821 if (is_zygote || Runtime::Current()->IsSafeMode()) {
1822 // Don't create a private region for a child zygote. Regions are usually map shared
1823 // (to satisfy dual-view), and we don't want children of a child zygote to inherit it.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001824 return;
1825 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001826
1827 // Reset all statistics to be specific to this process.
1828 number_of_compilations_ = 0;
1829 number_of_osr_compilations_ = 0;
1830 number_of_collections_ = 0;
Nicolas Geoffrayf2dcba02019-07-22 13:59:24 +01001831 histogram_stack_map_memory_use_.Reset();
1832 histogram_code_memory_use_.Reset();
1833 histogram_profiling_info_memory_use_.Reset();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001834
1835 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
1836 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001837 std::string error_msg;
Nicolas Geoffray9c54e182019-06-18 10:42:52 +01001838 if (!private_region_.Initialize(initial_capacity,
1839 max_capacity,
1840 /* rwx_memory_allowed= */ !is_system_server,
1841 is_zygote,
1842 &error_msg)) {
1843 LOG(WARNING) << "Could not create private region after zygote fork: " << error_msg;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001844 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001845}
1846
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001847JitMemoryRegion* JitCodeCache::GetCurrentRegion() {
1848 return Runtime::Current()->IsZygote() ? &shared_region_ : &private_region_;
1849}
1850
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001851void ZygoteMap::Initialize(uint32_t number_of_methods) {
1852 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
1853 // Allocate for 40-80% capacity. This will offer OK lookup times, and termination
1854 // cases.
1855 size_t capacity = RoundUpToPowerOfTwo(number_of_methods * 100 / 80);
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001856 const uint8_t* memory = region_->AllocateData(
1857 capacity * sizeof(Entry) + sizeof(ZygoteCompilationState));
1858 if (memory == nullptr) {
1859 LOG(WARNING) << "Could not allocate data for the zygote map";
1860 return;
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001861 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001862 const Entry* data = reinterpret_cast<const Entry*>(memory);
1863 region_->FillData(data, capacity, Entry { nullptr, nullptr });
1864 map_ = ArrayRef(data, capacity);
1865 compilation_state_ = reinterpret_cast<const ZygoteCompilationState*>(
1866 memory + capacity * sizeof(Entry));
1867 region_->WriteData(compilation_state_, ZygoteCompilationState::kInProgress);
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001868}
1869
1870const void* ZygoteMap::GetCodeFor(ArtMethod* method, uintptr_t pc) const {
1871 if (map_.empty()) {
1872 return nullptr;
1873 }
1874
1875 if (method == nullptr) {
1876 // Do a linear search. This should only be used in debug builds.
1877 CHECK(kIsDebugBuild);
1878 for (const Entry& entry : map_) {
1879 const void* code_ptr = entry.code_ptr;
1880 if (code_ptr != nullptr) {
1881 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1882 if (method_header->Contains(pc)) {
1883 return code_ptr;
1884 }
1885 }
1886 }
1887 return nullptr;
1888 }
1889
1890 std::hash<ArtMethod*> hf;
1891 size_t index = hf(method) & (map_.size() - 1u);
1892 size_t original_index = index;
1893 // Loop over the array: we know this loop terminates as we will either
1894 // encounter the given method, or a null entry. Both terminate the loop.
1895 // Note that the zygote may concurrently write new entries to the map. That's OK as the
1896 // map is never resized.
1897 while (true) {
1898 const Entry& entry = map_[index];
1899 if (entry.method == nullptr) {
1900 // Not compiled yet.
1901 return nullptr;
1902 }
1903 if (entry.method == method) {
1904 if (entry.code_ptr == nullptr) {
1905 // This is a race with the zygote which wrote the method, but hasn't written the
1906 // code. Just bail and wait for the next time we need the method.
1907 return nullptr;
1908 }
1909 if (pc != 0 && !OatQuickMethodHeader::FromCodePointer(entry.code_ptr)->Contains(pc)) {
1910 return nullptr;
1911 }
1912 return entry.code_ptr;
1913 }
1914 index = (index + 1) & (map_.size() - 1);
1915 DCHECK_NE(original_index, index);
1916 }
1917}
1918
1919void ZygoteMap::Put(const void* code, ArtMethod* method) {
1920 if (map_.empty()) {
1921 return;
1922 }
1923 CHECK(Runtime::Current()->IsZygote());
1924 std::hash<ArtMethod*> hf;
1925 size_t index = hf(method) & (map_.size() - 1);
1926 size_t original_index = index;
1927 // Because the size of the map is bigger than the number of methods that will
1928 // be added, we are guaranteed to find a free slot in the array, and
1929 // therefore for this loop to terminate.
1930 while (true) {
David Srbecky87fb0322019-08-20 10:34:02 +01001931 const Entry* entry = &map_[index];
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001932 if (entry->method == nullptr) {
1933 // Note that readers can read this memory concurrently, but that's OK as
1934 // we are writing pointers.
1935 region_->WriteData(entry, Entry { method, code });
1936 break;
1937 }
1938 index = (index + 1) & (map_.size() - 1);
1939 DCHECK_NE(original_index, index);
1940 }
1941 DCHECK_EQ(GetCodeFor(method), code);
1942}
1943
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001944} // namespace jit
1945} // namespace art