blob: 2505111058d2fecd2cbc7d0fae8d6c66ece19526 [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>
22#include <android-base/unique_fd.h>
Orion Hodson1d3fd082018-09-28 09:38:35 +010023
Andreas Gampe5629d2d2017-05-15 16:28:13 -070024#include "arch/context.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070025#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070026#include "base/enums.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070027#include "base/histogram-inl.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080028#include "base/logging.h" // For VLOG.
Orion Hodson563ada22018-09-04 11:28:31 +010029#include "base/membarrier.h"
Orion Hodson1d3fd082018-09-28 09:38:35 +010030#include "base/memfd.h"
David Sehr79e26072018-04-06 17:58:50 -070031#include "base/mem_map.h"
David Sehrc431b9d2018-03-02 12:01:51 -080032#include "base/quasi_atomic.h"
Calin Juravle66f55232015-12-08 15:09:10 +000033#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080034#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010035#include "base/time_utils.h"
Orion Hodsonf2331362018-07-11 15:14:10 +010036#include "base/utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070037#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000038#include "debugger_interface.h"
David Sehr9e734c72018-01-04 17:56:19 -080039#include "dex/dex_file_loader.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070040#include "dex/method_reference.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 Geoffray1dad3f62015-10-23 14:59:54 +010050#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080051#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070052#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070053#include "object_callbacks.h"
David Sehr82d046e2018-04-23 08:14:19 -070054#include "profile/profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070055#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070056#include "stack.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000057#include "thread-current-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010058#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080059
Orion Hodson1d3fd082018-09-28 09:38:35 +010060using android::base::unique_fd;
61
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080062namespace art {
63namespace jit {
64
Nicolas Geoffray933330a2016-03-16 14:20:06 +000065static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
66static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
67
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +000068// Data cache will be half of the capacity
69// Code cache will be the other half of the capacity.
70// TODO: Make this variable?
71static constexpr size_t kCodeAndDataCapacityDivider = 2;
72
Orion Hodson1d3fd082018-09-28 09:38:35 +010073static constexpr int kProtR = PROT_READ;
74static constexpr int kProtRW = PROT_READ | PROT_WRITE;
75static constexpr int kProtRWX = PROT_READ | PROT_WRITE | PROT_EXEC;
76static constexpr int kProtRX = PROT_READ | PROT_EXEC;
77
78namespace {
79
80// Translate an address belonging to one memory map into an address in a second. This is useful
81// when there are two virtual memory ranges for the same physical memory range.
82template <typename T>
83T* TranslateAddress(T* src_ptr, const MemMap& src, const MemMap& dst) {
84 CHECK(src.HasAddress(src_ptr));
85 uint8_t* const raw_src_ptr = reinterpret_cast<uint8_t*>(src_ptr);
86 return reinterpret_cast<T*>(raw_src_ptr - src.Begin() + dst.Begin());
87}
88
89} // namespace
90
Vladimir Marko2196c652017-11-30 16:16:07 +000091class JitCodeCache::JniStubKey {
92 public:
93 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
94 : shorty_(method->GetShorty()),
95 is_static_(method->IsStatic()),
96 is_fast_native_(method->IsFastNative()),
97 is_critical_native_(method->IsCriticalNative()),
98 is_synchronized_(method->IsSynchronized()) {
99 DCHECK(!(is_fast_native_ && is_critical_native_));
100 }
101
102 bool operator<(const JniStubKey& rhs) const {
103 if (is_static_ != rhs.is_static_) {
104 return rhs.is_static_;
105 }
106 if (is_synchronized_ != rhs.is_synchronized_) {
107 return rhs.is_synchronized_;
108 }
109 if (is_fast_native_ != rhs.is_fast_native_) {
110 return rhs.is_fast_native_;
111 }
112 if (is_critical_native_ != rhs.is_critical_native_) {
113 return rhs.is_critical_native_;
114 }
115 return strcmp(shorty_, rhs.shorty_) < 0;
116 }
117
118 // Update the shorty to point to another method's shorty. Call this function when removing
119 // the method that references the old shorty from JniCodeData and not removing the entire
120 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
121 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
122 const char* shorty = method->GetShorty();
123 DCHECK_STREQ(shorty_, shorty);
124 shorty_ = shorty;
125 }
126
127 private:
128 // The shorty points to a DexFile data and may need to change
129 // to point to the same shorty in a different DexFile.
130 mutable const char* shorty_;
131
132 const bool is_static_;
133 const bool is_fast_native_;
134 const bool is_critical_native_;
135 const bool is_synchronized_;
136};
137
138class JitCodeCache::JniStubData {
139 public:
140 JniStubData() : code_(nullptr), methods_() {}
141
142 void SetCode(const void* code) {
143 DCHECK(code != nullptr);
144 code_ = code;
145 }
146
147 const void* GetCode() const {
148 return code_;
149 }
150
151 bool IsCompiled() const {
152 return GetCode() != nullptr;
153 }
154
155 void AddMethod(ArtMethod* method) {
156 if (!ContainsElement(methods_, method)) {
157 methods_.push_back(method);
158 }
159 }
160
161 const std::vector<ArtMethod*>& GetMethods() const {
162 return methods_;
163 }
164
165 void RemoveMethodsIn(const LinearAlloc& alloc) {
166 auto kept_end = std::remove_if(
167 methods_.begin(),
168 methods_.end(),
169 [&alloc](ArtMethod* method) { return alloc.ContainsUnsafe(method); });
170 methods_.erase(kept_end, methods_.end());
171 }
172
173 bool RemoveMethod(ArtMethod* method) {
174 auto it = std::find(methods_.begin(), methods_.end(), method);
175 if (it != methods_.end()) {
176 methods_.erase(it);
177 return true;
178 } else {
179 return false;
180 }
181 }
182
183 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
184 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
185 }
186
187 private:
188 const void* code_;
189 std::vector<ArtMethod*> methods_;
190};
191
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000192bool JitCodeCache::InitializeMappings(bool rwx_memory_allowed,
193 bool is_zygote,
194 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800195 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000196
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000197 const size_t capacity = max_capacity_;
198 const size_t data_capacity = capacity / kCodeAndDataCapacityDivider;
199 const size_t exec_capacity = capacity - data_capacity;
Orion Hodson563ada22018-09-04 11:28:31 +0100200
Orion Hodson1d3fd082018-09-28 09:38:35 +0100201 // File descriptor enabling dual-view mapping of code section.
202 unique_fd mem_fd;
203
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000204 // Zygote shouldn't create a shared mapping for JIT, so we cannot use dual view
205 // for it.
206 if (!is_zygote) {
207 // Bionic supports memfd_create, but the call may fail on older kernels.
208 mem_fd = unique_fd(art::memfd_create("/jit-cache", /* flags= */ 0));
209 if (mem_fd.get() < 0) {
210 std::ostringstream oss;
211 oss << "Failed to initialize dual view JIT. memfd_create() error: " << strerror(errno);
212 if (!rwx_memory_allowed) {
213 // Without using RWX page permissions, the JIT can not fallback to single mapping as it
214 // requires tranitioning the code pages to RWX for updates.
215 *error_msg = oss.str();
216 return false;
217 }
218 VLOG(jit) << oss.str();
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100219 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100220 }
221
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000222 if (mem_fd.get() >= 0 && ftruncate(mem_fd, capacity) != 0) {
Orion Hodson1d3fd082018-09-28 09:38:35 +0100223 std::ostringstream oss;
224 oss << "Failed to initialize memory file: " << strerror(errno);
225 *error_msg = oss.str();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000226 return false;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100227 }
228
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000229 std::string data_cache_name = is_zygote ? "zygote-data-code-cache" : "data-code-cache";
230 std::string exec_cache_name = is_zygote ? "zygote-jit-code-cache" : "jit-code-cache";
Calin Juravle016fcbe22018-05-03 19:47:35 -0700231
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800232 std::string error_str;
233 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000234 // Map in low 4gb to simplify accessing root tables for x86_64.
235 // We could do PC-relative addressing to avoid this problem, but that
236 // would require reserving code and data area before submitting, which
237 // means more windows for the code memory to be RWX.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100238 int base_flags;
239 MemMap data_pages;
240 if (mem_fd.get() >= 0) {
241 // Dual view of JIT code cache case. Create an initial mapping of data pages large enough
242 // for data and non-writable view of JIT code pages. We use the memory file descriptor to
243 // enable dual mapping - we'll create a second mapping using the descriptor below. The
244 // mappings will look like:
245 //
246 // VA PA
247 //
248 // +---------------+
249 // | non exec code |\
250 // +---------------+ \
251 // : :\ \
252 // +---------------+.\.+---------------+
253 // | exec code | \| code |
254 // +---------------+...+---------------+
255 // | data | | data |
256 // +---------------+...+---------------+
257 //
258 // In this configuration code updates are written to the non-executable view of the code
259 // cache, and the executable view of the code cache has fixed RX memory protections.
260 //
261 // This memory needs to be mapped shared as the code portions will have two mappings.
262 base_flags = MAP_SHARED;
263 data_pages = MemMap::MapFile(
264 data_capacity + exec_capacity,
265 kProtRW,
266 base_flags,
267 mem_fd,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700268 /* start= */ 0,
269 /* low_4gb= */ true,
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000270 data_cache_name.c_str(),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100271 &error_str);
272 } else {
273 // Single view of JIT code cache case. Create an initial mapping of data pages large enough
274 // for data and JIT code pages. The mappings will look like:
275 //
276 // VA PA
277 //
278 // +---------------+...+---------------+
279 // | exec code | | code |
280 // +---------------+...+---------------+
281 // | data | | data |
282 // +---------------+...+---------------+
283 //
284 // In this configuration code updates are written to the executable view of the code cache,
285 // and the executable view of the code cache transitions RX to RWX for the update and then
286 // back to RX after the update.
287 base_flags = MAP_PRIVATE | MAP_ANON;
288 data_pages = MemMap::MapAnonymous(
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000289 data_cache_name.c_str(),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100290 data_capacity + exec_capacity,
291 kProtRW,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700292 /* low_4gb= */ true,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100293 &error_str);
294 }
295
296 if (!data_pages.IsValid()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800297 std::ostringstream oss;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000298 oss << "Failed to create read write cache: " << error_str << " size=" << capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800299 *error_msg = oss.str();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000300 return false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800301 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100302
Orion Hodson1d3fd082018-09-28 09:38:35 +0100303 MemMap exec_pages;
304 MemMap non_exec_pages;
305 if (exec_capacity > 0) {
306 uint8_t* const divider = data_pages.Begin() + data_capacity;
307 // Set initial permission for executable view to catch any SELinux permission problems early
308 // (for processes that cannot map WX pages). Otherwise, this region does not need to be
309 // executable as there is no code in the cache yet.
310 exec_pages = data_pages.RemapAtEnd(divider,
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000311 exec_cache_name.c_str(),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100312 kProtRX,
313 base_flags | MAP_FIXED,
314 mem_fd.get(),
315 (mem_fd.get() >= 0) ? data_capacity : 0,
316 &error_str);
317 if (!exec_pages.IsValid()) {
318 std::ostringstream oss;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000319 oss << "Failed to create read execute code cache: " << error_str << " size=" << capacity;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100320 *error_msg = oss.str();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000321 return false;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100322 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100323
Orion Hodson1d3fd082018-09-28 09:38:35 +0100324 if (mem_fd.get() >= 0) {
325 // For dual view, create the secondary view of code memory used for updating code. This view
326 // is never executable.
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000327 std::string name = exec_cache_name + "-rw";
Orion Hodson1d3fd082018-09-28 09:38:35 +0100328 non_exec_pages = MemMap::MapFile(exec_capacity,
329 kProtR,
330 base_flags,
331 mem_fd,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700332 /* start= */ data_capacity,
333 /* low_4GB= */ false,
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000334 name.c_str(),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100335 &error_str);
336 if (!non_exec_pages.IsValid()) {
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100337 static const char* kFailedNxView = "Failed to map non-executable view of JIT code cache";
338 if (rwx_memory_allowed) {
339 // Log and continue as single view JIT (requires RWX memory).
340 VLOG(jit) << kFailedNxView;
341 } else {
342 *error_msg = kFailedNxView;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000343 return false;
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100344 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100345 }
346 }
347 } else {
348 // Profiling only. No memory for code required.
David Sehrd1dbb742017-07-17 11:20:38 -0700349 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100350
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000351 data_pages_ = std::move(data_pages);
352 exec_pages_ = std::move(exec_pages);
353 non_exec_pages_ = std::move(non_exec_pages);
354 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800355}
356
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000357JitCodeCache* JitCodeCache::Create(bool used_only_for_profile_data,
358 bool rwx_memory_allowed,
359 bool is_zygote,
360 std::string* error_msg) {
361 // Register for membarrier expedited sync core if JIT will be generating code.
362 if (!used_only_for_profile_data) {
363 if (art::membarrier(art::MembarrierCommand::kRegisterPrivateExpeditedSyncCore) != 0) {
364 // MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE ensures that CPU instruction pipelines are
365 // flushed and it's used when adding code to the JIT. The memory used by the new code may
366 // have just been released and, in theory, the old code could still be in a pipeline.
367 VLOG(jit) << "Kernel does not support membarrier sync-core";
368 }
369 }
370
371 // Check whether the provided max capacity in options is below 1GB.
372 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
373 // We need to have 32 bit offsets from method headers in code cache which point to things
374 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
375 // Ensure we're below 1 GB to be safe.
376 if (max_capacity > 1 * GB) {
377 std::ostringstream oss;
378 oss << "Maxium code cache capacity is limited to 1 GB, "
379 << PrettySize(max_capacity) << " is too big";
380 *error_msg = oss.str();
381 return nullptr;
382 }
383
384 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
385
386 std::unique_ptr<JitCodeCache> jit_code_cache(new JitCodeCache());
387
388 MutexLock mu(Thread::Current(), jit_code_cache->lock_);
389 jit_code_cache->InitializeState(initial_capacity, max_capacity);
390
391 // Zygote should never collect code to share the memory with the children.
392 if (is_zygote) {
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000393 jit_code_cache->garbage_collect_code_ = false;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000394 }
395
396 if (!jit_code_cache->InitializeMappings(rwx_memory_allowed, is_zygote, error_msg)) {
397 return nullptr;
398 }
399
400 jit_code_cache->InitializeSpaces();
401
402 VLOG(jit) << "Created jit code cache: initial capacity="
403 << PrettySize(initial_capacity)
404 << ", maximum capacity="
405 << PrettySize(max_capacity);
406
407 return jit_code_cache.release();
408}
409
410JitCodeCache::JitCodeCache()
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100411 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000412 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100413 collection_in_progress_(false),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000414 last_collection_increased_code_cache_(false),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100415 garbage_collect_code_(true),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000416 used_memory_for_data_(0),
417 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000418 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000419 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000420 number_of_collections_(0),
421 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
422 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000423 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
424 is_weak_access_enabled_(true),
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000425 inline_cache_cond_("Jit inline cache condition variable", lock_),
426 zygote_data_pages_(),
427 zygote_exec_pages_(),
428 zygote_data_mspace_(nullptr),
429 zygote_exec_mspace_(nullptr) {
430}
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100431
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000432void JitCodeCache::InitializeState(size_t initial_capacity, size_t max_capacity) {
433 CHECK_GE(max_capacity, initial_capacity);
434 CHECK(max_capacity <= 1 * GB) << "The max supported size for JIT code cache is 1GB";
435 // Align both capacities to page size, as that's the unit mspaces use.
436 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
437 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100438
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000439 used_memory_for_data_ = 0;
440 used_memory_for_code_ = 0;
441 number_of_compilations_ = 0;
442 number_of_osr_compilations_ = 0;
443 number_of_collections_ = 0;
444
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000445 data_pages_ = MemMap();
446 exec_pages_ = MemMap();
447 non_exec_pages_ = MemMap();
448 initial_capacity_ = initial_capacity;
449 max_capacity_ = max_capacity;
450 current_capacity_ = initial_capacity,
451 data_end_ = initial_capacity / kCodeAndDataCapacityDivider;
452 exec_end_ = initial_capacity - data_end_;
453}
454
455void JitCodeCache::InitializeSpaces() {
Orion Hodson1d3fd082018-09-28 09:38:35 +0100456 // Initialize the data heap
457 data_mspace_ = create_mspace_with_base(data_pages_.Begin(), data_end_, false /*locked*/);
458 CHECK(data_mspace_ != nullptr) << "create_mspace_with_base (data) failed";
459
460 // Initialize the code heap
461 MemMap* code_heap = nullptr;
462 if (non_exec_pages_.IsValid()) {
463 code_heap = &non_exec_pages_;
464 } else if (exec_pages_.IsValid()) {
465 code_heap = &exec_pages_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100466 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100467 if (code_heap != nullptr) {
468 // Make all pages reserved for the code heap writable. The mspace allocator, that manages the
469 // heap, will take and initialize pages in create_mspace_with_base().
470 CheckedCall(mprotect, "create code heap", code_heap->Begin(), code_heap->Size(), kProtRW);
471 exec_mspace_ = create_mspace_with_base(code_heap->Begin(), exec_end_, false /*locked*/);
472 CHECK(exec_mspace_ != nullptr) << "create_mspace_with_base (exec) failed";
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000473 SetFootprintLimit(initial_capacity_);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100474 // Protect pages containing heap metadata. Updates to the code heap toggle write permission to
475 // perform the update and there are no other times write access is required.
476 CheckedCall(mprotect, "protect code heap", code_heap->Begin(), code_heap->Size(), kProtR);
477 } else {
478 exec_mspace_ = nullptr;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000479 SetFootprintLimit(initial_capacity_);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100480 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800481}
482
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000483JitCodeCache::~JitCodeCache() {}
484
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100485bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000486 return exec_pages_.HasAddress(ptr) || zygote_exec_pages_.HasAddress(ptr);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800487}
488
Alex Light2d441b12018-06-08 15:33:21 -0700489bool JitCodeCache::WillExecuteJitCode(ArtMethod* method) {
490 ScopedObjectAccess soa(art::Thread::Current());
491 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
492 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
493 return true;
494 } else if (method->GetEntryPointFromQuickCompiledCode() == GetQuickInstrumentationEntryPoint()) {
495 return FindCompiledCodeForInstrumentation(method) != nullptr;
496 }
497 return false;
498}
499
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000500bool JitCodeCache::ContainsMethod(ArtMethod* method) {
501 MutexLock mu(Thread::Current(), lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000502 if (UNLIKELY(method->IsNative())) {
503 auto it = jni_stubs_map_.find(JniStubKey(method));
504 if (it != jni_stubs_map_.end() &&
505 it->second.IsCompiled() &&
506 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000507 return true;
508 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000509 } else {
510 for (const auto& it : method_code_map_) {
511 if (it.second == method) {
512 return true;
513 }
514 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000515 }
516 return false;
517}
518
Vladimir Marko2196c652017-11-30 16:16:07 +0000519const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
520 DCHECK(method->IsNative());
521 MutexLock mu(Thread::Current(), lock_);
522 auto it = jni_stubs_map_.find(JniStubKey(method));
523 if (it != jni_stubs_map_.end()) {
524 JniStubData& data = it->second;
525 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
526 return data.GetCode();
527 }
528 }
529 return nullptr;
530}
531
Alex Light2d441b12018-06-08 15:33:21 -0700532const void* JitCodeCache::FindCompiledCodeForInstrumentation(ArtMethod* method) {
Alex Light839f53a2018-07-10 15:46:14 -0700533 // If jit-gc is still on we use the SavedEntryPoint field for doing that and so cannot use it to
534 // find the instrumentation entrypoint.
535 if (LIKELY(GetGarbageCollectCode())) {
Alex Light2d441b12018-06-08 15:33:21 -0700536 return nullptr;
537 }
538 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
539 if (info == nullptr) {
540 return nullptr;
541 }
542 // When GC is disabled for trampoline tracing we will use SavedEntrypoint to hold the actual
543 // jit-compiled version of the method. If jit-gc is disabled for other reasons this will just be
544 // nullptr.
545 return info->GetSavedEntryPoint();
546}
547
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100548const void* JitCodeCache::GetZygoteSavedEntryPoint(ArtMethod* method) {
David Srbecky3db3d372019-04-17 18:19:17 +0100549 if (Runtime::Current()->IsUsingApexBootImageLocation() &&
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100550 // Currently only applies to boot classpath
551 method->GetDeclaringClass()->GetClassLoader() == nullptr) {
552 const void* entry_point = nullptr;
553 if (method->IsNative()) {
554 const void* code_ptr = GetJniStubCode(method);
555 if (code_ptr != nullptr) {
556 entry_point = OatQuickMethodHeader::FromCodePointer(code_ptr)->GetEntryPoint();
557 }
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100558 } else {
559 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
560 if (profiling_info != nullptr) {
561 entry_point = profiling_info->GetSavedEntryPoint();
562 }
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100563 }
564 if (Runtime::Current()->IsZygote() || IsInZygoteExecSpace(entry_point)) {
565 return entry_point;
566 }
567 }
568 return nullptr;
569}
570
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800571class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100572 public:
Calin Juravle016fcbe22018-05-03 19:47:35 -0700573 explicit ScopedCodeCacheWrite(const JitCodeCache* const code_cache)
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100574 : ScopedTrace("ScopedCodeCacheWrite"),
Calin Juravle016fcbe22018-05-03 19:47:35 -0700575 code_cache_(code_cache) {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800576 ScopedTrace trace("mprotect all");
Orion Hodson1d3fd082018-09-28 09:38:35 +0100577 const MemMap* const updatable_pages = code_cache_->GetUpdatableCodeMapping();
578 if (updatable_pages != nullptr) {
579 int prot = code_cache_->HasDualCodeMapping() ? kProtRW : kProtRWX;
580 CheckedCall(mprotect, "Cache +W", updatable_pages->Begin(), updatable_pages->Size(), prot);
581 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800582 }
Calin Juravle016fcbe22018-05-03 19:47:35 -0700583
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100584 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800585 ScopedTrace trace("mprotect code");
Orion Hodson1d3fd082018-09-28 09:38:35 +0100586 const MemMap* const updatable_pages = code_cache_->GetUpdatableCodeMapping();
587 if (updatable_pages != nullptr) {
588 int prot = code_cache_->HasDualCodeMapping() ? kProtR : kProtRX;
589 CheckedCall(mprotect, "Cache -W", updatable_pages->Begin(), updatable_pages->Size(), prot);
590 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100591 }
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700592
David Sehrd1dbb742017-07-17 11:20:38 -0700593 private:
Calin Juravle016fcbe22018-05-03 19:47:35 -0700594 const JitCodeCache* const code_cache_;
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100595
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100596 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
597};
598
599uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100600 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000601 uint8_t* stack_map,
602 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100603 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000604 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100605 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000606 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100607 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700608 bool has_should_deoptimize_flag,
609 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100610 uint8_t* result = CommitCodeInternal(self,
611 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000612 stack_map,
613 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100614 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000615 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100616 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000617 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700618 roots,
619 has_should_deoptimize_flag,
620 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100621 if (result == nullptr) {
622 // Retry.
623 GarbageCollectCache(self);
624 result = CommitCodeInternal(self,
625 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000626 stack_map,
627 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100628 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000629 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100630 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000631 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700632 roots,
633 has_should_deoptimize_flag,
634 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100635 }
636 return result;
637}
638
639bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
640 bool in_collection = false;
641 while (collection_in_progress_) {
642 in_collection = true;
643 lock_cond_.Wait(self);
644 }
645 return in_collection;
646}
647
648static uintptr_t FromCodeToAllocation(const void* code) {
649 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
650 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
651}
652
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000653static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
654 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
655}
656
657static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
658 // The length of the table is stored just before the stack map (and therefore at the end of
659 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
660 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
661}
662
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800663static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
664 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
665 // pointer.
666 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
667}
668
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000669static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
670 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
671}
672
Vladimir Markoac3ac682018-09-20 11:01:43 +0100673static void DCheckRootsAreValid(const std::vector<Handle<mirror::Object>>& roots)
Alex Light3e36a9c2018-06-19 09:45:05 -0700674 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
675 if (!kIsDebugBuild) {
676 return;
677 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700678 // Put all roots in `roots_data`.
Vladimir Markoac3ac682018-09-20 11:01:43 +0100679 for (Handle<mirror::Object> object : roots) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700680 // Ensure the string is strongly interned. b/32995596
681 if (object->IsString()) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100682 ObjPtr<mirror::String> str = object->AsString();
Alex Light3e36a9c2018-06-19 09:45:05 -0700683 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
684 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
685 }
686 }
687}
688
689void JitCodeCache::FillRootTable(uint8_t* roots_data,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100690 const std::vector<Handle<mirror::Object>>& roots) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000691 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Vladimir Markoac3ac682018-09-20 11:01:43 +0100692 const uint32_t length = roots.size();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000693 // Put all roots in `roots_data`.
694 for (uint32_t i = 0; i < length; ++i) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100695 ObjPtr<mirror::Object> object = roots[i].Get();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000696 gc_roots[i] = GcRoot<mirror::Object>(object);
697 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000698}
699
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100700static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000701 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
702 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
703 uint32_t roots = GetNumberOfRoots(data);
704 if (number_of_roots != nullptr) {
705 *number_of_roots = roots;
706 }
707 return data - ComputeRootTableSize(roots);
708}
709
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100710// Use a sentinel for marking entries in the JIT table that have been cleared.
711// This helps diagnosing in case the compiled code tries to wrongly access such
712// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700713static mirror::Class* const weak_sentinel =
714 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100715
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000716// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100717static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
718 IsMarkedVisitor* visitor,
719 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000720 REQUIRES_SHARED(Locks::mutator_lock_) {
721 // This does not need a read barrier because this is called by GC.
722 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100723 if (cls != nullptr && cls != weak_sentinel) {
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700724 DCHECK((cls->IsClass<kDefaultVerifyFlags>()));
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000725 // Look at the classloader of the class to know if it has been unloaded.
726 // This does not need a read barrier because this is called by GC.
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000727 ObjPtr<mirror::Object> class_loader =
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000728 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000729 if (class_loader == nullptr || visitor->IsMarked(class_loader.Ptr()) != nullptr) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000730 // The class loader is live, update the entry if the class has moved.
731 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
732 // Note that new_object can be null for CMS and newly allocated objects.
733 if (new_cls != nullptr && new_cls != cls) {
734 *root_ptr = GcRoot<mirror::Class>(new_cls);
735 }
736 } else {
737 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100738 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000739 }
740 }
741}
742
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000743void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
744 MutexLock mu(Thread::Current(), lock_);
745 for (const auto& entry : method_code_map_) {
746 uint32_t number_of_roots = 0;
747 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
748 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
749 for (uint32_t i = 0; i < number_of_roots; ++i) {
750 // This does not need a read barrier because this is called by GC.
751 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100752 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000753 // entry got deleted in a previous sweep.
Vladimir Markod355acf2019-03-21 17:09:40 +0000754 } else if (object->IsString<kDefaultVerifyFlags>()) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000755 mirror::Object* new_object = visitor->IsMarked(object);
756 // We know the string is marked because it's a strongly-interned string that
757 // is always alive. The IsMarked implementation of the CMS collector returns
758 // null for newly allocated objects, but we know those haven't moved. Therefore,
759 // only update the entry if we get a different non-null string.
760 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
761 // out of the weak access/creation pause. b/32167580
762 if (new_object != nullptr && new_object != object) {
763 DCHECK(new_object->IsString());
764 roots[i] = GcRoot<mirror::Object>(new_object);
765 }
766 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100767 ProcessWeakClass(
768 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000769 }
770 }
771 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000772 // Walk over inline caches to clear entries containing unloaded classes.
773 for (ProfilingInfo* info : profiling_infos_) {
774 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
775 InlineCache* cache = &info->cache_[i];
776 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100777 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000778 }
779 }
780 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000781}
782
Orion Hodson607624f2018-05-11 10:10:46 +0100783void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
Nicolas Geoffrayae982f92018-12-08 12:31:10 +0000784 if (IsInZygoteExecSpace(code_ptr)) {
785 // No need to free, this is shared memory.
786 return;
787 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100788 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000789 // Notify native debugger that we are about to remove the code.
790 // It does nothing if we are not using native debugger.
David Srbeckyafc60cd2018-12-05 11:59:31 +0000791 RemoveNativeDebugInfoForJit(Thread::Current(), code_ptr);
Vladimir Marko2196c652017-11-30 16:16:07 +0000792 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
793 FreeData(GetRootTable(code_ptr));
794 } // else this is a JNI stub without any data.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100795
796 uint8_t* code_allocation = reinterpret_cast<uint8_t*>(allocation);
797 if (HasDualCodeMapping()) {
798 code_allocation = TranslateAddress(code_allocation, exec_pages_, non_exec_pages_);
799 }
800
801 FreeCode(code_allocation);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100802}
803
Mingyao Yang063fc772016-08-02 11:02:54 -0700804void JitCodeCache::FreeAllMethodHeaders(
805 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700806 // We need to remove entries in method_headers from CHA dependencies
807 // first since once we do FreeCode() below, the memory can be reused
808 // so it's possible for the same method_header to start representing
809 // different compile code.
810 MutexLock mu(Thread::Current(), lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000811 {
812 MutexLock mu2(Thread::Current(), *Locks::cha_lock_);
813 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
814 ->RemoveDependentsWithMethodHeaders(method_headers);
815 }
816
Calin Juravle016fcbe22018-05-03 19:47:35 -0700817 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700818 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodson607624f2018-05-11 10:10:46 +0100819 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700820 }
821}
822
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100823void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800824 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700825 // We use a set to first collect all method_headers whose code need to be
826 // removed. We need to free the underlying code after we remove CHA dependencies
827 // for entries in this set. And it's more efficient to iterate through
828 // the CHA dependency map just once with an unordered_set.
829 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000830 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700831 MutexLock mu(self, lock_);
832 // We do not check if a code cache GC is in progress, as this method comes
833 // with the classlinker_classes_lock_ held, and suspending ourselves could
834 // lead to a deadlock.
835 {
Calin Juravle016fcbe22018-05-03 19:47:35 -0700836 ScopedCodeCacheWrite scc(this);
Vladimir Marko2196c652017-11-30 16:16:07 +0000837 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
838 it->second.RemoveMethodsIn(alloc);
839 if (it->second.GetMethods().empty()) {
840 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
841 it = jni_stubs_map_.erase(it);
842 } else {
843 it->first.UpdateShorty(it->second.GetMethods().front());
844 ++it;
845 }
846 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700847 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
848 if (alloc.ContainsUnsafe(it->second)) {
849 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
850 it = method_code_map_.erase(it);
851 } else {
852 ++it;
853 }
854 }
855 }
856 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
857 if (alloc.ContainsUnsafe(it->first)) {
858 // Note that the code has already been pushed to method_headers in the loop
859 // above and is going to be removed in FreeCode() below.
860 it = osr_code_map_.erase(it);
861 } else {
862 ++it;
863 }
864 }
865 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
866 ProfilingInfo* info = *it;
867 if (alloc.ContainsUnsafe(info->GetMethod())) {
868 info->GetMethod()->SetProfilingInfo(nullptr);
869 FreeData(reinterpret_cast<uint8_t*>(info));
870 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000871 } else {
872 ++it;
873 }
874 }
875 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700876 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100877}
878
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000879bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
880 return kUseReadBarrier
881 ? self->GetWeakRefAccessEnabled()
Orion Hodson88591fe2018-03-06 13:35:43 +0000882 : is_weak_access_enabled_.load(std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000883}
884
885void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
886 if (IsWeakAccessEnabled(self)) {
887 return;
888 }
889 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000890 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000891 while (!IsWeakAccessEnabled(self)) {
892 inline_cache_cond_.Wait(self);
893 }
894}
895
896void JitCodeCache::BroadcastForInlineCacheAccess() {
897 Thread* self = Thread::Current();
898 MutexLock mu(self, lock_);
899 inline_cache_cond_.Broadcast(self);
900}
901
902void JitCodeCache::AllowInlineCacheAccess() {
903 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000904 is_weak_access_enabled_.store(true, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000905 BroadcastForInlineCacheAccess();
906}
907
908void JitCodeCache::DisallowInlineCacheAccess() {
909 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000910 is_weak_access_enabled_.store(false, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000911}
912
913void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
914 Handle<mirror::ObjectArray<mirror::Class>> array) {
915 WaitUntilInlineCacheAccessible(Thread::Current());
916 // Note that we don't need to lock `lock_` here, the compiler calling
917 // this method has already ensured the inline cache will not be deleted.
918 for (size_t in_cache = 0, in_array = 0;
919 in_cache < InlineCache::kIndividualCacheSize;
920 ++in_cache) {
921 mirror::Class* object = ic.classes_[in_cache].Read();
922 if (object != nullptr) {
923 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000924 }
925 }
926}
927
David Srbeckye36e7f22018-11-14 14:21:23 +0000928static void ClearMethodCounter(ArtMethod* method, bool was_warm)
929 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf044c222017-05-31 15:27:54 -0700930 if (was_warm) {
Vladimir Markoc945e0d2018-07-18 17:26:45 +0100931 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700932 }
933 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
934 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100935 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
936 // the warmup threshold is 1.
937 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
938 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700939}
940
Alex Light33b7b5d2018-08-07 19:13:51 +0000941void JitCodeCache::WaitForPotentialCollectionToCompleteRunnable(Thread* self) {
942 while (collection_in_progress_) {
943 lock_.Unlock(self);
944 {
945 ScopedThreadSuspension sts(self, kSuspended);
946 MutexLock mu(self, lock_);
947 WaitForPotentialCollectionToComplete(self);
948 }
949 lock_.Lock(self);
950 }
951}
952
Orion Hodson1d3fd082018-09-28 09:38:35 +0100953const MemMap* JitCodeCache::GetUpdatableCodeMapping() const {
954 if (HasDualCodeMapping()) {
955 return &non_exec_pages_;
956 } else if (HasCodeMapping()) {
957 return &exec_pages_;
958 } else {
959 return nullptr;
960 }
961}
962
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100963uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
964 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000965 uint8_t* stack_map,
966 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100967 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000968 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100969 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000970 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100971 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700972 bool has_should_deoptimize_flag,
973 const ArenaSet<ArtMethod*>&
974 cha_single_implementation_list) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000975 DCHECK(!method->IsNative() || !osr);
Alex Light33b7b5d2018-08-07 19:13:51 +0000976
977 if (!method->IsNative()) {
978 // We need to do this before grabbing the lock_ because it needs to be able to see the string
979 // InternTable. Native methods do not have roots.
980 DCheckRootsAreValid(roots);
981 }
982
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100983 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100984 uint8_t* code_ptr = nullptr;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100985
Alex Light33b7b5d2018-08-07 19:13:51 +0000986 MutexLock mu(self, lock_);
987 // We need to make sure that there will be no jit-gcs going on and wait for any ongoing one to
988 // finish.
989 WaitForPotentialCollectionToCompleteRunnable(self);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100990 {
Alex Light33b7b5d2018-08-07 19:13:51 +0000991 ScopedCodeCacheWrite scc(this);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100992
993 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
994 // Ensure the header ends up at expected instruction alignment.
995 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
996 size_t total_size = header_size + code_size;
997
998 // AllocateCode allocates memory in non-executable region for alignment header and code. The
999 // header size may include alignment padding.
1000 uint8_t* nox_memory = AllocateCode(total_size);
1001 if (nox_memory == nullptr) {
Alex Light33b7b5d2018-08-07 19:13:51 +00001002 return nullptr;
1003 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001004
Orion Hodson1d3fd082018-09-28 09:38:35 +01001005 // code_ptr points to non-executable code.
1006 code_ptr = nox_memory + header_size;
Alex Light33b7b5d2018-08-07 19:13:51 +00001007 std::copy(code, code + code_size, code_ptr);
1008 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001009
1010 // From here code_ptr points to executable code.
1011 if (HasDualCodeMapping()) {
1012 code_ptr = TranslateAddress(code_ptr, non_exec_pages_, exec_pages_);
1013 }
1014
Alex Light33b7b5d2018-08-07 19:13:51 +00001015 new (method_header) OatQuickMethodHeader(
Nicolas Geoffray57083762019-03-05 09:24:45 +00001016 (stack_map != nullptr) ? code_ptr - stack_map : 0u,
1017 code_size);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001018
1019 DCHECK(!Runtime::Current()->IsAotCompiler());
1020 if (has_should_deoptimize_flag) {
1021 method_header->SetHasShouldDeoptimizeFlag();
1022 }
1023
1024 // Update method_header pointer to executable code region.
1025 if (HasDualCodeMapping()) {
1026 method_header = TranslateAddress(method_header, non_exec_pages_, exec_pages_);
1027 }
1028
1029 // Both instruction and data caches need flushing to the point of unification where both share
1030 // a common view of memory. Flushing the data cache ensures the dirty cachelines from the
1031 // newly added code are written out to the point of unification. Flushing the instruction
1032 // cache ensures the newly written code will be fetched from the point of unification before
1033 // use. Memory in the code cache is re-cycled as code is added and removed. The flushes
1034 // prevent stale code from residing in the instruction cache.
1035 //
1036 // Caches are flushed before write permission is removed because some ARMv8 Qualcomm kernels
1037 // may trigger a segfault if a page fault occurs when requesting a cache maintenance
1038 // operation. This is a kernel bug that we need to work around until affected devices
1039 // (e.g. Nexus 5X and 6P) stop being supported or their kernels are fixed.
Alex Light33b7b5d2018-08-07 19:13:51 +00001040 //
1041 // For reference, this behavior is caused by this commit:
1042 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
Orion Hodson1d3fd082018-09-28 09:38:35 +01001043 //
1044 if (HasDualCodeMapping()) {
1045 // Flush the data cache lines associated with the non-executable copy of the code just added.
1046 FlushDataCache(nox_memory, nox_memory + total_size);
1047 }
1048 // FlushInstructionCache() flushes both data and instruction caches lines. The cacheline range
1049 // flushed is for the executable mapping of the code just added.
Orion Hodsondf1ab202019-06-02 16:45:03 +01001050 uint8_t* x_memory = reinterpret_cast<uint8_t*>(method_header);
1051 FlushInstructionCache(x_memory, x_memory + total_size);
Orion Hodsonf2331362018-07-11 15:14:10 +01001052
1053 // Ensure CPU instruction pipelines are flushed for all cores. This is necessary for
1054 // correctness as code may still be in instruction pipelines despite the i-cache flush. It is
1055 // not safe to assume that changing permissions with mprotect (RX->RWX->RX) will cause a TLB
1056 // shootdown (incidentally invalidating the CPU pipelines by sending an IPI to all cores to
1057 // notify them of the TLB invalidation). Some architectures, notably ARM and ARM64, have
1058 // hardware support that broadcasts TLB invalidations and so their kernels have no software
Orion Hodson1d3fd082018-09-28 09:38:35 +01001059 // based TLB shootdown. The sync-core flavor of membarrier was introduced in Linux 4.16 to
1060 // address this (see mbarrier(2)). The membarrier here will fail on prior kernels and on
1061 // platforms lacking the appropriate support.
Orion Hodson563ada22018-09-04 11:28:31 +01001062 art::membarrier(art::MembarrierCommand::kPrivateExpeditedSyncCore);
Orion Hodson38d29fd2018-09-07 12:58:37 +01001063
Nicolas Geoffray0a522232016-01-19 09:34:58 +00001064 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001065 }
Orion Hodson1d3fd082018-09-28 09:38:35 +01001066
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001067 // We need to update the entry point in the runnable state for the instrumentation.
1068 {
Alex Light33b7b5d2018-08-07 19:13:51 +00001069 // The following needs to be guarded by cha_lock_ also. Otherwise it's possible that the
1070 // compiled code is considered invalidated by some class linking, but below we still make the
1071 // compiled code valid for the method. Need cha_lock_ for checking all single-implementation
1072 // flags and register dependencies.
Mingyao Yang063fc772016-08-02 11:02:54 -07001073 MutexLock cha_mu(self, *Locks::cha_lock_);
1074 bool single_impl_still_valid = true;
1075 for (ArtMethod* single_impl : cha_single_implementation_list) {
1076 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001077 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
1078 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -07001079 single_impl_still_valid = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001080 ClearMethodCounter(method, /*was_warm=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -07001081 break;
1082 }
1083 }
1084
1085 // Discard the code if any single-implementation assumptions are now invalid.
1086 if (!single_impl_still_valid) {
1087 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
1088 return nullptr;
1089 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00001090 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -08001091 << "Should not be using cha on debuggable apps/runs!";
1092
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001093 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mingyao Yang063fc772016-08-02 11:02:54 -07001094 for (ArtMethod* single_impl : cha_single_implementation_list) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001095 class_linker->GetClassHierarchyAnalysis()->AddDependency(single_impl, method, method_header);
Mingyao Yang063fc772016-08-02 11:02:54 -07001096 }
1097
Vladimir Marko2196c652017-11-30 16:16:07 +00001098 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001099 auto it = jni_stubs_map_.find(JniStubKey(method));
1100 DCHECK(it != jni_stubs_map_.end())
1101 << "Entry inserted in NotifyCompilationOf() should be alive.";
1102 JniStubData* data = &it->second;
1103 DCHECK(ContainsElement(data->GetMethods(), method))
1104 << "Entry inserted in NotifyCompilationOf() should contain this method.";
1105 data->SetCode(code_ptr);
1106 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
1107 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001108 if (!class_linker->IsQuickResolutionStub(m->GetEntryPointFromQuickCompiledCode())) {
1109 instrum->UpdateMethodsCode(m, method_header->GetEntryPoint());
1110 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001111 }
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001112 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +00001113 // Fill the root table before updating the entry point.
1114 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
1115 DCHECK_LE(roots_data, stack_map);
1116 FillRootTable(roots_data, roots);
1117 {
1118 // Flush data cache, as compiled code references literals in it.
Orion Hodson38d29fd2018-09-07 12:58:37 +01001119 FlushDataCache(roots_data, roots_data + data_size);
Vladimir Marko2196c652017-11-30 16:16:07 +00001120 }
1121 method_code_map_.Put(code_ptr, method);
1122 if (osr) {
1123 number_of_osr_compilations_++;
1124 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001125 } else if (class_linker->IsQuickResolutionStub(
1126 method->GetEntryPointFromQuickCompiledCode())) {
1127 // This situation currently only occurs in the jit-zygote mode.
1128 DCHECK(Runtime::Current()->IsZygote());
David Srbecky3db3d372019-04-17 18:19:17 +01001129 DCHECK(Runtime::Current()->IsUsingApexBootImageLocation());
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001130 DCHECK(method->GetDeclaringClass()->GetClassLoader() == nullptr);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001131 // TODO(ngeoffray): In most cases, the zygote will not have a profiling
1132 // info for a compiled method. Use a map instead.
1133 if (method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
1134 // Save the entrypoint, so it can be fetched later once the class is
1135 // initialized.
1136 method->GetProfilingInfo(kRuntimePointerSize)->SetSavedEntryPoint(
1137 method_header->GetEntryPoint());
1138 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001139 } else {
1140 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1141 method, method_header->GetEntryPoint());
1142 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001143 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001144 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001145 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -07001146 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001147 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1148 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
1149 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -07001150 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
1151 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001152 histogram_code_memory_use_.AddValue(code_size);
1153 if (code_size > kCodeSizeLogThreshold) {
1154 LOG(INFO) << "JIT allocated "
1155 << PrettySize(code_size)
1156 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -07001157 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001158 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001159 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001160
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001161 return reinterpret_cast<uint8_t*>(method_header);
1162}
1163
1164size_t JitCodeCache::CodeCacheSize() {
1165 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001166 return CodeCacheSizeLocked();
1167}
1168
Orion Hodsoneced6922017-06-01 10:54:28 +01001169bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001170 // This function is used only for testing and only with non-native methods.
1171 CHECK(!method->IsNative());
1172
Orion Hodsoneced6922017-06-01 10:54:28 +01001173 MutexLock mu(Thread::Current(), lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +01001174
Vladimir Marko2196c652017-11-30 16:16:07 +00001175 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
1176 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +01001177
1178 if (!in_cache) {
1179 return false;
1180 }
1181
David Srbeckye36e7f22018-11-14 14:21:23 +00001182 method->SetCounter(0);
Orion Hodsoneced6922017-06-01 10:54:28 +01001183 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1184 method, GetQuickToInterpreterBridge());
1185 VLOG(jit)
1186 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
1187 << ArtMethod::PrettyMethod(method) << "@" << method
1188 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1189 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
1190 return true;
1191}
1192
Vladimir Marko2196c652017-11-30 16:16:07 +00001193bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
1194 if (LIKELY(!method->IsNative())) {
1195 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1196 if (info != nullptr) {
1197 RemoveElement(profiling_infos_, info);
1198 }
1199 method->SetProfilingInfo(nullptr);
1200 }
1201
1202 bool in_cache = false;
Calin Juravle016fcbe22018-05-03 19:47:35 -07001203 ScopedCodeCacheWrite ccw(this);
Vladimir Marko2196c652017-11-30 16:16:07 +00001204 if (UNLIKELY(method->IsNative())) {
1205 auto it = jni_stubs_map_.find(JniStubKey(method));
1206 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
1207 in_cache = true;
1208 if (it->second.GetMethods().empty()) {
1209 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +01001210 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +00001211 }
1212 jni_stubs_map_.erase(it);
1213 } else {
1214 it->first.UpdateShorty(it->second.GetMethods().front());
1215 }
1216 }
1217 } else {
1218 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1219 if (it->second == method) {
1220 in_cache = true;
1221 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +01001222 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +00001223 }
1224 it = method_code_map_.erase(it);
1225 } else {
1226 ++it;
1227 }
1228 }
1229
1230 auto osr_it = osr_code_map_.find(method);
1231 if (osr_it != osr_code_map_.end()) {
1232 osr_code_map_.erase(osr_it);
1233 }
1234 }
1235
1236 return in_cache;
1237}
1238
Alex Lightdba61482016-12-21 08:20:29 -08001239// This notifies the code cache that the given method has been redefined and that it should remove
1240// any cached information it has on the method. All threads must be suspended before calling this
1241// method. The compiled code for the method (if there is any) must not be in any threads call stack.
1242void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
1243 MutexLock mu(Thread::Current(), lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001244 RemoveMethodLocked(method, /* release_memory= */ true);
Alex Lightdba61482016-12-21 08:20:29 -08001245}
1246
1247// This invalidates old_method. Once this function returns one can no longer use old_method to
1248// execute code unless it is fixed up. This fixup will happen later in the process of installing a
1249// class redefinition.
1250// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
1251// shouldn't be used since it is no longer logically in the jit code cache.
1252// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
1253void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001254 MutexLock mu(Thread::Current(), lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +00001255 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001256 // Update methods in jni_stubs_map_.
1257 for (auto& entry : jni_stubs_map_) {
1258 JniStubData& data = entry.second;
1259 data.MoveObsoleteMethod(old_method, new_method);
1260 }
Alex Lighteee0bd42017-02-14 15:31:45 +00001261 return;
1262 }
Alex Lightdba61482016-12-21 08:20:29 -08001263 // Update ProfilingInfo to the new one and remove it from the old_method.
1264 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
1265 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
1266 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
1267 old_method->SetProfilingInfo(nullptr);
1268 // Since the JIT should be paused and all threads suspended by the time this is called these
1269 // checks should always pass.
1270 DCHECK(!info->IsInUseByCompiler());
1271 new_method->SetProfilingInfo(info);
Alex Light2d441b12018-06-08 15:33:21 -07001272 // Get rid of the old saved entrypoint if it is there.
1273 info->SetSavedEntryPoint(nullptr);
Alex Lightdba61482016-12-21 08:20:29 -08001274 info->method_ = new_method;
1275 }
1276 // Update method_code_map_ to point to the new method.
1277 for (auto& it : method_code_map_) {
1278 if (it.second == old_method) {
1279 it.second = new_method;
1280 }
1281 }
1282 // Update osr_code_map_ to point to the new method.
1283 auto code_map = osr_code_map_.find(old_method);
1284 if (code_map != osr_code_map_.end()) {
1285 osr_code_map_.Put(new_method, code_map->second);
1286 osr_code_map_.erase(old_method);
1287 }
1288}
1289
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001290void JitCodeCache::ClearEntryPointsInZygoteExecSpace() {
1291 MutexLock mu(Thread::Current(), lock_);
1292 // Iterate over profiling infos to know which methods may have been JITted. Note that
1293 // to be JITted, a method must have a profiling info.
1294 for (ProfilingInfo* info : profiling_infos_) {
1295 ArtMethod* method = info->GetMethod();
1296 if (IsInZygoteExecSpace(method->GetEntryPointFromQuickCompiledCode())) {
1297 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1298 }
1299 // If zygote does method tracing, or in some configuration where
1300 // the JIT zygote does GC, we also need to clear the saved entry point
1301 // in the profiling info.
1302 if (IsInZygoteExecSpace(info->GetSavedEntryPoint())) {
1303 info->SetSavedEntryPoint(nullptr);
1304 }
1305 }
1306}
1307
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001308size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001309 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001310}
1311
1312size_t JitCodeCache::DataCacheSize() {
1313 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001314 return DataCacheSizeLocked();
1315}
1316
1317size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001318 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001319}
1320
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001321void JitCodeCache::ClearData(Thread* self,
1322 uint8_t* stack_map_data,
1323 uint8_t* roots_data) {
1324 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001325 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001326 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001327}
1328
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001329size_t JitCodeCache::ReserveData(Thread* self,
1330 size_t stack_map_size,
1331 size_t number_of_roots,
1332 ArtMethod* method,
1333 uint8_t** stack_map_data,
1334 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001335 size_t table_size = ComputeRootTableSize(number_of_roots);
David Srbecky8cd54542018-07-15 23:58:44 +01001336 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001337 uint8_t* result = nullptr;
1338
1339 {
1340 ScopedThreadSuspension sts(self, kSuspended);
1341 MutexLock mu(self, lock_);
1342 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001343 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001344 }
1345
1346 if (result == nullptr) {
1347 // Retry.
1348 GarbageCollectCache(self);
1349 ScopedThreadSuspension sts(self, kSuspended);
1350 MutexLock mu(self, lock_);
1351 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001352 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001353 }
1354
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001355 MutexLock mu(self, lock_);
1356 histogram_stack_map_memory_use_.AddValue(size);
1357 if (size > kStackMapSizeLogThreshold) {
1358 LOG(INFO) << "JIT allocated "
1359 << PrettySize(size)
1360 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001361 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001362 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001363 if (result != nullptr) {
1364 *roots_data = result;
1365 *stack_map_data = result + table_size;
1366 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001367 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001368 } else {
1369 *roots_data = nullptr;
1370 *stack_map_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001371 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001372 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001373}
1374
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001375class MarkCodeClosure final : public Closure {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001376 public:
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001377 MarkCodeClosure(JitCodeCache* code_cache, CodeCacheBitmap* bitmap, Barrier* barrier)
1378 : code_cache_(code_cache), bitmap_(bitmap), barrier_(barrier) {}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001379
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001380 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001381 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001382 DCHECK(thread == Thread::Current() || thread->IsSuspended());
Andreas Gampec7d878d2018-11-19 18:42:06 +00001383 StackVisitor::WalkStack(
1384 [&](const art::StackVisitor* stack_visitor) {
1385 const OatQuickMethodHeader* method_header =
1386 stack_visitor->GetCurrentOatQuickMethodHeader();
1387 if (method_header == nullptr) {
1388 return true;
1389 }
1390 const void* code = method_header->GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001391 if (code_cache_->ContainsPc(code) && !code_cache_->IsInZygoteExecSpace(code)) {
Andreas Gampec7d878d2018-11-19 18:42:06 +00001392 // Use the atomic set version, as multiple threads are executing this code.
1393 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1394 }
1395 return true;
1396 },
1397 thread,
1398 /* context= */ nullptr,
1399 art::StackVisitor::StackWalkKind::kSkipInlinedFrames);
1400
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001401 if (kIsDebugBuild) {
1402 // The stack walking code queries the side instrumentation stack if it
1403 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1404 // must have been seen. We sanity check this below.
1405 for (const instrumentation::InstrumentationStackFrame& frame
1406 : *thread->GetInstrumentationStack()) {
1407 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1408 // its stack frame, it is not the method owning return_pc_. We just pass null to
1409 // LookupMethodHeader: the method is only checked against in debug builds.
1410 OatQuickMethodHeader* method_header =
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001411 code_cache_->LookupMethodHeader(frame.return_pc_, /* method= */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001412 if (method_header != nullptr) {
1413 const void* code = method_header->GetCode();
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001414 CHECK(bitmap_->Test(FromCodeToAllocation(code)));
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001415 }
1416 }
1417 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001418 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001419 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001420
1421 private:
1422 JitCodeCache* const code_cache_;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001423 CodeCacheBitmap* const bitmap_;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001424 Barrier* const barrier_;
1425};
1426
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001427void JitCodeCache::NotifyCollectionDone(Thread* self) {
1428 collection_in_progress_ = false;
1429 lock_cond_.Broadcast(self);
1430}
1431
1432void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001433 size_t data_space_footprint = new_footprint / kCodeAndDataCapacityDivider;
1434 DCHECK(IsAlignedParam(data_space_footprint, kPageSize));
1435 DCHECK_EQ(data_space_footprint * kCodeAndDataCapacityDivider, new_footprint);
1436 mspace_set_footprint_limit(data_mspace_, data_space_footprint);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001437 if (HasCodeMapping()) {
Calin Juravle016fcbe22018-05-03 19:47:35 -07001438 ScopedCodeCacheWrite scc(this);
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001439 mspace_set_footprint_limit(exec_mspace_, new_footprint - data_space_footprint);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001440 }
1441}
1442
1443bool JitCodeCache::IncreaseCodeCacheCapacity() {
1444 if (current_capacity_ == max_capacity_) {
1445 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001446 }
1447
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001448 // Double the capacity if we're below 1MB, or increase it by 1MB if
1449 // we're above.
1450 if (current_capacity_ < 1 * MB) {
1451 current_capacity_ *= 2;
1452 } else {
1453 current_capacity_ += 1 * MB;
1454 }
1455 if (current_capacity_ > max_capacity_) {
1456 current_capacity_ = max_capacity_;
1457 }
1458
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001459 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001460
1461 SetFootprintLimit(current_capacity_);
1462
1463 return true;
1464}
1465
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001466void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1467 Barrier barrier(0);
1468 size_t threads_running_checkpoint = 0;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001469 MarkCodeClosure closure(this, GetLiveBitmap(), &barrier);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001470 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1471 // Now that we have run our checkpoint, move to a suspended state and wait
1472 // for other threads to run the checkpoint.
1473 ScopedThreadSuspension sts(self, kSuspended);
1474 if (threads_running_checkpoint != 0) {
1475 barrier.Increment(self, threads_running_checkpoint);
1476 }
1477}
1478
Nicolas Geoffray35122442016-03-02 12:05:30 +00001479bool JitCodeCache::ShouldDoFullCollection() {
1480 if (current_capacity_ == max_capacity_) {
1481 // Always do a full collection when the code cache is full.
1482 return true;
1483 } else if (current_capacity_ < kReservedCapacity) {
1484 // Always do partial collection when the code cache size is below the reserved
1485 // capacity.
1486 return false;
1487 } else if (last_collection_increased_code_cache_) {
1488 // This time do a full collection.
1489 return true;
1490 } else {
1491 // This time do a partial collection.
1492 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001493 }
1494}
1495
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001496void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001497 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001498 // Wait for an existing collection, or let everyone know we are starting one.
1499 {
1500 ScopedThreadSuspension sts(self, kSuspended);
1501 MutexLock mu(self, lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001502 if (!garbage_collect_code_) {
1503 IncreaseCodeCacheCapacity();
1504 return;
1505 } else if (WaitForPotentialCollectionToComplete(self)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001506 return;
1507 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001508 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001509 live_bitmap_.reset(CodeCacheBitmap::Create(
1510 "code-cache-bitmap",
Orion Hodson1d3fd082018-09-28 09:38:35 +01001511 reinterpret_cast<uintptr_t>(exec_pages_.Begin()),
1512 reinterpret_cast<uintptr_t>(exec_pages_.Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001513 collection_in_progress_ = true;
1514 }
1515 }
1516
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001517 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001518 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001519 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001520
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001521 bool do_full_collection = false;
1522 {
1523 MutexLock mu(self, lock_);
1524 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001525 }
1526
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001527 VLOG(jit) << "Do "
1528 << (do_full_collection ? "full" : "partial")
1529 << " code cache collection, code="
1530 << PrettySize(CodeCacheSize())
1531 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001532
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001533 DoCollection(self, /* collect_profiling_info= */ do_full_collection);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001534
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001535 VLOG(jit) << "After code cache collection, code="
1536 << PrettySize(CodeCacheSize())
1537 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001538
1539 {
1540 MutexLock mu(self, lock_);
1541
1542 // Increase the code cache only when we do partial collections.
1543 // TODO: base this strategy on how full the code cache is?
1544 if (do_full_collection) {
1545 last_collection_increased_code_cache_ = false;
1546 } else {
1547 last_collection_increased_code_cache_ = true;
1548 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001549 }
1550
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001551 bool next_collection_will_be_full = ShouldDoFullCollection();
1552
1553 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001554 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001555 // Save the entry point of methods we have compiled, and update the entry
1556 // point of those methods to the interpreter. If the method is invoked, the
1557 // interpreter will update its entry point to the compiled code and call it.
1558 for (ProfilingInfo* info : profiling_infos_) {
1559 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001560 if (!IsInZygoteDataSpace(info) && ContainsPc(entry_point)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001561 info->SetSavedEntryPoint(entry_point);
Vladimir Marko2196c652017-11-30 16:16:07 +00001562 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001563 // class of the method. We may be concurrently running a GC which makes accessing
1564 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1565 // checked that the current entry point is JIT compiled code.
1566 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001567 }
1568 }
1569
Vladimir Marko2196c652017-11-30 16:16:07 +00001570 // Change entry points of native methods back to the GenericJNI entrypoint.
1571 for (const auto& entry : jni_stubs_map_) {
1572 const JniStubData& data = entry.second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001573 if (!data.IsCompiled() || IsInZygoteExecSpace(data.GetCode())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001574 continue;
1575 }
1576 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1577 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1578 const OatQuickMethodHeader* method_header =
1579 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1580 for (ArtMethod* method : data.GetMethods()) {
1581 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1582 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1583 method->SetCounter(new_counter);
1584 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1585 }
1586 }
1587 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001588 }
1589 live_bitmap_.reset(nullptr);
1590 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001591 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001592 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001593 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001594}
1595
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001596void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001597 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001598 std::unordered_set<OatQuickMethodHeader*> method_headers;
1599 {
1600 MutexLock mu(self, lock_);
Calin Juravle016fcbe22018-05-03 19:47:35 -07001601 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -07001602 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001603 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1604 JniStubData* data = &it->second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001605 if (IsInZygoteExecSpace(data->GetCode()) ||
1606 !data->IsCompiled() ||
1607 GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001608 ++it;
1609 } else {
1610 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1611 it = jni_stubs_map_.erase(it);
1612 }
1613 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001614 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1615 const void* code_ptr = it->first;
1616 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001617 if (IsInZygoteExecSpace(code_ptr) || GetLiveBitmap()->Test(allocation)) {
Mingyao Yang063fc772016-08-02 11:02:54 -07001618 ++it;
1619 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001620 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1621 method_headers.insert(header);
Mingyao Yang063fc772016-08-02 11:02:54 -07001622 it = method_code_map_.erase(it);
1623 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001624 }
1625 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001626 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001627}
1628
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001629bool JitCodeCache::GetGarbageCollectCode() {
1630 MutexLock mu(Thread::Current(), lock_);
1631 return garbage_collect_code_;
1632}
1633
1634void JitCodeCache::SetGarbageCollectCode(bool value) {
1635 Thread* self = Thread::Current();
1636 MutexLock mu(self, lock_);
1637 if (garbage_collect_code_ != value) {
1638 if (garbage_collect_code_) {
1639 // When dynamically disabling the garbage collection, we neee
1640 // to make sure that a potential current collection is finished, and also
1641 // clear the saved entry point in profiling infos to avoid dangling pointers.
1642 WaitForPotentialCollectionToComplete(self);
1643 for (ProfilingInfo* info : profiling_infos_) {
1644 info->SetSavedEntryPoint(nullptr);
1645 }
1646 }
1647 // Update the flag while holding the lock to ensure no thread will try to GC.
1648 garbage_collect_code_ = value;
1649 }
1650}
1651
Nicolas Geoffray35122442016-03-02 12:05:30 +00001652void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001653 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001654 {
1655 MutexLock mu(self, lock_);
1656 if (collect_profiling_info) {
1657 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1658 // Also remove the saved entry point from the ProfilingInfo objects.
1659 for (ProfilingInfo* info : profiling_infos_) {
1660 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001661 if (!ContainsPc(ptr) && !info->IsInUseByCompiler() && !IsInZygoteDataSpace(info)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001662 info->GetMethod()->SetProfilingInfo(nullptr);
1663 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001664
1665 if (info->GetSavedEntryPoint() != nullptr) {
1666 info->SetSavedEntryPoint(nullptr);
1667 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001668 // give it a chance to be hot again.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001669 ClearMethodCounter(info->GetMethod(), /*was_warm=*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001670 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001671 }
1672 } else if (kIsDebugBuild) {
1673 // Sanity check that the profiling infos do not have a dangling entry point.
1674 for (ProfilingInfo* info : profiling_infos_) {
David Srbecky605a5fe2019-04-24 14:05:21 +01001675 DCHECK(!Runtime::Current()->IsZygote());
1676 const void* entry_point = info->GetSavedEntryPoint();
1677 DCHECK(entry_point == nullptr || IsInZygoteExecSpace(entry_point));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001678 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001679 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001680
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001681 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1682 // an entry point is either:
1683 // - an osr compiled code, that will be removed if not in a thread call stack.
1684 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001685 for (const auto& entry : jni_stubs_map_) {
1686 const JniStubData& data = entry.second;
1687 const void* code_ptr = data.GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001688 if (IsInZygoteExecSpace(code_ptr)) {
1689 continue;
1690 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001691 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1692 for (ArtMethod* method : data.GetMethods()) {
1693 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1694 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1695 break;
1696 }
1697 }
1698 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001699 for (const auto& it : method_code_map_) {
1700 ArtMethod* method = it.second;
1701 const void* code_ptr = it.first;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001702 if (IsInZygoteExecSpace(code_ptr)) {
1703 continue;
1704 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001705 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1706 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1707 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1708 }
1709 }
1710
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001711 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001712 // on thread stacks).
1713 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001714 }
1715
1716 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001717 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001718
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001719 // At this point, mutator threads are still running, and entrypoints of methods can
1720 // change. We do know they cannot change to a code cache entry that is not marked,
1721 // therefore we can safely remove those entries.
1722 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001723
Nicolas Geoffray35122442016-03-02 12:05:30 +00001724 if (collect_profiling_info) {
1725 MutexLock mu(self, lock_);
1726 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001727 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001728 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001729 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001730 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1731 // that the compiled code would not get revived. As mutator threads run concurrently,
1732 // they may have revived the compiled code, and now we are in the situation where
1733 // a method has compiled code but no ProfilingInfo.
1734 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1735 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001736 if (ContainsPc(ptr) &&
1737 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001738 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001739 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001740 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001741 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001742 return true;
1743 }
1744 return false;
1745 });
1746 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001747 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001748}
1749
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001750OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001751 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1752 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001753 // On Thumb-2, the pc is offset by one.
1754 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001755 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001756 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1757 return nullptr;
1758 }
1759
Vladimir Marko2196c652017-11-30 16:16:07 +00001760 if (!kIsDebugBuild) {
1761 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1762 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001763 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001764
Vladimir Marko2196c652017-11-30 16:16:07 +00001765 MutexLock mu(Thread::Current(), lock_);
1766 OatQuickMethodHeader* method_header = nullptr;
1767 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1768 if (method != nullptr && UNLIKELY(method->IsNative())) {
1769 auto it = jni_stubs_map_.find(JniStubKey(method));
1770 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1771 return nullptr;
1772 }
1773 const void* code_ptr = it->second.GetCode();
1774 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1775 if (!method_header->Contains(pc)) {
1776 return nullptr;
1777 }
1778 } else {
1779 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1780 if (it != method_code_map_.begin()) {
1781 --it;
1782 const void* code_ptr = it->first;
1783 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1784 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1785 found_method = it->second;
1786 }
1787 }
1788 if (method_header == nullptr && method == nullptr) {
1789 // Scan all compiled JNI stubs as well. This slow search is used only
1790 // for checks in debug build, for release builds the `method` is not null.
1791 for (auto&& entry : jni_stubs_map_) {
1792 const JniStubData& data = entry.second;
1793 if (data.IsCompiled() &&
1794 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1795 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1796 }
1797 }
1798 }
1799 if (method_header == nullptr) {
1800 return nullptr;
1801 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001802 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001803
1804 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Vladimir Markoeab02482019-05-09 10:28:17 +01001805 DCHECK_EQ(found_method, method)
1806 << ArtMethod::PrettyMethod(method) << " "
1807 << ArtMethod::PrettyMethod(found_method) << " "
David Sehr709b0702016-10-13 09:12:37 -07001808 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001809 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001810 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001811}
1812
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001813OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1814 MutexLock mu(Thread::Current(), lock_);
1815 auto it = osr_code_map_.find(method);
1816 if (it == osr_code_map_.end()) {
1817 return nullptr;
1818 }
1819 return OatQuickMethodHeader::FromCodePointer(it->second);
1820}
1821
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001822ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1823 ArtMethod* method,
1824 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001825 bool retry_allocation)
1826 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1827 NO_THREAD_SAFETY_ANALYSIS {
1828 ProfilingInfo* info = nullptr;
1829 if (!retry_allocation) {
1830 // If we are allocating for the interpreter, just try to lock, to avoid
1831 // lock contention with the JIT.
1832 if (lock_.ExclusiveTryLock(self)) {
1833 info = AddProfilingInfoInternal(self, method, entries);
1834 lock_.ExclusiveUnlock(self);
1835 }
1836 } else {
1837 {
1838 MutexLock mu(self, lock_);
1839 info = AddProfilingInfoInternal(self, method, entries);
1840 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001841
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001842 if (info == nullptr) {
1843 GarbageCollectCache(self);
1844 MutexLock mu(self, lock_);
1845 info = AddProfilingInfoInternal(self, method, entries);
1846 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001847 }
1848 return info;
1849}
1850
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001851ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001852 ArtMethod* method,
1853 const std::vector<uint32_t>& entries) {
1854 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001855 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001856 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001857
1858 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001859 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001860 if (info != nullptr) {
1861 return info;
1862 }
1863
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001864 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001865 if (data == nullptr) {
1866 return nullptr;
1867 }
1868 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001869
1870 // Make sure other threads see the data in the profiling info object before the
1871 // store in the ArtMethod's ProfilingInfo pointer.
Orion Hodson27b96762018-03-13 16:06:57 +00001872 std::atomic_thread_fence(std::memory_order_release);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001873
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001874 method->SetProfilingInfo(info);
1875 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001876 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001877 return info;
1878}
1879
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001880// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1881// is already held.
1882void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
Orion Hodson1d3fd082018-09-28 09:38:35 +01001883 if (mspace == exec_mspace_) {
1884 DCHECK(exec_mspace_ != nullptr);
1885 const MemMap* const code_pages = GetUpdatableCodeMapping();
1886 void* result = code_pages->Begin() + exec_end_;
1887 exec_end_ += increment;
1888 return result;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001889 } else {
1890 DCHECK_EQ(data_mspace_, mspace);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001891 void* result = data_pages_.Begin() + data_end_;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001892 data_end_ += increment;
Orion Hodson1d3fd082018-09-28 09:38:35 +01001893 return result;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001894 }
1895}
1896
Calin Juravle99629622016-04-19 16:33:46 +01001897void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001898 std::vector<ProfileMethodInfo>& methods) {
Nicolas Geoffray1afdfe62018-11-21 09:38:10 +00001899 Thread* self = Thread::Current();
1900 WaitUntilInlineCacheAccessible(self);
1901 MutexLock mu(self, lock_);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001902 ScopedTrace trace(__FUNCTION__);
Calin Juravlea39fd982017-05-18 10:15:52 -07001903 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001904 for (const ProfilingInfo* info : profiling_infos_) {
1905 ArtMethod* method = info->GetMethod();
1906 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001907 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1908 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001909 // Skip dex files which are not profiled.
1910 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001911 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001912 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001913
1914 // If the method didn't reach the compilation threshold don't save the inline caches.
1915 // They might be incomplete and cause unnecessary deoptimizations.
1916 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1917 if (method->GetCounter() < jit_compile_threshold) {
1918 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001919 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001920 continue;
1921 }
1922
Calin Juravle940eb0c2017-01-30 19:30:44 -08001923 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001924 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001925 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001926 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001927 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001928 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1929 mirror::Class* cls = cache.classes_[k].Read();
1930 if (cls == nullptr) {
1931 break;
1932 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001933
Calin Juravle13439f02017-02-21 01:17:21 -08001934 // Check if the receiver is in the boot class path or if it's in the
1935 // same class loader as the caller. If not, skip it, as there is not
1936 // much we can do during AOT.
1937 if (!cls->IsBootStrapClassLoaded() &&
1938 caller->GetClassLoader() != cls->GetClassLoader()) {
1939 is_missing_types = true;
1940 continue;
1941 }
1942
Calin Juravle4ca70a32017-02-21 16:22:24 -08001943 const DexFile* class_dex_file = nullptr;
1944 dex::TypeIndex type_index;
1945
1946 if (cls->GetDexCache() == nullptr) {
1947 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001948 // Make a best effort to find the type index in the method's dex file.
1949 // We could search all open dex files but that might turn expensive
1950 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001951 class_dex_file = dex_file;
1952 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1953 } else {
1954 class_dex_file = &(cls->GetDexFile());
1955 type_index = cls->GetDexTypeIndex();
1956 }
1957 if (!type_index.IsValid()) {
1958 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001959 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001960 continue;
1961 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001962 if (ContainsElement(dex_base_locations,
1963 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001964 // Only consider classes from the same apk (including multidex).
1965 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001966 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001967 } else {
1968 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001969 }
1970 }
1971 if (!profile_classes.empty()) {
1972 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001973 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001974 }
1975 }
1976 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001977 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001978 }
1979}
1980
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001981bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1982 MutexLock mu(Thread::Current(), lock_);
1983 return osr_code_map_.find(method) != osr_code_map_.end();
1984}
1985
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001986bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr, bool prejit) {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001987 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001988 return false;
1989 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001990
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01001991 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1992 if (class_linker->IsQuickResolutionStub(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001993 if (!prejit) {
1994 // Unless we're pre-jitting, we currently don't save the JIT compiled code if we cannot
1995 // update the entrypoint due to having the resolution stub.
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001996 VLOG(jit) << "Not compiling "
1997 << method->PrettyMethod()
1998 << " because it has the resolution stub";
1999 // Give it a new chance to be hot.
2000 ClearMethodCounter(method, /*was_warm=*/ false);
2001 return false;
2002 }
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01002003 }
2004
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00002005 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00002006 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
2007 return false;
2008 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002009
Vladimir Marko2196c652017-11-30 16:16:07 +00002010 if (UNLIKELY(method->IsNative())) {
2011 JniStubKey key(method);
2012 auto it = jni_stubs_map_.find(key);
2013 bool new_compilation = false;
2014 if (it == jni_stubs_map_.end()) {
2015 // Create a new entry to mark the stub as being compiled.
2016 it = jni_stubs_map_.Put(key, JniStubData{});
2017 new_compilation = true;
2018 }
2019 JniStubData* data = &it->second;
2020 data->AddMethod(method);
2021 if (data->IsCompiled()) {
2022 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
2023 const void* entrypoint = method_header->GetEntryPoint();
2024 // Update also entrypoints of other methods held by the JniStubData.
2025 // We could simply update the entrypoint of `method` but if the last JIT GC has
2026 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
2027 // as well change them back as this stub shall not be collected anyway and this
2028 // can avoid a few expensive GenericJNI calls.
2029 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
2030 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +00002031 // Call the dedicated method instead of the more generic UpdateMethodsCode, because
2032 // `m` might be in the process of being deleted.
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01002033 if (!class_linker->IsQuickResolutionStub(m->GetEntryPointFromQuickCompiledCode())) {
2034 instrumentation->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
2035 }
Vladimir Marko2196c652017-11-30 16:16:07 +00002036 }
2037 if (collection_in_progress_) {
David Srbeckyc45b5892019-04-24 10:32:04 +01002038 if (!IsInZygoteExecSpace(data->GetCode())) {
2039 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
2040 }
Vladimir Marko2196c652017-11-30 16:16:07 +00002041 }
2042 }
2043 return new_compilation;
2044 } else {
2045 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
2046 if (info == nullptr) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01002047 // When prejitting, we don't allocate a profiling info.
2048 if (!prejit) {
2049 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
2050 // Because the counter is not atomic, there are some rare cases where we may not hit the
2051 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
2052 ClearMethodCounter(method, /*was_warm=*/ false);
2053 return false;
2054 }
2055 } else {
2056 if (info->IsMethodBeingCompiled(osr)) {
2057 return false;
2058 }
2059 info->SetIsMethodBeingCompiled(true, osr);
Vladimir Marko2196c652017-11-30 16:16:07 +00002060 }
Vladimir Marko2196c652017-11-30 16:16:07 +00002061 return true;
2062 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002063}
2064
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00002065ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00002066 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07002067 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00002068 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002069 if (!info->IncrementInlineUse()) {
2070 // Overflow of inlining uses, just bail.
2071 return nullptr;
2072 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00002073 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00002074 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00002075}
2076
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00002077void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00002078 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07002079 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00002080 DCHECK(info != nullptr);
2081 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00002082}
2083
Vladimir Marko2196c652017-11-30 16:16:07 +00002084void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
2085 DCHECK_EQ(Thread::Current(), self);
2086 MutexLock mu(self, lock_);
2087 if (UNLIKELY(method->IsNative())) {
2088 auto it = jni_stubs_map_.find(JniStubKey(method));
2089 DCHECK(it != jni_stubs_map_.end());
2090 JniStubData* data = &it->second;
2091 DCHECK(ContainsElement(data->GetMethods(), method));
2092 if (UNLIKELY(!data->IsCompiled())) {
2093 // Failed to compile; the JNI compiler never fails, but the cache may be full.
2094 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
2095 } // else CommitCodeInternal() updated entrypoints of all methods in the JniStubData.
2096 } else {
2097 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01002098 if (info != nullptr) {
2099 DCHECK(info->IsMethodBeingCompiled(osr));
2100 info->SetIsMethodBeingCompiled(false, osr);
2101 }
Vladimir Marko2196c652017-11-30 16:16:07 +00002102 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002103}
2104
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00002105void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
2106 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00002107 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07002108 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Alex Light2d441b12018-06-08 15:33:21 -07002109 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00002110 if ((profiling_info != nullptr) &&
2111 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
Alex Light2d441b12018-06-08 15:33:21 -07002112 // When instrumentation is set, the actual entrypoint is the one in the profiling info.
2113 method_entrypoint = profiling_info->GetSavedEntryPoint();
Nicolas Geoffray35122442016-03-02 12:05:30 +00002114 // Prevent future uses of the compiled code.
2115 profiling_info->SetSavedEntryPoint(nullptr);
2116 }
2117
Alex Light2d441b12018-06-08 15:33:21 -07002118 // Clear the method counter if we are running jitted code since we might want to jit this again in
2119 // the future.
2120 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07002121 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07002122 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00002123 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
2124 method, GetQuickToInterpreterBridge());
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002125 ClearMethodCounter(method, /*was_warm=*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00002126 } else {
2127 MutexLock mu(Thread::Current(), lock_);
2128 auto it = osr_code_map_.find(method);
2129 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
2130 // Remove the OSR method, to avoid using it again.
2131 osr_code_map_.erase(it);
2132 }
2133 }
2134}
2135
Orion Hodsondf1ab202019-06-02 16:45:03 +01002136uint8_t* JitCodeCache::AllocateCode(size_t allocation_size) {
2137 // Each allocation should be on its own set of cache lines. The allocation must be large enough
2138 // for header, code, and any padding.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002139 uint8_t* result = reinterpret_cast<uint8_t*>(
Orion Hodsondf1ab202019-06-02 16:45:03 +01002140 mspace_memalign(exec_mspace_, kJitCodeAlignment, allocation_size));
2141 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002142 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
2143 // Ensure the header ends up at expected instruction alignment.
2144 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
2145 used_memory_for_code_ += mspace_usable_size(result);
2146 return result;
2147}
2148
Orion Hodsondbd05fe2017-08-10 11:41:35 +01002149void JitCodeCache::FreeCode(uint8_t* code) {
Nicolas Geoffray1c1c6e62018-12-07 14:46:50 +00002150 if (IsInZygoteExecSpace(code)) {
2151 // No need to free, this is shared memory.
2152 return;
2153 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +01002154 used_memory_for_code_ -= mspace_usable_size(code);
Orion Hodson1d3fd082018-09-28 09:38:35 +01002155 mspace_free(exec_mspace_, code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002156}
2157
2158uint8_t* JitCodeCache::AllocateData(size_t data_size) {
2159 void* result = mspace_malloc(data_mspace_, data_size);
2160 used_memory_for_data_ += mspace_usable_size(result);
2161 return reinterpret_cast<uint8_t*>(result);
2162}
2163
2164void JitCodeCache::FreeData(uint8_t* data) {
Nicolas Geoffray1c1c6e62018-12-07 14:46:50 +00002165 if (IsInZygoteDataSpace(data)) {
2166 // No need to free, this is shared memory.
2167 return;
2168 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002169 used_memory_for_data_ -= mspace_usable_size(data);
2170 mspace_free(data_mspace_, data);
2171}
2172
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002173void JitCodeCache::Dump(std::ostream& os) {
2174 MutexLock mu(Thread::Current(), lock_);
2175 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
2176 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
David Srbeckyafc60cd2018-12-05 11:59:31 +00002177 << "Current JIT mini-debug-info size: " << PrettySize(GetJitMiniDebugInfoMemUsage()) << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002178 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00002179 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002180 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
2181 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
2182 << "Total number of JIT compilations for on stack replacement: "
2183 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002184 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00002185 histogram_stack_map_memory_use_.PrintMemoryUse(os);
2186 histogram_code_memory_use_.PrintMemoryUse(os);
2187 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002188}
2189
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00002190void JitCodeCache::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00002191 if (is_zygote) {
2192 // Don't transition if this is for a child zygote.
2193 return;
2194 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00002195 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00002196
2197 zygote_data_pages_ = std::move(data_pages_);
2198 zygote_exec_pages_ = std::move(exec_pages_);
2199 zygote_data_mspace_ = data_mspace_;
2200 zygote_exec_mspace_ = exec_mspace_;
2201
2202 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
2203 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
2204
2205 InitializeState(initial_capacity, max_capacity);
2206
2207 std::string error_msg;
2208 if (!InitializeMappings(/* rwx_memory_allowed= */ !is_system_server, is_zygote, &error_msg)) {
2209 LOG(WARNING) << "Could not reset JIT state after zygote fork: " << error_msg;
2210 return;
2211 }
2212
2213 InitializeSpaces();
2214}
2215
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002216} // namespace jit
2217} // namespace art