blob: 97887ccbc96b5f719f4d81c6012e0ebba727100e [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) {
393 jit_code_cache->SetGarbageCollectCode(false);
394 }
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 Geoffray7a2c7c22018-11-20 10:03:13 +0000439 data_pages_ = MemMap();
440 exec_pages_ = MemMap();
441 non_exec_pages_ = MemMap();
442 initial_capacity_ = initial_capacity;
443 max_capacity_ = max_capacity;
444 current_capacity_ = initial_capacity,
445 data_end_ = initial_capacity / kCodeAndDataCapacityDivider;
446 exec_end_ = initial_capacity - data_end_;
447}
448
449void JitCodeCache::InitializeSpaces() {
Orion Hodson1d3fd082018-09-28 09:38:35 +0100450 // Initialize the data heap
451 data_mspace_ = create_mspace_with_base(data_pages_.Begin(), data_end_, false /*locked*/);
452 CHECK(data_mspace_ != nullptr) << "create_mspace_with_base (data) failed";
453
454 // Initialize the code heap
455 MemMap* code_heap = nullptr;
456 if (non_exec_pages_.IsValid()) {
457 code_heap = &non_exec_pages_;
458 } else if (exec_pages_.IsValid()) {
459 code_heap = &exec_pages_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100460 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100461 if (code_heap != nullptr) {
462 // Make all pages reserved for the code heap writable. The mspace allocator, that manages the
463 // heap, will take and initialize pages in create_mspace_with_base().
464 CheckedCall(mprotect, "create code heap", code_heap->Begin(), code_heap->Size(), kProtRW);
465 exec_mspace_ = create_mspace_with_base(code_heap->Begin(), exec_end_, false /*locked*/);
466 CHECK(exec_mspace_ != nullptr) << "create_mspace_with_base (exec) failed";
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000467 SetFootprintLimit(initial_capacity_);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100468 // Protect pages containing heap metadata. Updates to the code heap toggle write permission to
469 // perform the update and there are no other times write access is required.
470 CheckedCall(mprotect, "protect code heap", code_heap->Begin(), code_heap->Size(), kProtR);
471 } else {
472 exec_mspace_ = nullptr;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000473 SetFootprintLimit(initial_capacity_);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100474 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800475}
476
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000477JitCodeCache::~JitCodeCache() {}
478
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100479bool JitCodeCache::ContainsPc(const void* ptr) const {
Orion Hodson1d3fd082018-09-28 09:38:35 +0100480 return exec_pages_.Begin() <= ptr && ptr < exec_pages_.End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800481}
482
Alex Light2d441b12018-06-08 15:33:21 -0700483bool JitCodeCache::WillExecuteJitCode(ArtMethod* method) {
484 ScopedObjectAccess soa(art::Thread::Current());
485 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
486 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
487 return true;
488 } else if (method->GetEntryPointFromQuickCompiledCode() == GetQuickInstrumentationEntryPoint()) {
489 return FindCompiledCodeForInstrumentation(method) != nullptr;
490 }
491 return false;
492}
493
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000494bool JitCodeCache::ContainsMethod(ArtMethod* method) {
495 MutexLock mu(Thread::Current(), lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000496 if (UNLIKELY(method->IsNative())) {
497 auto it = jni_stubs_map_.find(JniStubKey(method));
498 if (it != jni_stubs_map_.end() &&
499 it->second.IsCompiled() &&
500 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000501 return true;
502 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000503 } else {
504 for (const auto& it : method_code_map_) {
505 if (it.second == method) {
506 return true;
507 }
508 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000509 }
510 return false;
511}
512
Vladimir Marko2196c652017-11-30 16:16:07 +0000513const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
514 DCHECK(method->IsNative());
515 MutexLock mu(Thread::Current(), lock_);
516 auto it = jni_stubs_map_.find(JniStubKey(method));
517 if (it != jni_stubs_map_.end()) {
518 JniStubData& data = it->second;
519 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
520 return data.GetCode();
521 }
522 }
523 return nullptr;
524}
525
Alex Light2d441b12018-06-08 15:33:21 -0700526const void* JitCodeCache::FindCompiledCodeForInstrumentation(ArtMethod* method) {
Alex Light839f53a2018-07-10 15:46:14 -0700527 // If jit-gc is still on we use the SavedEntryPoint field for doing that and so cannot use it to
528 // find the instrumentation entrypoint.
529 if (LIKELY(GetGarbageCollectCode())) {
Alex Light2d441b12018-06-08 15:33:21 -0700530 return nullptr;
531 }
532 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
533 if (info == nullptr) {
534 return nullptr;
535 }
536 // When GC is disabled for trampoline tracing we will use SavedEntrypoint to hold the actual
537 // jit-compiled version of the method. If jit-gc is disabled for other reasons this will just be
538 // nullptr.
539 return info->GetSavedEntryPoint();
540}
541
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800542class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100543 public:
Calin Juravle016fcbe22018-05-03 19:47:35 -0700544 explicit ScopedCodeCacheWrite(const JitCodeCache* const code_cache)
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100545 : ScopedTrace("ScopedCodeCacheWrite"),
Calin Juravle016fcbe22018-05-03 19:47:35 -0700546 code_cache_(code_cache) {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800547 ScopedTrace trace("mprotect all");
Orion Hodson1d3fd082018-09-28 09:38:35 +0100548 const MemMap* const updatable_pages = code_cache_->GetUpdatableCodeMapping();
549 if (updatable_pages != nullptr) {
550 int prot = code_cache_->HasDualCodeMapping() ? kProtRW : kProtRWX;
551 CheckedCall(mprotect, "Cache +W", updatable_pages->Begin(), updatable_pages->Size(), prot);
552 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800553 }
Calin Juravle016fcbe22018-05-03 19:47:35 -0700554
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100555 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800556 ScopedTrace trace("mprotect code");
Orion Hodson1d3fd082018-09-28 09:38:35 +0100557 const MemMap* const updatable_pages = code_cache_->GetUpdatableCodeMapping();
558 if (updatable_pages != nullptr) {
559 int prot = code_cache_->HasDualCodeMapping() ? kProtR : kProtRX;
560 CheckedCall(mprotect, "Cache -W", updatable_pages->Begin(), updatable_pages->Size(), prot);
561 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100562 }
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700563
David Sehrd1dbb742017-07-17 11:20:38 -0700564 private:
Calin Juravle016fcbe22018-05-03 19:47:35 -0700565 const JitCodeCache* const code_cache_;
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100566
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100567 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
568};
569
570uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100571 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000572 uint8_t* stack_map,
573 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100574 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000575 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100576 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000577 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100578 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700579 bool has_should_deoptimize_flag,
580 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100581 uint8_t* result = CommitCodeInternal(self,
582 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000583 stack_map,
584 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100585 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000586 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100587 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000588 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700589 roots,
590 has_should_deoptimize_flag,
591 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100592 if (result == nullptr) {
593 // Retry.
594 GarbageCollectCache(self);
595 result = CommitCodeInternal(self,
596 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000597 stack_map,
598 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100599 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000600 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100601 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000602 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700603 roots,
604 has_should_deoptimize_flag,
605 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100606 }
607 return result;
608}
609
610bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
611 bool in_collection = false;
612 while (collection_in_progress_) {
613 in_collection = true;
614 lock_cond_.Wait(self);
615 }
616 return in_collection;
617}
618
619static uintptr_t FromCodeToAllocation(const void* code) {
620 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
621 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
622}
623
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000624static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
625 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
626}
627
628static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
629 // The length of the table is stored just before the stack map (and therefore at the end of
630 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
631 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
632}
633
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800634static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
635 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
636 // pointer.
637 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
638}
639
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000640static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
641 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
642}
643
Vladimir Markoac3ac682018-09-20 11:01:43 +0100644static void DCheckRootsAreValid(const std::vector<Handle<mirror::Object>>& roots)
Alex Light3e36a9c2018-06-19 09:45:05 -0700645 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
646 if (!kIsDebugBuild) {
647 return;
648 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700649 // Put all roots in `roots_data`.
Vladimir Markoac3ac682018-09-20 11:01:43 +0100650 for (Handle<mirror::Object> object : roots) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700651 // Ensure the string is strongly interned. b/32995596
652 if (object->IsString()) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100653 ObjPtr<mirror::String> str = object->AsString();
Alex Light3e36a9c2018-06-19 09:45:05 -0700654 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
655 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
656 }
657 }
658}
659
660void JitCodeCache::FillRootTable(uint8_t* roots_data,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100661 const std::vector<Handle<mirror::Object>>& roots) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000662 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Vladimir Markoac3ac682018-09-20 11:01:43 +0100663 const uint32_t length = roots.size();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000664 // Put all roots in `roots_data`.
665 for (uint32_t i = 0; i < length; ++i) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100666 ObjPtr<mirror::Object> object = roots[i].Get();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000667 gc_roots[i] = GcRoot<mirror::Object>(object);
668 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000669}
670
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100671static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000672 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
673 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
674 uint32_t roots = GetNumberOfRoots(data);
675 if (number_of_roots != nullptr) {
676 *number_of_roots = roots;
677 }
678 return data - ComputeRootTableSize(roots);
679}
680
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100681// Use a sentinel for marking entries in the JIT table that have been cleared.
682// This helps diagnosing in case the compiled code tries to wrongly access such
683// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700684static mirror::Class* const weak_sentinel =
685 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100686
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000687// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100688static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
689 IsMarkedVisitor* visitor,
690 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000691 REQUIRES_SHARED(Locks::mutator_lock_) {
692 // This does not need a read barrier because this is called by GC.
693 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100694 if (cls != nullptr && cls != weak_sentinel) {
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700695 DCHECK((cls->IsClass<kDefaultVerifyFlags>()));
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000696 // Look at the classloader of the class to know if it has been unloaded.
697 // This does not need a read barrier because this is called by GC.
698 mirror::Object* class_loader =
699 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
700 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
701 // The class loader is live, update the entry if the class has moved.
702 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
703 // Note that new_object can be null for CMS and newly allocated objects.
704 if (new_cls != nullptr && new_cls != cls) {
705 *root_ptr = GcRoot<mirror::Class>(new_cls);
706 }
707 } else {
708 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100709 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000710 }
711 }
712}
713
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000714void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
715 MutexLock mu(Thread::Current(), lock_);
716 for (const auto& entry : method_code_map_) {
717 uint32_t number_of_roots = 0;
718 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
719 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
720 for (uint32_t i = 0; i < number_of_roots; ++i) {
721 // This does not need a read barrier because this is called by GC.
722 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100723 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000724 // entry got deleted in a previous sweep.
725 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
726 mirror::Object* new_object = visitor->IsMarked(object);
727 // We know the string is marked because it's a strongly-interned string that
728 // is always alive. The IsMarked implementation of the CMS collector returns
729 // null for newly allocated objects, but we know those haven't moved. Therefore,
730 // only update the entry if we get a different non-null string.
731 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
732 // out of the weak access/creation pause. b/32167580
733 if (new_object != nullptr && new_object != object) {
734 DCHECK(new_object->IsString());
735 roots[i] = GcRoot<mirror::Object>(new_object);
736 }
737 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100738 ProcessWeakClass(
739 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000740 }
741 }
742 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000743 // Walk over inline caches to clear entries containing unloaded classes.
744 for (ProfilingInfo* info : profiling_infos_) {
745 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
746 InlineCache* cache = &info->cache_[i];
747 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100748 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000749 }
750 }
751 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000752}
753
Orion Hodson607624f2018-05-11 10:10:46 +0100754void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100755 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000756 // Notify native debugger that we are about to remove the code.
757 // It does nothing if we are not using native debugger.
David Srbeckyfb3de3d2018-01-29 16:11:49 +0000758 MutexLock mu(Thread::Current(), *Locks::native_debug_interface_lock_);
David Srbecky440a9b32018-02-15 17:47:29 +0000759 RemoveNativeDebugInfoForJit(code_ptr);
Vladimir Marko2196c652017-11-30 16:16:07 +0000760 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
761 FreeData(GetRootTable(code_ptr));
762 } // else this is a JNI stub without any data.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100763
764 uint8_t* code_allocation = reinterpret_cast<uint8_t*>(allocation);
765 if (HasDualCodeMapping()) {
766 code_allocation = TranslateAddress(code_allocation, exec_pages_, non_exec_pages_);
767 }
768
769 FreeCode(code_allocation);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100770}
771
Mingyao Yang063fc772016-08-02 11:02:54 -0700772void JitCodeCache::FreeAllMethodHeaders(
773 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700774 // We need to remove entries in method_headers from CHA dependencies
775 // first since once we do FreeCode() below, the memory can be reused
776 // so it's possible for the same method_header to start representing
777 // different compile code.
778 MutexLock mu(Thread::Current(), lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000779 {
780 MutexLock mu2(Thread::Current(), *Locks::cha_lock_);
781 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
782 ->RemoveDependentsWithMethodHeaders(method_headers);
783 }
784
Calin Juravle016fcbe22018-05-03 19:47:35 -0700785 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700786 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodson607624f2018-05-11 10:10:46 +0100787 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700788 }
789}
790
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100791void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800792 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700793 // We use a set to first collect all method_headers whose code need to be
794 // removed. We need to free the underlying code after we remove CHA dependencies
795 // for entries in this set. And it's more efficient to iterate through
796 // the CHA dependency map just once with an unordered_set.
797 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000798 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700799 MutexLock mu(self, lock_);
800 // We do not check if a code cache GC is in progress, as this method comes
801 // with the classlinker_classes_lock_ held, and suspending ourselves could
802 // lead to a deadlock.
803 {
Calin Juravle016fcbe22018-05-03 19:47:35 -0700804 ScopedCodeCacheWrite scc(this);
Vladimir Marko2196c652017-11-30 16:16:07 +0000805 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
806 it->second.RemoveMethodsIn(alloc);
807 if (it->second.GetMethods().empty()) {
808 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
809 it = jni_stubs_map_.erase(it);
810 } else {
811 it->first.UpdateShorty(it->second.GetMethods().front());
812 ++it;
813 }
814 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700815 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
816 if (alloc.ContainsUnsafe(it->second)) {
817 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
818 it = method_code_map_.erase(it);
819 } else {
820 ++it;
821 }
822 }
823 }
824 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
825 if (alloc.ContainsUnsafe(it->first)) {
826 // Note that the code has already been pushed to method_headers in the loop
827 // above and is going to be removed in FreeCode() below.
828 it = osr_code_map_.erase(it);
829 } else {
830 ++it;
831 }
832 }
833 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
834 ProfilingInfo* info = *it;
835 if (alloc.ContainsUnsafe(info->GetMethod())) {
836 info->GetMethod()->SetProfilingInfo(nullptr);
837 FreeData(reinterpret_cast<uint8_t*>(info));
838 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000839 } else {
840 ++it;
841 }
842 }
843 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700844 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100845}
846
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000847bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
848 return kUseReadBarrier
849 ? self->GetWeakRefAccessEnabled()
Orion Hodson88591fe2018-03-06 13:35:43 +0000850 : is_weak_access_enabled_.load(std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000851}
852
853void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
854 if (IsWeakAccessEnabled(self)) {
855 return;
856 }
857 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000858 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000859 while (!IsWeakAccessEnabled(self)) {
860 inline_cache_cond_.Wait(self);
861 }
862}
863
864void JitCodeCache::BroadcastForInlineCacheAccess() {
865 Thread* self = Thread::Current();
866 MutexLock mu(self, lock_);
867 inline_cache_cond_.Broadcast(self);
868}
869
870void JitCodeCache::AllowInlineCacheAccess() {
871 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000872 is_weak_access_enabled_.store(true, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000873 BroadcastForInlineCacheAccess();
874}
875
876void JitCodeCache::DisallowInlineCacheAccess() {
877 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000878 is_weak_access_enabled_.store(false, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000879}
880
881void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
882 Handle<mirror::ObjectArray<mirror::Class>> array) {
883 WaitUntilInlineCacheAccessible(Thread::Current());
884 // Note that we don't need to lock `lock_` here, the compiler calling
885 // this method has already ensured the inline cache will not be deleted.
886 for (size_t in_cache = 0, in_array = 0;
887 in_cache < InlineCache::kIndividualCacheSize;
888 ++in_cache) {
889 mirror::Class* object = ic.classes_[in_cache].Read();
890 if (object != nullptr) {
891 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000892 }
893 }
894}
895
David Srbeckye36e7f22018-11-14 14:21:23 +0000896static void ClearMethodCounter(ArtMethod* method, bool was_warm)
897 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf044c222017-05-31 15:27:54 -0700898 if (was_warm) {
Vladimir Markoc945e0d2018-07-18 17:26:45 +0100899 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700900 }
901 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
902 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100903 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
904 // the warmup threshold is 1.
905 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
906 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700907}
908
Alex Light33b7b5d2018-08-07 19:13:51 +0000909void JitCodeCache::WaitForPotentialCollectionToCompleteRunnable(Thread* self) {
910 while (collection_in_progress_) {
911 lock_.Unlock(self);
912 {
913 ScopedThreadSuspension sts(self, kSuspended);
914 MutexLock mu(self, lock_);
915 WaitForPotentialCollectionToComplete(self);
916 }
917 lock_.Lock(self);
918 }
919}
920
Orion Hodson1d3fd082018-09-28 09:38:35 +0100921const MemMap* JitCodeCache::GetUpdatableCodeMapping() const {
922 if (HasDualCodeMapping()) {
923 return &non_exec_pages_;
924 } else if (HasCodeMapping()) {
925 return &exec_pages_;
926 } else {
927 return nullptr;
928 }
929}
930
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100931uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
932 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000933 uint8_t* stack_map,
934 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100935 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000936 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100937 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000938 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100939 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700940 bool has_should_deoptimize_flag,
941 const ArenaSet<ArtMethod*>&
942 cha_single_implementation_list) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000943 DCHECK(!method->IsNative() || !osr);
Alex Light33b7b5d2018-08-07 19:13:51 +0000944
945 if (!method->IsNative()) {
946 // We need to do this before grabbing the lock_ because it needs to be able to see the string
947 // InternTable. Native methods do not have roots.
948 DCheckRootsAreValid(roots);
949 }
950
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100951 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100952 uint8_t* code_ptr = nullptr;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100953
Alex Light33b7b5d2018-08-07 19:13:51 +0000954 MutexLock mu(self, lock_);
955 // We need to make sure that there will be no jit-gcs going on and wait for any ongoing one to
956 // finish.
957 WaitForPotentialCollectionToCompleteRunnable(self);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100958 {
Alex Light33b7b5d2018-08-07 19:13:51 +0000959 ScopedCodeCacheWrite scc(this);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100960
961 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
962 // Ensure the header ends up at expected instruction alignment.
963 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
964 size_t total_size = header_size + code_size;
965
966 // AllocateCode allocates memory in non-executable region for alignment header and code. The
967 // header size may include alignment padding.
968 uint8_t* nox_memory = AllocateCode(total_size);
969 if (nox_memory == nullptr) {
Alex Light33b7b5d2018-08-07 19:13:51 +0000970 return nullptr;
971 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000972
Orion Hodson1d3fd082018-09-28 09:38:35 +0100973 // code_ptr points to non-executable code.
974 code_ptr = nox_memory + header_size;
Alex Light33b7b5d2018-08-07 19:13:51 +0000975 std::copy(code, code + code_size, code_ptr);
976 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100977
978 // From here code_ptr points to executable code.
979 if (HasDualCodeMapping()) {
980 code_ptr = TranslateAddress(code_ptr, non_exec_pages_, exec_pages_);
981 }
982
Alex Light33b7b5d2018-08-07 19:13:51 +0000983 new (method_header) OatQuickMethodHeader(
984 (stack_map != nullptr) ? code_ptr - stack_map : 0u,
985 code_size);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100986
987 DCHECK(!Runtime::Current()->IsAotCompiler());
988 if (has_should_deoptimize_flag) {
989 method_header->SetHasShouldDeoptimizeFlag();
990 }
991
992 // Update method_header pointer to executable code region.
993 if (HasDualCodeMapping()) {
994 method_header = TranslateAddress(method_header, non_exec_pages_, exec_pages_);
995 }
996
997 // Both instruction and data caches need flushing to the point of unification where both share
998 // a common view of memory. Flushing the data cache ensures the dirty cachelines from the
999 // newly added code are written out to the point of unification. Flushing the instruction
1000 // cache ensures the newly written code will be fetched from the point of unification before
1001 // use. Memory in the code cache is re-cycled as code is added and removed. The flushes
1002 // prevent stale code from residing in the instruction cache.
1003 //
1004 // Caches are flushed before write permission is removed because some ARMv8 Qualcomm kernels
1005 // may trigger a segfault if a page fault occurs when requesting a cache maintenance
1006 // operation. This is a kernel bug that we need to work around until affected devices
1007 // (e.g. Nexus 5X and 6P) stop being supported or their kernels are fixed.
Alex Light33b7b5d2018-08-07 19:13:51 +00001008 //
1009 // For reference, this behavior is caused by this commit:
1010 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
Orion Hodson1d3fd082018-09-28 09:38:35 +01001011 //
1012 if (HasDualCodeMapping()) {
1013 // Flush the data cache lines associated with the non-executable copy of the code just added.
1014 FlushDataCache(nox_memory, nox_memory + total_size);
1015 }
1016 // FlushInstructionCache() flushes both data and instruction caches lines. The cacheline range
1017 // flushed is for the executable mapping of the code just added.
Orion Hodson38d29fd2018-09-07 12:58:37 +01001018 FlushInstructionCache(code_ptr, code_ptr + code_size);
Orion Hodsonf2331362018-07-11 15:14:10 +01001019
1020 // Ensure CPU instruction pipelines are flushed for all cores. This is necessary for
1021 // correctness as code may still be in instruction pipelines despite the i-cache flush. It is
1022 // not safe to assume that changing permissions with mprotect (RX->RWX->RX) will cause a TLB
1023 // shootdown (incidentally invalidating the CPU pipelines by sending an IPI to all cores to
1024 // notify them of the TLB invalidation). Some architectures, notably ARM and ARM64, have
1025 // hardware support that broadcasts TLB invalidations and so their kernels have no software
Orion Hodson1d3fd082018-09-28 09:38:35 +01001026 // based TLB shootdown. The sync-core flavor of membarrier was introduced in Linux 4.16 to
1027 // address this (see mbarrier(2)). The membarrier here will fail on prior kernels and on
1028 // platforms lacking the appropriate support.
Orion Hodson563ada22018-09-04 11:28:31 +01001029 art::membarrier(art::MembarrierCommand::kPrivateExpeditedSyncCore);
Orion Hodson38d29fd2018-09-07 12:58:37 +01001030
Nicolas Geoffray0a522232016-01-19 09:34:58 +00001031 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001032 }
Orion Hodson1d3fd082018-09-28 09:38:35 +01001033
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001034 // We need to update the entry point in the runnable state for the instrumentation.
1035 {
Alex Light33b7b5d2018-08-07 19:13:51 +00001036 // The following needs to be guarded by cha_lock_ also. Otherwise it's possible that the
1037 // compiled code is considered invalidated by some class linking, but below we still make the
1038 // compiled code valid for the method. Need cha_lock_ for checking all single-implementation
1039 // flags and register dependencies.
Mingyao Yang063fc772016-08-02 11:02:54 -07001040 MutexLock cha_mu(self, *Locks::cha_lock_);
1041 bool single_impl_still_valid = true;
1042 for (ArtMethod* single_impl : cha_single_implementation_list) {
1043 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001044 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
1045 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -07001046 single_impl_still_valid = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001047 ClearMethodCounter(method, /*was_warm=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -07001048 break;
1049 }
1050 }
1051
1052 // Discard the code if any single-implementation assumptions are now invalid.
1053 if (!single_impl_still_valid) {
1054 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
1055 return nullptr;
1056 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00001057 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -08001058 << "Should not be using cha on debuggable apps/runs!";
1059
Mingyao Yang063fc772016-08-02 11:02:54 -07001060 for (ArtMethod* single_impl : cha_single_implementation_list) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07001061 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()->AddDependency(
Mingyao Yang063fc772016-08-02 11:02:54 -07001062 single_impl, method, method_header);
1063 }
1064
Vladimir Marko2196c652017-11-30 16:16:07 +00001065 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001066 auto it = jni_stubs_map_.find(JniStubKey(method));
1067 DCHECK(it != jni_stubs_map_.end())
1068 << "Entry inserted in NotifyCompilationOf() should be alive.";
1069 JniStubData* data = &it->second;
1070 DCHECK(ContainsElement(data->GetMethods(), method))
1071 << "Entry inserted in NotifyCompilationOf() should contain this method.";
1072 data->SetCode(code_ptr);
1073 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
1074 for (ArtMethod* m : data->GetMethods()) {
1075 instrum->UpdateMethodsCode(m, method_header->GetEntryPoint());
1076 }
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001077 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +00001078 // Fill the root table before updating the entry point.
1079 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
1080 DCHECK_LE(roots_data, stack_map);
1081 FillRootTable(roots_data, roots);
1082 {
1083 // Flush data cache, as compiled code references literals in it.
Orion Hodson38d29fd2018-09-07 12:58:37 +01001084 FlushDataCache(roots_data, roots_data + data_size);
Vladimir Marko2196c652017-11-30 16:16:07 +00001085 }
1086 method_code_map_.Put(code_ptr, method);
1087 if (osr) {
1088 number_of_osr_compilations_++;
1089 osr_code_map_.Put(method, code_ptr);
1090 } else {
1091 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1092 method, method_header->GetEntryPoint());
1093 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001094 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001095 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001096 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -07001097 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001098 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1099 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
1100 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -07001101 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
1102 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001103 histogram_code_memory_use_.AddValue(code_size);
1104 if (code_size > kCodeSizeLogThreshold) {
1105 LOG(INFO) << "JIT allocated "
1106 << PrettySize(code_size)
1107 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -07001108 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001109 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001110 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001111
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001112 return reinterpret_cast<uint8_t*>(method_header);
1113}
1114
1115size_t JitCodeCache::CodeCacheSize() {
1116 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001117 return CodeCacheSizeLocked();
1118}
1119
Orion Hodsoneced6922017-06-01 10:54:28 +01001120bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001121 // This function is used only for testing and only with non-native methods.
1122 CHECK(!method->IsNative());
1123
Orion Hodsoneced6922017-06-01 10:54:28 +01001124 MutexLock mu(Thread::Current(), lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +01001125
Vladimir Marko2196c652017-11-30 16:16:07 +00001126 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
1127 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +01001128
1129 if (!in_cache) {
1130 return false;
1131 }
1132
David Srbeckye36e7f22018-11-14 14:21:23 +00001133 method->SetCounter(0);
Orion Hodsoneced6922017-06-01 10:54:28 +01001134 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1135 method, GetQuickToInterpreterBridge());
1136 VLOG(jit)
1137 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
1138 << ArtMethod::PrettyMethod(method) << "@" << method
1139 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1140 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
1141 return true;
1142}
1143
Vladimir Marko2196c652017-11-30 16:16:07 +00001144bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
1145 if (LIKELY(!method->IsNative())) {
1146 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1147 if (info != nullptr) {
1148 RemoveElement(profiling_infos_, info);
1149 }
1150 method->SetProfilingInfo(nullptr);
1151 }
1152
1153 bool in_cache = false;
Calin Juravle016fcbe22018-05-03 19:47:35 -07001154 ScopedCodeCacheWrite ccw(this);
Vladimir Marko2196c652017-11-30 16:16:07 +00001155 if (UNLIKELY(method->IsNative())) {
1156 auto it = jni_stubs_map_.find(JniStubKey(method));
1157 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
1158 in_cache = true;
1159 if (it->second.GetMethods().empty()) {
1160 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +01001161 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +00001162 }
1163 jni_stubs_map_.erase(it);
1164 } else {
1165 it->first.UpdateShorty(it->second.GetMethods().front());
1166 }
1167 }
1168 } else {
1169 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1170 if (it->second == method) {
1171 in_cache = true;
1172 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +01001173 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +00001174 }
1175 it = method_code_map_.erase(it);
1176 } else {
1177 ++it;
1178 }
1179 }
1180
1181 auto osr_it = osr_code_map_.find(method);
1182 if (osr_it != osr_code_map_.end()) {
1183 osr_code_map_.erase(osr_it);
1184 }
1185 }
1186
1187 return in_cache;
1188}
1189
Alex Lightdba61482016-12-21 08:20:29 -08001190// This notifies the code cache that the given method has been redefined and that it should remove
1191// any cached information it has on the method. All threads must be suspended before calling this
1192// method. The compiled code for the method (if there is any) must not be in any threads call stack.
1193void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
1194 MutexLock mu(Thread::Current(), lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001195 RemoveMethodLocked(method, /* release_memory= */ true);
Alex Lightdba61482016-12-21 08:20:29 -08001196}
1197
1198// This invalidates old_method. Once this function returns one can no longer use old_method to
1199// execute code unless it is fixed up. This fixup will happen later in the process of installing a
1200// class redefinition.
1201// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
1202// shouldn't be used since it is no longer logically in the jit code cache.
1203// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
1204void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001205 MutexLock mu(Thread::Current(), lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +00001206 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001207 // Update methods in jni_stubs_map_.
1208 for (auto& entry : jni_stubs_map_) {
1209 JniStubData& data = entry.second;
1210 data.MoveObsoleteMethod(old_method, new_method);
1211 }
Alex Lighteee0bd42017-02-14 15:31:45 +00001212 return;
1213 }
Alex Lightdba61482016-12-21 08:20:29 -08001214 // Update ProfilingInfo to the new one and remove it from the old_method.
1215 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
1216 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
1217 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
1218 old_method->SetProfilingInfo(nullptr);
1219 // Since the JIT should be paused and all threads suspended by the time this is called these
1220 // checks should always pass.
1221 DCHECK(!info->IsInUseByCompiler());
1222 new_method->SetProfilingInfo(info);
Alex Light2d441b12018-06-08 15:33:21 -07001223 // Get rid of the old saved entrypoint if it is there.
1224 info->SetSavedEntryPoint(nullptr);
Alex Lightdba61482016-12-21 08:20:29 -08001225 info->method_ = new_method;
1226 }
1227 // Update method_code_map_ to point to the new method.
1228 for (auto& it : method_code_map_) {
1229 if (it.second == old_method) {
1230 it.second = new_method;
1231 }
1232 }
1233 // Update osr_code_map_ to point to the new method.
1234 auto code_map = osr_code_map_.find(old_method);
1235 if (code_map != osr_code_map_.end()) {
1236 osr_code_map_.Put(new_method, code_map->second);
1237 osr_code_map_.erase(old_method);
1238 }
1239}
1240
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001241size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001242 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001243}
1244
1245size_t JitCodeCache::DataCacheSize() {
1246 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001247 return DataCacheSizeLocked();
1248}
1249
1250size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001251 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001252}
1253
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001254void JitCodeCache::ClearData(Thread* self,
1255 uint8_t* stack_map_data,
1256 uint8_t* roots_data) {
1257 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001258 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001259 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001260}
1261
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001262size_t JitCodeCache::ReserveData(Thread* self,
1263 size_t stack_map_size,
1264 size_t number_of_roots,
1265 ArtMethod* method,
1266 uint8_t** stack_map_data,
1267 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001268 size_t table_size = ComputeRootTableSize(number_of_roots);
David Srbecky8cd54542018-07-15 23:58:44 +01001269 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001270 uint8_t* result = nullptr;
1271
1272 {
1273 ScopedThreadSuspension sts(self, kSuspended);
1274 MutexLock mu(self, lock_);
1275 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001276 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001277 }
1278
1279 if (result == nullptr) {
1280 // Retry.
1281 GarbageCollectCache(self);
1282 ScopedThreadSuspension sts(self, kSuspended);
1283 MutexLock mu(self, lock_);
1284 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001285 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001286 }
1287
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001288 MutexLock mu(self, lock_);
1289 histogram_stack_map_memory_use_.AddValue(size);
1290 if (size > kStackMapSizeLogThreshold) {
1291 LOG(INFO) << "JIT allocated "
1292 << PrettySize(size)
1293 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001294 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001295 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001296 if (result != nullptr) {
1297 *roots_data = result;
1298 *stack_map_data = result + table_size;
1299 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001300 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001301 } else {
1302 *roots_data = nullptr;
1303 *stack_map_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001304 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001305 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001306}
1307
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001308class MarkCodeClosure final : public Closure {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001309 public:
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001310 MarkCodeClosure(JitCodeCache* code_cache, CodeCacheBitmap* bitmap, Barrier* barrier)
1311 : code_cache_(code_cache), bitmap_(bitmap), barrier_(barrier) {}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001312
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001313 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001314 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001315 DCHECK(thread == Thread::Current() || thread->IsSuspended());
Andreas Gampec7d878d2018-11-19 18:42:06 +00001316 StackVisitor::WalkStack(
1317 [&](const art::StackVisitor* stack_visitor) {
1318 const OatQuickMethodHeader* method_header =
1319 stack_visitor->GetCurrentOatQuickMethodHeader();
1320 if (method_header == nullptr) {
1321 return true;
1322 }
1323 const void* code = method_header->GetCode();
1324 if (code_cache_->ContainsPc(code)) {
1325 // Use the atomic set version, as multiple threads are executing this code.
1326 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1327 }
1328 return true;
1329 },
1330 thread,
1331 /* context= */ nullptr,
1332 art::StackVisitor::StackWalkKind::kSkipInlinedFrames);
1333
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001334 if (kIsDebugBuild) {
1335 // The stack walking code queries the side instrumentation stack if it
1336 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1337 // must have been seen. We sanity check this below.
1338 for (const instrumentation::InstrumentationStackFrame& frame
1339 : *thread->GetInstrumentationStack()) {
1340 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1341 // its stack frame, it is not the method owning return_pc_. We just pass null to
1342 // LookupMethodHeader: the method is only checked against in debug builds.
1343 OatQuickMethodHeader* method_header =
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001344 code_cache_->LookupMethodHeader(frame.return_pc_, /* method= */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001345 if (method_header != nullptr) {
1346 const void* code = method_header->GetCode();
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001347 CHECK(bitmap_->Test(FromCodeToAllocation(code)));
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001348 }
1349 }
1350 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001351 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001352 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001353
1354 private:
1355 JitCodeCache* const code_cache_;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001356 CodeCacheBitmap* const bitmap_;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001357 Barrier* const barrier_;
1358};
1359
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001360void JitCodeCache::NotifyCollectionDone(Thread* self) {
1361 collection_in_progress_ = false;
1362 lock_cond_.Broadcast(self);
1363}
1364
1365void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001366 size_t data_space_footprint = new_footprint / kCodeAndDataCapacityDivider;
1367 DCHECK(IsAlignedParam(data_space_footprint, kPageSize));
1368 DCHECK_EQ(data_space_footprint * kCodeAndDataCapacityDivider, new_footprint);
1369 mspace_set_footprint_limit(data_mspace_, data_space_footprint);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001370 if (HasCodeMapping()) {
Calin Juravle016fcbe22018-05-03 19:47:35 -07001371 ScopedCodeCacheWrite scc(this);
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001372 mspace_set_footprint_limit(exec_mspace_, new_footprint - data_space_footprint);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001373 }
1374}
1375
1376bool JitCodeCache::IncreaseCodeCacheCapacity() {
1377 if (current_capacity_ == max_capacity_) {
1378 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001379 }
1380
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001381 // Double the capacity if we're below 1MB, or increase it by 1MB if
1382 // we're above.
1383 if (current_capacity_ < 1 * MB) {
1384 current_capacity_ *= 2;
1385 } else {
1386 current_capacity_ += 1 * MB;
1387 }
1388 if (current_capacity_ > max_capacity_) {
1389 current_capacity_ = max_capacity_;
1390 }
1391
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001392 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001393
1394 SetFootprintLimit(current_capacity_);
1395
1396 return true;
1397}
1398
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001399void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1400 Barrier barrier(0);
1401 size_t threads_running_checkpoint = 0;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001402 MarkCodeClosure closure(this, GetLiveBitmap(), &barrier);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001403 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1404 // Now that we have run our checkpoint, move to a suspended state and wait
1405 // for other threads to run the checkpoint.
1406 ScopedThreadSuspension sts(self, kSuspended);
1407 if (threads_running_checkpoint != 0) {
1408 barrier.Increment(self, threads_running_checkpoint);
1409 }
1410}
1411
Nicolas Geoffray35122442016-03-02 12:05:30 +00001412bool JitCodeCache::ShouldDoFullCollection() {
1413 if (current_capacity_ == max_capacity_) {
1414 // Always do a full collection when the code cache is full.
1415 return true;
1416 } else if (current_capacity_ < kReservedCapacity) {
1417 // Always do partial collection when the code cache size is below the reserved
1418 // capacity.
1419 return false;
1420 } else if (last_collection_increased_code_cache_) {
1421 // This time do a full collection.
1422 return true;
1423 } else {
1424 // This time do a partial collection.
1425 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001426 }
1427}
1428
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001429void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001430 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001431 if (!garbage_collect_code_) {
1432 MutexLock mu(self, lock_);
1433 IncreaseCodeCacheCapacity();
1434 return;
1435 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001436
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001437 // Wait for an existing collection, or let everyone know we are starting one.
1438 {
1439 ScopedThreadSuspension sts(self, kSuspended);
1440 MutexLock mu(self, lock_);
1441 if (WaitForPotentialCollectionToComplete(self)) {
1442 return;
1443 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001444 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001445 live_bitmap_.reset(CodeCacheBitmap::Create(
1446 "code-cache-bitmap",
Orion Hodson1d3fd082018-09-28 09:38:35 +01001447 reinterpret_cast<uintptr_t>(exec_pages_.Begin()),
1448 reinterpret_cast<uintptr_t>(exec_pages_.Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001449 collection_in_progress_ = true;
1450 }
1451 }
1452
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001453 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001454 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001455 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001456
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001457 bool do_full_collection = false;
1458 {
1459 MutexLock mu(self, lock_);
1460 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001461 }
1462
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001463 VLOG(jit) << "Do "
1464 << (do_full_collection ? "full" : "partial")
1465 << " code cache collection, code="
1466 << PrettySize(CodeCacheSize())
1467 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001468
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001469 DoCollection(self, /* collect_profiling_info= */ do_full_collection);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001470
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001471 VLOG(jit) << "After code cache collection, code="
1472 << PrettySize(CodeCacheSize())
1473 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001474
1475 {
1476 MutexLock mu(self, lock_);
1477
1478 // Increase the code cache only when we do partial collections.
1479 // TODO: base this strategy on how full the code cache is?
1480 if (do_full_collection) {
1481 last_collection_increased_code_cache_ = false;
1482 } else {
1483 last_collection_increased_code_cache_ = true;
1484 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001485 }
1486
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001487 bool next_collection_will_be_full = ShouldDoFullCollection();
1488
1489 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001490 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001491 // Save the entry point of methods we have compiled, and update the entry
1492 // point of those methods to the interpreter. If the method is invoked, the
1493 // interpreter will update its entry point to the compiled code and call it.
1494 for (ProfilingInfo* info : profiling_infos_) {
1495 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1496 if (ContainsPc(entry_point)) {
1497 info->SetSavedEntryPoint(entry_point);
Vladimir Marko2196c652017-11-30 16:16:07 +00001498 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001499 // class of the method. We may be concurrently running a GC which makes accessing
1500 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1501 // checked that the current entry point is JIT compiled code.
1502 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001503 }
1504 }
1505
1506 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Vladimir Marko2196c652017-11-30 16:16:07 +00001507
1508 // Change entry points of native methods back to the GenericJNI entrypoint.
1509 for (const auto& entry : jni_stubs_map_) {
1510 const JniStubData& data = entry.second;
1511 if (!data.IsCompiled()) {
1512 continue;
1513 }
1514 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1515 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1516 const OatQuickMethodHeader* method_header =
1517 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1518 for (ArtMethod* method : data.GetMethods()) {
1519 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1520 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1521 method->SetCounter(new_counter);
1522 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1523 }
1524 }
1525 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001526 }
1527 live_bitmap_.reset(nullptr);
1528 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001529 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001530 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001531 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001532}
1533
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001534void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001535 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001536 std::unordered_set<OatQuickMethodHeader*> method_headers;
1537 {
1538 MutexLock mu(self, lock_);
Calin Juravle016fcbe22018-05-03 19:47:35 -07001539 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -07001540 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001541 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1542 JniStubData* data = &it->second;
1543 if (!data->IsCompiled() || GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
1544 ++it;
1545 } else {
1546 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1547 it = jni_stubs_map_.erase(it);
1548 }
1549 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001550 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1551 const void* code_ptr = it->first;
1552 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1553 if (GetLiveBitmap()->Test(allocation)) {
1554 ++it;
1555 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001556 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1557 method_headers.insert(header);
Mingyao Yang063fc772016-08-02 11:02:54 -07001558 it = method_code_map_.erase(it);
1559 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001560 }
1561 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001562 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001563}
1564
1565void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001566 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001567 {
1568 MutexLock mu(self, lock_);
1569 if (collect_profiling_info) {
1570 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1571 // Also remove the saved entry point from the ProfilingInfo objects.
1572 for (ProfilingInfo* info : profiling_infos_) {
1573 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001574 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001575 info->GetMethod()->SetProfilingInfo(nullptr);
1576 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001577
1578 if (info->GetSavedEntryPoint() != nullptr) {
1579 info->SetSavedEntryPoint(nullptr);
1580 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001581 // give it a chance to be hot again.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001582 ClearMethodCounter(info->GetMethod(), /*was_warm=*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001583 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001584 }
1585 } else if (kIsDebugBuild) {
1586 // Sanity check that the profiling infos do not have a dangling entry point.
1587 for (ProfilingInfo* info : profiling_infos_) {
1588 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001589 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001590 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001591
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001592 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1593 // an entry point is either:
1594 // - an osr compiled code, that will be removed if not in a thread call stack.
1595 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001596 for (const auto& entry : jni_stubs_map_) {
1597 const JniStubData& data = entry.second;
1598 const void* code_ptr = data.GetCode();
1599 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1600 for (ArtMethod* method : data.GetMethods()) {
1601 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1602 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1603 break;
1604 }
1605 }
1606 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001607 for (const auto& it : method_code_map_) {
1608 ArtMethod* method = it.second;
1609 const void* code_ptr = it.first;
1610 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1611 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1612 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1613 }
1614 }
1615
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001616 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001617 // on thread stacks).
1618 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001619 }
1620
1621 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001622 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001623
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001624 // At this point, mutator threads are still running, and entrypoints of methods can
1625 // change. We do know they cannot change to a code cache entry that is not marked,
1626 // therefore we can safely remove those entries.
1627 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001628
Nicolas Geoffray35122442016-03-02 12:05:30 +00001629 if (collect_profiling_info) {
1630 MutexLock mu(self, lock_);
1631 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001632 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001633 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001634 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001635 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1636 // that the compiled code would not get revived. As mutator threads run concurrently,
1637 // they may have revived the compiled code, and now we are in the situation where
1638 // a method has compiled code but no ProfilingInfo.
1639 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1640 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001641 if (ContainsPc(ptr) &&
1642 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001643 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001644 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001645 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001646 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001647 return true;
1648 }
1649 return false;
1650 });
1651 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001652 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001653 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001654}
1655
Nicolas Geoffray35122442016-03-02 12:05:30 +00001656bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001657 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001658 // Check that methods we have compiled do have a ProfilingInfo object. We would
1659 // have memory leaks of compiled code otherwise.
1660 for (const auto& it : method_code_map_) {
1661 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001662 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001663 const void* code_ptr = it.first;
1664 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1665 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1666 // If the code is not dead, then we have a problem. Note that this can even
1667 // happen just after a collection, as mutator threads are running in parallel
1668 // and could deoptimize an existing compiled code.
1669 return false;
1670 }
1671 }
1672 }
1673 return true;
1674}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001675
1676OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001677 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1678 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001679 // On Thumb-2, the pc is offset by one.
1680 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001681 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001682 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1683 return nullptr;
1684 }
1685
Vladimir Marko2196c652017-11-30 16:16:07 +00001686 if (!kIsDebugBuild) {
1687 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1688 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001689 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001690
Vladimir Marko2196c652017-11-30 16:16:07 +00001691 MutexLock mu(Thread::Current(), lock_);
1692 OatQuickMethodHeader* method_header = nullptr;
1693 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1694 if (method != nullptr && UNLIKELY(method->IsNative())) {
1695 auto it = jni_stubs_map_.find(JniStubKey(method));
1696 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1697 return nullptr;
1698 }
1699 const void* code_ptr = it->second.GetCode();
1700 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1701 if (!method_header->Contains(pc)) {
1702 return nullptr;
1703 }
1704 } else {
1705 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1706 if (it != method_code_map_.begin()) {
1707 --it;
1708 const void* code_ptr = it->first;
1709 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1710 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1711 found_method = it->second;
1712 }
1713 }
1714 if (method_header == nullptr && method == nullptr) {
1715 // Scan all compiled JNI stubs as well. This slow search is used only
1716 // for checks in debug build, for release builds the `method` is not null.
1717 for (auto&& entry : jni_stubs_map_) {
1718 const JniStubData& data = entry.second;
1719 if (data.IsCompiled() &&
1720 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1721 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1722 }
1723 }
1724 }
1725 if (method_header == nullptr) {
1726 return nullptr;
1727 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001728 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001729
1730 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001731 // When we are walking the stack to redefine classes and creating obsolete methods it is
1732 // possible that we might have updated the method_code_map by making this method obsolete in a
1733 // previous frame. Therefore we should just check that the non-obsolete version of this method
1734 // is the one we expect. We change to the non-obsolete versions in the error message since the
1735 // obsolete version of the method might not be fully initialized yet. This situation can only
1736 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
Andreas Gampe06c42a52017-07-26 14:17:14 -07001737 // method and it->second should be identical. (See openjdkjvmti/ti_redefine.cc for more
Alex Light1ebe4fe2017-01-30 14:57:11 -08001738 // information.)
Vladimir Marko2196c652017-11-30 16:16:07 +00001739 DCHECK_EQ(found_method->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
Alex Light1ebe4fe2017-01-30 14:57:11 -08001740 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
Vladimir Marko2196c652017-11-30 16:16:07 +00001741 << ArtMethod::PrettyMethod(found_method->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001742 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001743 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001744 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001745}
1746
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001747OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1748 MutexLock mu(Thread::Current(), lock_);
1749 auto it = osr_code_map_.find(method);
1750 if (it == osr_code_map_.end()) {
1751 return nullptr;
1752 }
1753 return OatQuickMethodHeader::FromCodePointer(it->second);
1754}
1755
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001756ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1757 ArtMethod* method,
1758 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001759 bool retry_allocation)
1760 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1761 NO_THREAD_SAFETY_ANALYSIS {
1762 ProfilingInfo* info = nullptr;
1763 if (!retry_allocation) {
1764 // If we are allocating for the interpreter, just try to lock, to avoid
1765 // lock contention with the JIT.
1766 if (lock_.ExclusiveTryLock(self)) {
1767 info = AddProfilingInfoInternal(self, method, entries);
1768 lock_.ExclusiveUnlock(self);
1769 }
1770 } else {
1771 {
1772 MutexLock mu(self, lock_);
1773 info = AddProfilingInfoInternal(self, method, entries);
1774 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001775
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001776 if (info == nullptr) {
1777 GarbageCollectCache(self);
1778 MutexLock mu(self, lock_);
1779 info = AddProfilingInfoInternal(self, method, entries);
1780 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001781 }
1782 return info;
1783}
1784
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001785ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001786 ArtMethod* method,
1787 const std::vector<uint32_t>& entries) {
1788 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001789 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001790 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001791
1792 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001793 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001794 if (info != nullptr) {
1795 return info;
1796 }
1797
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001798 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001799 if (data == nullptr) {
1800 return nullptr;
1801 }
1802 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001803
1804 // Make sure other threads see the data in the profiling info object before the
1805 // store in the ArtMethod's ProfilingInfo pointer.
Orion Hodson27b96762018-03-13 16:06:57 +00001806 std::atomic_thread_fence(std::memory_order_release);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001807
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001808 method->SetProfilingInfo(info);
1809 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001810 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001811 return info;
1812}
1813
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001814// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1815// is already held.
1816void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
Orion Hodson1d3fd082018-09-28 09:38:35 +01001817 if (mspace == exec_mspace_) {
1818 DCHECK(exec_mspace_ != nullptr);
1819 const MemMap* const code_pages = GetUpdatableCodeMapping();
1820 void* result = code_pages->Begin() + exec_end_;
1821 exec_end_ += increment;
1822 return result;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001823 } else {
1824 DCHECK_EQ(data_mspace_, mspace);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001825 void* result = data_pages_.Begin() + data_end_;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001826 data_end_ += increment;
Orion Hodson1d3fd082018-09-28 09:38:35 +01001827 return result;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001828 }
1829}
1830
Calin Juravle99629622016-04-19 16:33:46 +01001831void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001832 std::vector<ProfileMethodInfo>& methods) {
Nicolas Geoffray1afdfe62018-11-21 09:38:10 +00001833 Thread* self = Thread::Current();
1834 WaitUntilInlineCacheAccessible(self);
1835 MutexLock mu(self, lock_);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001836 ScopedTrace trace(__FUNCTION__);
Calin Juravlea39fd982017-05-18 10:15:52 -07001837 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001838 for (const ProfilingInfo* info : profiling_infos_) {
1839 ArtMethod* method = info->GetMethod();
1840 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001841 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1842 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001843 // Skip dex files which are not profiled.
1844 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001845 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001846 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001847
1848 // If the method didn't reach the compilation threshold don't save the inline caches.
1849 // They might be incomplete and cause unnecessary deoptimizations.
1850 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1851 if (method->GetCounter() < jit_compile_threshold) {
1852 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001853 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001854 continue;
1855 }
1856
Calin Juravle940eb0c2017-01-30 19:30:44 -08001857 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001858 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001859 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001860 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001861 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001862 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1863 mirror::Class* cls = cache.classes_[k].Read();
1864 if (cls == nullptr) {
1865 break;
1866 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001867
Calin Juravle13439f02017-02-21 01:17:21 -08001868 // Check if the receiver is in the boot class path or if it's in the
1869 // same class loader as the caller. If not, skip it, as there is not
1870 // much we can do during AOT.
1871 if (!cls->IsBootStrapClassLoaded() &&
1872 caller->GetClassLoader() != cls->GetClassLoader()) {
1873 is_missing_types = true;
1874 continue;
1875 }
1876
Calin Juravle4ca70a32017-02-21 16:22:24 -08001877 const DexFile* class_dex_file = nullptr;
1878 dex::TypeIndex type_index;
1879
1880 if (cls->GetDexCache() == nullptr) {
1881 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001882 // Make a best effort to find the type index in the method's dex file.
1883 // We could search all open dex files but that might turn expensive
1884 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001885 class_dex_file = dex_file;
1886 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1887 } else {
1888 class_dex_file = &(cls->GetDexFile());
1889 type_index = cls->GetDexTypeIndex();
1890 }
1891 if (!type_index.IsValid()) {
1892 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001893 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001894 continue;
1895 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001896 if (ContainsElement(dex_base_locations,
1897 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001898 // Only consider classes from the same apk (including multidex).
1899 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001900 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001901 } else {
1902 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001903 }
1904 }
1905 if (!profile_classes.empty()) {
1906 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001907 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001908 }
1909 }
1910 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001911 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001912 }
1913}
1914
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001915bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1916 MutexLock mu(Thread::Current(), lock_);
1917 return osr_code_map_.find(method) != osr_code_map_.end();
1918}
1919
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001920bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1921 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001922 return false;
1923 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001924
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001925 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001926 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1927 return false;
1928 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001929
Vladimir Marko2196c652017-11-30 16:16:07 +00001930 if (UNLIKELY(method->IsNative())) {
1931 JniStubKey key(method);
1932 auto it = jni_stubs_map_.find(key);
1933 bool new_compilation = false;
1934 if (it == jni_stubs_map_.end()) {
1935 // Create a new entry to mark the stub as being compiled.
1936 it = jni_stubs_map_.Put(key, JniStubData{});
1937 new_compilation = true;
1938 }
1939 JniStubData* data = &it->second;
1940 data->AddMethod(method);
1941 if (data->IsCompiled()) {
1942 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1943 const void* entrypoint = method_header->GetEntryPoint();
1944 // Update also entrypoints of other methods held by the JniStubData.
1945 // We could simply update the entrypoint of `method` but if the last JIT GC has
1946 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1947 // as well change them back as this stub shall not be collected anyway and this
1948 // can avoid a few expensive GenericJNI calls.
1949 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1950 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +00001951 // Call the dedicated method instead of the more generic UpdateMethodsCode, because
1952 // `m` might be in the process of being deleted.
1953 instrumentation->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
Vladimir Marko2196c652017-11-30 16:16:07 +00001954 }
1955 if (collection_in_progress_) {
1956 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1957 }
1958 }
1959 return new_compilation;
1960 } else {
1961 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1962 if (info == nullptr) {
1963 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1964 // Because the counter is not atomic, there are some rare cases where we may not hit the
1965 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001966 ClearMethodCounter(method, /*was_warm=*/ false);
Vladimir Marko2196c652017-11-30 16:16:07 +00001967 return false;
1968 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001969
Vladimir Marko2196c652017-11-30 16:16:07 +00001970 if (info->IsMethodBeingCompiled(osr)) {
1971 return false;
1972 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001973
Vladimir Marko2196c652017-11-30 16:16:07 +00001974 info->SetIsMethodBeingCompiled(true, osr);
1975 return true;
1976 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001977}
1978
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001979ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001980 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001981 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001982 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001983 if (!info->IncrementInlineUse()) {
1984 // Overflow of inlining uses, just bail.
1985 return nullptr;
1986 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001987 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001988 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001989}
1990
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001991void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001992 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001993 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001994 DCHECK(info != nullptr);
1995 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001996}
1997
Vladimir Marko2196c652017-11-30 16:16:07 +00001998void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
1999 DCHECK_EQ(Thread::Current(), self);
2000 MutexLock mu(self, lock_);
2001 if (UNLIKELY(method->IsNative())) {
2002 auto it = jni_stubs_map_.find(JniStubKey(method));
2003 DCHECK(it != jni_stubs_map_.end());
2004 JniStubData* data = &it->second;
2005 DCHECK(ContainsElement(data->GetMethods(), method));
2006 if (UNLIKELY(!data->IsCompiled())) {
2007 // Failed to compile; the JNI compiler never fails, but the cache may be full.
2008 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
2009 } // else CommitCodeInternal() updated entrypoints of all methods in the JniStubData.
2010 } else {
2011 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
2012 DCHECK(info->IsMethodBeingCompiled(osr));
2013 info->SetIsMethodBeingCompiled(false, osr);
2014 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002015}
2016
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00002017void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
2018 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00002019 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07002020 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Alex Light2d441b12018-06-08 15:33:21 -07002021 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00002022 if ((profiling_info != nullptr) &&
2023 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
Alex Light2d441b12018-06-08 15:33:21 -07002024 // When instrumentation is set, the actual entrypoint is the one in the profiling info.
2025 method_entrypoint = profiling_info->GetSavedEntryPoint();
Nicolas Geoffray35122442016-03-02 12:05:30 +00002026 // Prevent future uses of the compiled code.
2027 profiling_info->SetSavedEntryPoint(nullptr);
2028 }
2029
Alex Light2d441b12018-06-08 15:33:21 -07002030 // Clear the method counter if we are running jitted code since we might want to jit this again in
2031 // the future.
2032 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07002033 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07002034 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00002035 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
2036 method, GetQuickToInterpreterBridge());
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002037 ClearMethodCounter(method, /*was_warm=*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00002038 } else {
2039 MutexLock mu(Thread::Current(), lock_);
2040 auto it = osr_code_map_.find(method);
2041 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
2042 // Remove the OSR method, to avoid using it again.
2043 osr_code_map_.erase(it);
2044 }
2045 }
2046}
2047
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002048uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
2049 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
2050 uint8_t* result = reinterpret_cast<uint8_t*>(
Orion Hodson1d3fd082018-09-28 09:38:35 +01002051 mspace_memalign(exec_mspace_, alignment, code_size));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002052 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
2053 // Ensure the header ends up at expected instruction alignment.
2054 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
2055 used_memory_for_code_ += mspace_usable_size(result);
2056 return result;
2057}
2058
Orion Hodsondbd05fe2017-08-10 11:41:35 +01002059void JitCodeCache::FreeCode(uint8_t* code) {
2060 used_memory_for_code_ -= mspace_usable_size(code);
Orion Hodson1d3fd082018-09-28 09:38:35 +01002061 mspace_free(exec_mspace_, code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002062}
2063
2064uint8_t* JitCodeCache::AllocateData(size_t data_size) {
2065 void* result = mspace_malloc(data_mspace_, data_size);
2066 used_memory_for_data_ += mspace_usable_size(result);
2067 return reinterpret_cast<uint8_t*>(result);
2068}
2069
2070void JitCodeCache::FreeData(uint8_t* data) {
2071 used_memory_for_data_ -= mspace_usable_size(data);
2072 mspace_free(data_mspace_, data);
2073}
2074
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002075void JitCodeCache::Dump(std::ostream& os) {
2076 MutexLock mu(Thread::Current(), lock_);
David Srbeckyfb3de3d2018-01-29 16:11:49 +00002077 MutexLock mu2(Thread::Current(), *Locks::native_debug_interface_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002078 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
2079 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
David Srbecky440a9b32018-02-15 17:47:29 +00002080 << "Current JIT mini-debug-info size: " << PrettySize(GetJitNativeDebugInfoMemUsage()) << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002081 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00002082 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002083 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
2084 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
2085 << "Total number of JIT compilations for on stack replacement: "
2086 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002087 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00002088 histogram_stack_map_memory_use_.PrintMemoryUse(os);
2089 histogram_code_memory_use_.PrintMemoryUse(os);
2090 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002091}
2092
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00002093void JitCodeCache::PostForkChildAction(bool is_system_server, bool is_zygote) {
2094 MutexLock mu(Thread::Current(), lock_);
2095 // Currently, we don't expect any compilations from zygote.
2096 CHECK_EQ(number_of_compilations_, 0u);
2097 CHECK_EQ(number_of_osr_compilations_, 0u);
2098 CHECK(jni_stubs_map_.empty());
2099 CHECK(method_code_map_.empty());
2100 CHECK(osr_code_map_.empty());
2101
2102 zygote_data_pages_ = std::move(data_pages_);
2103 zygote_exec_pages_ = std::move(exec_pages_);
2104 zygote_data_mspace_ = data_mspace_;
2105 zygote_exec_mspace_ = exec_mspace_;
2106
2107 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
2108 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
2109
2110 InitializeState(initial_capacity, max_capacity);
2111
2112 std::string error_msg;
2113 if (!InitializeMappings(/* rwx_memory_allowed= */ !is_system_server, is_zygote, &error_msg)) {
2114 LOG(WARNING) << "Could not reset JIT state after zygote fork: " << error_msg;
2115 return;
2116 }
2117
2118 InitializeSpaces();
2119}
2120
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002121} // namespace jit
2122} // namespace art