blob: 7729838601112df268e70341dc20f95fa360e578 [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 Gampe3d477f32018-11-16 16:40:45 +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
Orion Hodson1d3fd082018-09-28 09:38:35 +010068static constexpr int kProtR = PROT_READ;
69static constexpr int kProtRW = PROT_READ | PROT_WRITE;
70static constexpr int kProtRWX = PROT_READ | PROT_WRITE | PROT_EXEC;
71static constexpr int kProtRX = PROT_READ | PROT_EXEC;
72
73namespace {
74
75// Translate an address belonging to one memory map into an address in a second. This is useful
76// when there are two virtual memory ranges for the same physical memory range.
77template <typename T>
78T* TranslateAddress(T* src_ptr, const MemMap& src, const MemMap& dst) {
79 CHECK(src.HasAddress(src_ptr));
80 uint8_t* const raw_src_ptr = reinterpret_cast<uint8_t*>(src_ptr);
81 return reinterpret_cast<T*>(raw_src_ptr - src.Begin() + dst.Begin());
82}
83
84} // namespace
85
Vladimir Marko2196c652017-11-30 16:16:07 +000086class JitCodeCache::JniStubKey {
87 public:
88 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
89 : shorty_(method->GetShorty()),
90 is_static_(method->IsStatic()),
91 is_fast_native_(method->IsFastNative()),
92 is_critical_native_(method->IsCriticalNative()),
93 is_synchronized_(method->IsSynchronized()) {
94 DCHECK(!(is_fast_native_ && is_critical_native_));
95 }
96
97 bool operator<(const JniStubKey& rhs) const {
98 if (is_static_ != rhs.is_static_) {
99 return rhs.is_static_;
100 }
101 if (is_synchronized_ != rhs.is_synchronized_) {
102 return rhs.is_synchronized_;
103 }
104 if (is_fast_native_ != rhs.is_fast_native_) {
105 return rhs.is_fast_native_;
106 }
107 if (is_critical_native_ != rhs.is_critical_native_) {
108 return rhs.is_critical_native_;
109 }
110 return strcmp(shorty_, rhs.shorty_) < 0;
111 }
112
113 // Update the shorty to point to another method's shorty. Call this function when removing
114 // the method that references the old shorty from JniCodeData and not removing the entire
115 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
116 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
117 const char* shorty = method->GetShorty();
118 DCHECK_STREQ(shorty_, shorty);
119 shorty_ = shorty;
120 }
121
122 private:
123 // The shorty points to a DexFile data and may need to change
124 // to point to the same shorty in a different DexFile.
125 mutable const char* shorty_;
126
127 const bool is_static_;
128 const bool is_fast_native_;
129 const bool is_critical_native_;
130 const bool is_synchronized_;
131};
132
133class JitCodeCache::JniStubData {
134 public:
135 JniStubData() : code_(nullptr), methods_() {}
136
137 void SetCode(const void* code) {
138 DCHECK(code != nullptr);
139 code_ = code;
140 }
141
142 const void* GetCode() const {
143 return code_;
144 }
145
146 bool IsCompiled() const {
147 return GetCode() != nullptr;
148 }
149
150 void AddMethod(ArtMethod* method) {
151 if (!ContainsElement(methods_, method)) {
152 methods_.push_back(method);
153 }
154 }
155
156 const std::vector<ArtMethod*>& GetMethods() const {
157 return methods_;
158 }
159
160 void RemoveMethodsIn(const LinearAlloc& alloc) {
161 auto kept_end = std::remove_if(
162 methods_.begin(),
163 methods_.end(),
164 [&alloc](ArtMethod* method) { return alloc.ContainsUnsafe(method); });
165 methods_.erase(kept_end, methods_.end());
166 }
167
168 bool RemoveMethod(ArtMethod* method) {
169 auto it = std::find(methods_.begin(), methods_.end(), method);
170 if (it != methods_.end()) {
171 methods_.erase(it);
172 return true;
173 } else {
174 return false;
175 }
176 }
177
178 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
179 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
180 }
181
182 private:
183 const void* code_;
184 std::vector<ArtMethod*> methods_;
185};
186
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000187JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
188 size_t max_capacity,
Calin Juravle016fcbe22018-05-03 19:47:35 -0700189 bool used_only_for_profile_data,
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100190 bool rwx_memory_allowed,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000191 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800192 ScopedTrace trace(__PRETTY_FUNCTION__);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100193 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000194
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000195 // We need to have 32 bit offsets from method headers in code cache which point to things
196 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
197 // Ensure we're below 1 GB to be safe.
198 if (max_capacity > 1 * GB) {
199 std::ostringstream oss;
200 oss << "Maxium code cache capacity is limited to 1 GB, "
201 << PrettySize(max_capacity) << " is too big";
202 *error_msg = oss.str();
203 return nullptr;
204 }
205
Orion Hodson563ada22018-09-04 11:28:31 +0100206 // Register for membarrier expedited sync core if JIT will be generating code.
207 if (!used_only_for_profile_data) {
Orion Hodson1d3fd082018-09-28 09:38:35 +0100208 if (art::membarrier(art::MembarrierCommand::kRegisterPrivateExpeditedSyncCore) != 0) {
209 // MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE ensures that CPU instruction pipelines are
210 // flushed and it's used when adding code to the JIT. The memory used by the new code may
211 // have just been released and, in theory, the old code could still be in a pipeline.
212 VLOG(jit) << "Kernel does not support membarrier sync-core";
213 }
Orion Hodson563ada22018-09-04 11:28:31 +0100214 }
215
Orion Hodson1d3fd082018-09-28 09:38:35 +0100216 // File descriptor enabling dual-view mapping of code section.
217 unique_fd mem_fd;
218
219 // Bionic supports memfd_create, but the call may fail on older kernels.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700220 mem_fd = unique_fd(art::memfd_create("/jit-cache", /* flags= */ 0));
Orion Hodson1d3fd082018-09-28 09:38:35 +0100221 if (mem_fd.get() < 0) {
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100222 std::ostringstream oss;
223 oss << "Failed to initialize dual view JIT. memfd_create() error: " << strerror(errno);
224 if (!rwx_memory_allowed) {
225 // Without using RWX page permissions, the JIT can not fallback to single mapping as it
226 // requires tranitioning the code pages to RWX for updates.
227 *error_msg = oss.str();
228 return nullptr;
229 }
230 VLOG(jit) << oss.str();
Orion Hodson1d3fd082018-09-28 09:38:35 +0100231 }
232
233 if (mem_fd.get() >= 0 && ftruncate(mem_fd, max_capacity) != 0) {
234 std::ostringstream oss;
235 oss << "Failed to initialize memory file: " << strerror(errno);
236 *error_msg = oss.str();
237 return nullptr;
238 }
239
240 // Data cache will be half of the initial allocation.
241 // Code cache will be the other half of the initial allocation.
242 // TODO: Make this variable?
243
244 // Align both capacities to page size, as that's the unit mspaces use.
245 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
246 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
247 const size_t data_capacity = max_capacity / 2;
248 const size_t exec_capacity = used_only_for_profile_data ? 0 : max_capacity - data_capacity;
249 DCHECK_LE(data_capacity + exec_capacity, max_capacity);
Calin Juravle016fcbe22018-05-03 19:47:35 -0700250
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800251 std::string error_str;
252 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000253 // Map in low 4gb to simplify accessing root tables for x86_64.
254 // We could do PC-relative addressing to avoid this problem, but that
255 // would require reserving code and data area before submitting, which
256 // means more windows for the code memory to be RWX.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100257 int base_flags;
258 MemMap data_pages;
259 if (mem_fd.get() >= 0) {
260 // Dual view of JIT code cache case. Create an initial mapping of data pages large enough
261 // for data and non-writable view of JIT code pages. We use the memory file descriptor to
262 // enable dual mapping - we'll create a second mapping using the descriptor below. The
263 // mappings will look like:
264 //
265 // VA PA
266 //
267 // +---------------+
268 // | non exec code |\
269 // +---------------+ \
270 // : :\ \
271 // +---------------+.\.+---------------+
272 // | exec code | \| code |
273 // +---------------+...+---------------+
274 // | data | | data |
275 // +---------------+...+---------------+
276 //
277 // In this configuration code updates are written to the non-executable view of the code
278 // cache, and the executable view of the code cache has fixed RX memory protections.
279 //
280 // This memory needs to be mapped shared as the code portions will have two mappings.
281 base_flags = MAP_SHARED;
282 data_pages = MemMap::MapFile(
283 data_capacity + exec_capacity,
284 kProtRW,
285 base_flags,
286 mem_fd,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700287 /* start= */ 0,
288 /* low_4gb= */ true,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100289 "data-code-cache",
290 &error_str);
291 } else {
292 // Single view of JIT code cache case. Create an initial mapping of data pages large enough
293 // for data and JIT code pages. The mappings will look like:
294 //
295 // VA PA
296 //
297 // +---------------+...+---------------+
298 // | exec code | | code |
299 // +---------------+...+---------------+
300 // | data | | data |
301 // +---------------+...+---------------+
302 //
303 // In this configuration code updates are written to the executable view of the code cache,
304 // and the executable view of the code cache transitions RX to RWX for the update and then
305 // back to RX after the update.
306 base_flags = MAP_PRIVATE | MAP_ANON;
307 data_pages = MemMap::MapAnonymous(
308 "data-code-cache",
Orion Hodson1d3fd082018-09-28 09:38:35 +0100309 data_capacity + exec_capacity,
310 kProtRW,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700311 /* low_4gb= */ true,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100312 &error_str);
313 }
314
315 if (!data_pages.IsValid()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800316 std::ostringstream oss;
Andreas Gampee4deaf32017-06-09 15:27:15 -0700317 oss << "Failed to create read write cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800318 *error_msg = oss.str();
319 return nullptr;
320 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100321
Orion Hodson1d3fd082018-09-28 09:38:35 +0100322 MemMap exec_pages;
323 MemMap non_exec_pages;
324 if (exec_capacity > 0) {
325 uint8_t* const divider = data_pages.Begin() + data_capacity;
326 // Set initial permission for executable view to catch any SELinux permission problems early
327 // (for processes that cannot map WX pages). Otherwise, this region does not need to be
328 // executable as there is no code in the cache yet.
329 exec_pages = data_pages.RemapAtEnd(divider,
330 "jit-code-cache",
331 kProtRX,
332 base_flags | MAP_FIXED,
333 mem_fd.get(),
334 (mem_fd.get() >= 0) ? data_capacity : 0,
335 &error_str);
336 if (!exec_pages.IsValid()) {
337 std::ostringstream oss;
338 oss << "Failed to create read execute code cache: " << error_str << " size=" << max_capacity;
339 *error_msg = oss.str();
340 return nullptr;
341 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100342
Orion Hodson1d3fd082018-09-28 09:38:35 +0100343 if (mem_fd.get() >= 0) {
344 // For dual view, create the secondary view of code memory used for updating code. This view
345 // is never executable.
346 non_exec_pages = MemMap::MapFile(exec_capacity,
347 kProtR,
348 base_flags,
349 mem_fd,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700350 /* start= */ data_capacity,
351 /* low_4GB= */ false,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100352 "jit-code-cache-rw",
353 &error_str);
354 if (!non_exec_pages.IsValid()) {
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100355 static const char* kFailedNxView = "Failed to map non-executable view of JIT code cache";
356 if (rwx_memory_allowed) {
357 // Log and continue as single view JIT (requires RWX memory).
358 VLOG(jit) << kFailedNxView;
359 } else {
360 *error_msg = kFailedNxView;
361 return nullptr;
362 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100363 }
364 }
365 } else {
366 // Profiling only. No memory for code required.
367 DCHECK(used_only_for_profile_data);
David Sehrd1dbb742017-07-17 11:20:38 -0700368 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100369
370 const size_t initial_data_capacity = initial_capacity / 2;
371 const size_t initial_exec_capacity =
372 (exec_capacity == 0) ? 0 : (initial_capacity - initial_data_capacity);
373
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100374 return new JitCodeCache(
Orion Hodson1d3fd082018-09-28 09:38:35 +0100375 std::move(data_pages),
376 std::move(exec_pages),
377 std::move(non_exec_pages),
378 initial_data_capacity,
379 initial_exec_capacity,
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100380 max_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800381}
382
Orion Hodson1d3fd082018-09-28 09:38:35 +0100383JitCodeCache::JitCodeCache(MemMap&& data_pages,
384 MemMap&& exec_pages,
385 MemMap&& non_exec_pages,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000386 size_t initial_data_capacity,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100387 size_t initial_exec_capacity,
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100388 size_t max_capacity)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100389 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000390 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100391 collection_in_progress_(false),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100392 data_pages_(std::move(data_pages)),
393 exec_pages_(std::move(exec_pages)),
394 non_exec_pages_(std::move(non_exec_pages)),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000395 max_capacity_(max_capacity),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100396 current_capacity_(initial_exec_capacity + initial_data_capacity),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000397 data_end_(initial_data_capacity),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100398 exec_end_(initial_exec_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000399 last_collection_increased_code_cache_(false),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100400 garbage_collect_code_(true),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000401 used_memory_for_data_(0),
402 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000403 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000404 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000405 number_of_collections_(0),
406 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
407 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000408 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
409 is_weak_access_enabled_(true),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100410 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100411
Orion Hodson1d3fd082018-09-28 09:38:35 +0100412 DCHECK_GE(max_capacity, initial_exec_capacity + initial_data_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100413
Orion Hodson1d3fd082018-09-28 09:38:35 +0100414 // Initialize the data heap
415 data_mspace_ = create_mspace_with_base(data_pages_.Begin(), data_end_, false /*locked*/);
416 CHECK(data_mspace_ != nullptr) << "create_mspace_with_base (data) failed";
417
418 // Initialize the code heap
419 MemMap* code_heap = nullptr;
420 if (non_exec_pages_.IsValid()) {
421 code_heap = &non_exec_pages_;
422 } else if (exec_pages_.IsValid()) {
423 code_heap = &exec_pages_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100424 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100425 if (code_heap != nullptr) {
426 // Make all pages reserved for the code heap writable. The mspace allocator, that manages the
427 // heap, will take and initialize pages in create_mspace_with_base().
428 CheckedCall(mprotect, "create code heap", code_heap->Begin(), code_heap->Size(), kProtRW);
429 exec_mspace_ = create_mspace_with_base(code_heap->Begin(), exec_end_, false /*locked*/);
430 CHECK(exec_mspace_ != nullptr) << "create_mspace_with_base (exec) failed";
431 SetFootprintLimit(current_capacity_);
432 // Protect pages containing heap metadata. Updates to the code heap toggle write permission to
433 // perform the update and there are no other times write access is required.
434 CheckedCall(mprotect, "protect code heap", code_heap->Begin(), code_heap->Size(), kProtR);
435 } else {
436 exec_mspace_ = nullptr;
437 SetFootprintLimit(current_capacity_);
438 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100439
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000440 VLOG(jit) << "Created jit code cache: initial data size="
441 << PrettySize(initial_data_capacity)
442 << ", initial code size="
Orion Hodson1d3fd082018-09-28 09:38:35 +0100443 << PrettySize(initial_exec_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800444}
445
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000446JitCodeCache::~JitCodeCache() {}
447
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100448bool JitCodeCache::ContainsPc(const void* ptr) const {
Orion Hodson1d3fd082018-09-28 09:38:35 +0100449 return exec_pages_.Begin() <= ptr && ptr < exec_pages_.End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800450}
451
Alex Light2d441b12018-06-08 15:33:21 -0700452bool JitCodeCache::WillExecuteJitCode(ArtMethod* method) {
453 ScopedObjectAccess soa(art::Thread::Current());
454 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
455 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
456 return true;
457 } else if (method->GetEntryPointFromQuickCompiledCode() == GetQuickInstrumentationEntryPoint()) {
458 return FindCompiledCodeForInstrumentation(method) != nullptr;
459 }
460 return false;
461}
462
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000463bool JitCodeCache::ContainsMethod(ArtMethod* method) {
464 MutexLock mu(Thread::Current(), lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000465 if (UNLIKELY(method->IsNative())) {
466 auto it = jni_stubs_map_.find(JniStubKey(method));
467 if (it != jni_stubs_map_.end() &&
468 it->second.IsCompiled() &&
469 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000470 return true;
471 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000472 } else {
473 for (const auto& it : method_code_map_) {
474 if (it.second == method) {
475 return true;
476 }
477 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000478 }
479 return false;
480}
481
Vladimir Marko2196c652017-11-30 16:16:07 +0000482const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
483 DCHECK(method->IsNative());
484 MutexLock mu(Thread::Current(), lock_);
485 auto it = jni_stubs_map_.find(JniStubKey(method));
486 if (it != jni_stubs_map_.end()) {
487 JniStubData& data = it->second;
488 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
489 return data.GetCode();
490 }
491 }
492 return nullptr;
493}
494
Alex Light2d441b12018-06-08 15:33:21 -0700495const void* JitCodeCache::FindCompiledCodeForInstrumentation(ArtMethod* method) {
Alex Light839f53a2018-07-10 15:46:14 -0700496 // If jit-gc is still on we use the SavedEntryPoint field for doing that and so cannot use it to
497 // find the instrumentation entrypoint.
498 if (LIKELY(GetGarbageCollectCode())) {
Alex Light2d441b12018-06-08 15:33:21 -0700499 return nullptr;
500 }
501 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
502 if (info == nullptr) {
503 return nullptr;
504 }
505 // When GC is disabled for trampoline tracing we will use SavedEntrypoint to hold the actual
506 // jit-compiled version of the method. If jit-gc is disabled for other reasons this will just be
507 // nullptr.
508 return info->GetSavedEntryPoint();
509}
510
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800511class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100512 public:
Calin Juravle016fcbe22018-05-03 19:47:35 -0700513 explicit ScopedCodeCacheWrite(const JitCodeCache* const code_cache)
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100514 : ScopedTrace("ScopedCodeCacheWrite"),
Calin Juravle016fcbe22018-05-03 19:47:35 -0700515 code_cache_(code_cache) {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800516 ScopedTrace trace("mprotect all");
Orion Hodson1d3fd082018-09-28 09:38:35 +0100517 const MemMap* const updatable_pages = code_cache_->GetUpdatableCodeMapping();
518 if (updatable_pages != nullptr) {
519 int prot = code_cache_->HasDualCodeMapping() ? kProtRW : kProtRWX;
520 CheckedCall(mprotect, "Cache +W", updatable_pages->Begin(), updatable_pages->Size(), prot);
521 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800522 }
Calin Juravle016fcbe22018-05-03 19:47:35 -0700523
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100524 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800525 ScopedTrace trace("mprotect code");
Orion Hodson1d3fd082018-09-28 09:38:35 +0100526 const MemMap* const updatable_pages = code_cache_->GetUpdatableCodeMapping();
527 if (updatable_pages != nullptr) {
528 int prot = code_cache_->HasDualCodeMapping() ? kProtR : kProtRX;
529 CheckedCall(mprotect, "Cache -W", updatable_pages->Begin(), updatable_pages->Size(), prot);
530 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100531 }
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700532
David Sehrd1dbb742017-07-17 11:20:38 -0700533 private:
Calin Juravle016fcbe22018-05-03 19:47:35 -0700534 const JitCodeCache* const code_cache_;
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100535
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100536 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
537};
538
539uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100540 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000541 uint8_t* stack_map,
542 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100543 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000544 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100545 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000546 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100547 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700548 bool has_should_deoptimize_flag,
549 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100550 uint8_t* result = CommitCodeInternal(self,
551 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000552 stack_map,
553 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100554 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000555 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100556 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000557 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700558 roots,
559 has_should_deoptimize_flag,
560 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100561 if (result == nullptr) {
562 // Retry.
563 GarbageCollectCache(self);
564 result = CommitCodeInternal(self,
565 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000566 stack_map,
567 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100568 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000569 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100570 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000571 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700572 roots,
573 has_should_deoptimize_flag,
574 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100575 }
576 return result;
577}
578
579bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
580 bool in_collection = false;
581 while (collection_in_progress_) {
582 in_collection = true;
583 lock_cond_.Wait(self);
584 }
585 return in_collection;
586}
587
588static uintptr_t FromCodeToAllocation(const void* code) {
589 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
590 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
591}
592
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000593static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
594 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
595}
596
597static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
598 // The length of the table is stored just before the stack map (and therefore at the end of
599 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
600 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
601}
602
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800603static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
604 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
605 // pointer.
606 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
607}
608
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000609static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
610 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
611}
612
Vladimir Markoac3ac682018-09-20 11:01:43 +0100613static void DCheckRootsAreValid(const std::vector<Handle<mirror::Object>>& roots)
Alex Light3e36a9c2018-06-19 09:45:05 -0700614 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
615 if (!kIsDebugBuild) {
616 return;
617 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700618 // Put all roots in `roots_data`.
Vladimir Markoac3ac682018-09-20 11:01:43 +0100619 for (Handle<mirror::Object> object : roots) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700620 // Ensure the string is strongly interned. b/32995596
621 if (object->IsString()) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100622 ObjPtr<mirror::String> str = object->AsString();
Alex Light3e36a9c2018-06-19 09:45:05 -0700623 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
624 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
625 }
626 }
627}
628
629void JitCodeCache::FillRootTable(uint8_t* roots_data,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100630 const std::vector<Handle<mirror::Object>>& roots) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000631 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Vladimir Markoac3ac682018-09-20 11:01:43 +0100632 const uint32_t length = roots.size();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000633 // Put all roots in `roots_data`.
634 for (uint32_t i = 0; i < length; ++i) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100635 ObjPtr<mirror::Object> object = roots[i].Get();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000636 gc_roots[i] = GcRoot<mirror::Object>(object);
637 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000638}
639
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100640static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000641 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
642 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
643 uint32_t roots = GetNumberOfRoots(data);
644 if (number_of_roots != nullptr) {
645 *number_of_roots = roots;
646 }
647 return data - ComputeRootTableSize(roots);
648}
649
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100650// Use a sentinel for marking entries in the JIT table that have been cleared.
651// This helps diagnosing in case the compiled code tries to wrongly access such
652// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700653static mirror::Class* const weak_sentinel =
654 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100655
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000656// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100657static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
658 IsMarkedVisitor* visitor,
659 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000660 REQUIRES_SHARED(Locks::mutator_lock_) {
661 // This does not need a read barrier because this is called by GC.
662 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100663 if (cls != nullptr && cls != weak_sentinel) {
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700664 DCHECK((cls->IsClass<kDefaultVerifyFlags>()));
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000665 // Look at the classloader of the class to know if it has been unloaded.
666 // This does not need a read barrier because this is called by GC.
667 mirror::Object* class_loader =
668 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
669 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
670 // The class loader is live, update the entry if the class has moved.
671 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
672 // Note that new_object can be null for CMS and newly allocated objects.
673 if (new_cls != nullptr && new_cls != cls) {
674 *root_ptr = GcRoot<mirror::Class>(new_cls);
675 }
676 } else {
677 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100678 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000679 }
680 }
681}
682
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000683void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
684 MutexLock mu(Thread::Current(), lock_);
685 for (const auto& entry : method_code_map_) {
686 uint32_t number_of_roots = 0;
687 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
688 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
689 for (uint32_t i = 0; i < number_of_roots; ++i) {
690 // This does not need a read barrier because this is called by GC.
691 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100692 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000693 // entry got deleted in a previous sweep.
694 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
695 mirror::Object* new_object = visitor->IsMarked(object);
696 // We know the string is marked because it's a strongly-interned string that
697 // is always alive. The IsMarked implementation of the CMS collector returns
698 // null for newly allocated objects, but we know those haven't moved. Therefore,
699 // only update the entry if we get a different non-null string.
700 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
701 // out of the weak access/creation pause. b/32167580
702 if (new_object != nullptr && new_object != object) {
703 DCHECK(new_object->IsString());
704 roots[i] = GcRoot<mirror::Object>(new_object);
705 }
706 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100707 ProcessWeakClass(
708 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000709 }
710 }
711 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000712 // Walk over inline caches to clear entries containing unloaded classes.
713 for (ProfilingInfo* info : profiling_infos_) {
714 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
715 InlineCache* cache = &info->cache_[i];
716 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100717 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000718 }
719 }
720 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000721}
722
Orion Hodson607624f2018-05-11 10:10:46 +0100723void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100724 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000725 // Notify native debugger that we are about to remove the code.
726 // It does nothing if we are not using native debugger.
David Srbeckyfb3de3d2018-01-29 16:11:49 +0000727 MutexLock mu(Thread::Current(), *Locks::native_debug_interface_lock_);
David Srbecky440a9b32018-02-15 17:47:29 +0000728 RemoveNativeDebugInfoForJit(code_ptr);
Vladimir Marko2196c652017-11-30 16:16:07 +0000729 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
730 FreeData(GetRootTable(code_ptr));
731 } // else this is a JNI stub without any data.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100732
733 uint8_t* code_allocation = reinterpret_cast<uint8_t*>(allocation);
734 if (HasDualCodeMapping()) {
735 code_allocation = TranslateAddress(code_allocation, exec_pages_, non_exec_pages_);
736 }
737
738 FreeCode(code_allocation);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100739}
740
Mingyao Yang063fc772016-08-02 11:02:54 -0700741void JitCodeCache::FreeAllMethodHeaders(
742 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700743 // We need to remove entries in method_headers from CHA dependencies
744 // first since once we do FreeCode() below, the memory can be reused
745 // so it's possible for the same method_header to start representing
746 // different compile code.
747 MutexLock mu(Thread::Current(), lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000748 {
749 MutexLock mu2(Thread::Current(), *Locks::cha_lock_);
750 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
751 ->RemoveDependentsWithMethodHeaders(method_headers);
752 }
753
Calin Juravle016fcbe22018-05-03 19:47:35 -0700754 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700755 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodson607624f2018-05-11 10:10:46 +0100756 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700757 }
758}
759
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100760void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800761 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700762 // We use a set to first collect all method_headers whose code need to be
763 // removed. We need to free the underlying code after we remove CHA dependencies
764 // for entries in this set. And it's more efficient to iterate through
765 // the CHA dependency map just once with an unordered_set.
766 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000767 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700768 MutexLock mu(self, lock_);
769 // We do not check if a code cache GC is in progress, as this method comes
770 // with the classlinker_classes_lock_ held, and suspending ourselves could
771 // lead to a deadlock.
772 {
Calin Juravle016fcbe22018-05-03 19:47:35 -0700773 ScopedCodeCacheWrite scc(this);
Vladimir Marko2196c652017-11-30 16:16:07 +0000774 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
775 it->second.RemoveMethodsIn(alloc);
776 if (it->second.GetMethods().empty()) {
777 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
778 it = jni_stubs_map_.erase(it);
779 } else {
780 it->first.UpdateShorty(it->second.GetMethods().front());
781 ++it;
782 }
783 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700784 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
785 if (alloc.ContainsUnsafe(it->second)) {
786 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
787 it = method_code_map_.erase(it);
788 } else {
789 ++it;
790 }
791 }
792 }
793 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
794 if (alloc.ContainsUnsafe(it->first)) {
795 // Note that the code has already been pushed to method_headers in the loop
796 // above and is going to be removed in FreeCode() below.
797 it = osr_code_map_.erase(it);
798 } else {
799 ++it;
800 }
801 }
802 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
803 ProfilingInfo* info = *it;
804 if (alloc.ContainsUnsafe(info->GetMethod())) {
805 info->GetMethod()->SetProfilingInfo(nullptr);
806 FreeData(reinterpret_cast<uint8_t*>(info));
807 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000808 } else {
809 ++it;
810 }
811 }
812 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700813 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100814}
815
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000816bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
817 return kUseReadBarrier
818 ? self->GetWeakRefAccessEnabled()
Orion Hodson88591fe2018-03-06 13:35:43 +0000819 : is_weak_access_enabled_.load(std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000820}
821
822void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
823 if (IsWeakAccessEnabled(self)) {
824 return;
825 }
826 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000827 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000828 while (!IsWeakAccessEnabled(self)) {
829 inline_cache_cond_.Wait(self);
830 }
831}
832
833void JitCodeCache::BroadcastForInlineCacheAccess() {
834 Thread* self = Thread::Current();
835 MutexLock mu(self, lock_);
836 inline_cache_cond_.Broadcast(self);
837}
838
839void JitCodeCache::AllowInlineCacheAccess() {
840 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000841 is_weak_access_enabled_.store(true, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000842 BroadcastForInlineCacheAccess();
843}
844
845void JitCodeCache::DisallowInlineCacheAccess() {
846 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000847 is_weak_access_enabled_.store(false, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000848}
849
850void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
851 Handle<mirror::ObjectArray<mirror::Class>> array) {
852 WaitUntilInlineCacheAccessible(Thread::Current());
853 // Note that we don't need to lock `lock_` here, the compiler calling
854 // this method has already ensured the inline cache will not be deleted.
855 for (size_t in_cache = 0, in_array = 0;
856 in_cache < InlineCache::kIndividualCacheSize;
857 ++in_cache) {
858 mirror::Class* object = ic.classes_[in_cache].Read();
859 if (object != nullptr) {
860 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000861 }
862 }
863}
864
Mathieu Chartierf044c222017-05-31 15:27:54 -0700865static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
866 if (was_warm) {
Vladimir Markoc945e0d2018-07-18 17:26:45 +0100867 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700868 }
869 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
870 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100871 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
872 // the warmup threshold is 1.
873 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
874 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700875}
876
Alex Light33b7b5d2018-08-07 19:13:51 +0000877void JitCodeCache::WaitForPotentialCollectionToCompleteRunnable(Thread* self) {
878 while (collection_in_progress_) {
879 lock_.Unlock(self);
880 {
881 ScopedThreadSuspension sts(self, kSuspended);
882 MutexLock mu(self, lock_);
883 WaitForPotentialCollectionToComplete(self);
884 }
885 lock_.Lock(self);
886 }
887}
888
Orion Hodson1d3fd082018-09-28 09:38:35 +0100889const MemMap* JitCodeCache::GetUpdatableCodeMapping() const {
890 if (HasDualCodeMapping()) {
891 return &non_exec_pages_;
892 } else if (HasCodeMapping()) {
893 return &exec_pages_;
894 } else {
895 return nullptr;
896 }
897}
898
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100899uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
900 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000901 uint8_t* stack_map,
902 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100903 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000904 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100905 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000906 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100907 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700908 bool has_should_deoptimize_flag,
909 const ArenaSet<ArtMethod*>&
910 cha_single_implementation_list) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000911 DCHECK(!method->IsNative() || !osr);
Alex Light33b7b5d2018-08-07 19:13:51 +0000912
913 if (!method->IsNative()) {
914 // We need to do this before grabbing the lock_ because it needs to be able to see the string
915 // InternTable. Native methods do not have roots.
916 DCheckRootsAreValid(roots);
917 }
918
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100919 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100920 uint8_t* code_ptr = nullptr;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100921
Alex Light33b7b5d2018-08-07 19:13:51 +0000922 MutexLock mu(self, lock_);
923 // We need to make sure that there will be no jit-gcs going on and wait for any ongoing one to
924 // finish.
925 WaitForPotentialCollectionToCompleteRunnable(self);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100926 {
Alex Light33b7b5d2018-08-07 19:13:51 +0000927 ScopedCodeCacheWrite scc(this);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100928
929 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
930 // Ensure the header ends up at expected instruction alignment.
931 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
932 size_t total_size = header_size + code_size;
933
934 // AllocateCode allocates memory in non-executable region for alignment header and code. The
935 // header size may include alignment padding.
936 uint8_t* nox_memory = AllocateCode(total_size);
937 if (nox_memory == nullptr) {
Alex Light33b7b5d2018-08-07 19:13:51 +0000938 return nullptr;
939 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000940
Orion Hodson1d3fd082018-09-28 09:38:35 +0100941 // code_ptr points to non-executable code.
942 code_ptr = nox_memory + header_size;
Alex Light33b7b5d2018-08-07 19:13:51 +0000943 std::copy(code, code + code_size, code_ptr);
944 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100945
946 // From here code_ptr points to executable code.
947 if (HasDualCodeMapping()) {
948 code_ptr = TranslateAddress(code_ptr, non_exec_pages_, exec_pages_);
949 }
950
Alex Light33b7b5d2018-08-07 19:13:51 +0000951 new (method_header) OatQuickMethodHeader(
952 (stack_map != nullptr) ? code_ptr - stack_map : 0u,
953 code_size);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100954
955 DCHECK(!Runtime::Current()->IsAotCompiler());
956 if (has_should_deoptimize_flag) {
957 method_header->SetHasShouldDeoptimizeFlag();
958 }
959
960 // Update method_header pointer to executable code region.
961 if (HasDualCodeMapping()) {
962 method_header = TranslateAddress(method_header, non_exec_pages_, exec_pages_);
963 }
964
965 // Both instruction and data caches need flushing to the point of unification where both share
966 // a common view of memory. Flushing the data cache ensures the dirty cachelines from the
967 // newly added code are written out to the point of unification. Flushing the instruction
968 // cache ensures the newly written code will be fetched from the point of unification before
969 // use. Memory in the code cache is re-cycled as code is added and removed. The flushes
970 // prevent stale code from residing in the instruction cache.
971 //
972 // Caches are flushed before write permission is removed because some ARMv8 Qualcomm kernels
973 // may trigger a segfault if a page fault occurs when requesting a cache maintenance
974 // operation. This is a kernel bug that we need to work around until affected devices
975 // (e.g. Nexus 5X and 6P) stop being supported or their kernels are fixed.
Alex Light33b7b5d2018-08-07 19:13:51 +0000976 //
977 // For reference, this behavior is caused by this commit:
978 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
Orion Hodson1d3fd082018-09-28 09:38:35 +0100979 //
980 if (HasDualCodeMapping()) {
981 // Flush the data cache lines associated with the non-executable copy of the code just added.
982 FlushDataCache(nox_memory, nox_memory + total_size);
983 }
984 // FlushInstructionCache() flushes both data and instruction caches lines. The cacheline range
985 // flushed is for the executable mapping of the code just added.
Orion Hodson38d29fd2018-09-07 12:58:37 +0100986 FlushInstructionCache(code_ptr, code_ptr + code_size);
Orion Hodsonf2331362018-07-11 15:14:10 +0100987
988 // Ensure CPU instruction pipelines are flushed for all cores. This is necessary for
989 // correctness as code may still be in instruction pipelines despite the i-cache flush. It is
990 // not safe to assume that changing permissions with mprotect (RX->RWX->RX) will cause a TLB
991 // shootdown (incidentally invalidating the CPU pipelines by sending an IPI to all cores to
992 // notify them of the TLB invalidation). Some architectures, notably ARM and ARM64, have
993 // hardware support that broadcasts TLB invalidations and so their kernels have no software
Orion Hodson1d3fd082018-09-28 09:38:35 +0100994 // based TLB shootdown. The sync-core flavor of membarrier was introduced in Linux 4.16 to
995 // address this (see mbarrier(2)). The membarrier here will fail on prior kernels and on
996 // platforms lacking the appropriate support.
Orion Hodson563ada22018-09-04 11:28:31 +0100997 art::membarrier(art::MembarrierCommand::kPrivateExpeditedSyncCore);
Orion Hodson38d29fd2018-09-07 12:58:37 +0100998
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000999 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001000 }
Orion Hodson1d3fd082018-09-28 09:38:35 +01001001
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001002 // We need to update the entry point in the runnable state for the instrumentation.
1003 {
Alex Light33b7b5d2018-08-07 19:13:51 +00001004 // The following needs to be guarded by cha_lock_ also. Otherwise it's possible that the
1005 // compiled code is considered invalidated by some class linking, but below we still make the
1006 // compiled code valid for the method. Need cha_lock_ for checking all single-implementation
1007 // flags and register dependencies.
Mingyao Yang063fc772016-08-02 11:02:54 -07001008 MutexLock cha_mu(self, *Locks::cha_lock_);
1009 bool single_impl_still_valid = true;
1010 for (ArtMethod* single_impl : cha_single_implementation_list) {
1011 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001012 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
1013 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -07001014 single_impl_still_valid = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001015 ClearMethodCounter(method, /*was_warm=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -07001016 break;
1017 }
1018 }
1019
1020 // Discard the code if any single-implementation assumptions are now invalid.
1021 if (!single_impl_still_valid) {
1022 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
1023 return nullptr;
1024 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00001025 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -08001026 << "Should not be using cha on debuggable apps/runs!";
1027
Mingyao Yang063fc772016-08-02 11:02:54 -07001028 for (ArtMethod* single_impl : cha_single_implementation_list) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07001029 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()->AddDependency(
Mingyao Yang063fc772016-08-02 11:02:54 -07001030 single_impl, method, method_header);
1031 }
1032
Vladimir Marko2196c652017-11-30 16:16:07 +00001033 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001034 auto it = jni_stubs_map_.find(JniStubKey(method));
1035 DCHECK(it != jni_stubs_map_.end())
1036 << "Entry inserted in NotifyCompilationOf() should be alive.";
1037 JniStubData* data = &it->second;
1038 DCHECK(ContainsElement(data->GetMethods(), method))
1039 << "Entry inserted in NotifyCompilationOf() should contain this method.";
1040 data->SetCode(code_ptr);
1041 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
1042 for (ArtMethod* m : data->GetMethods()) {
1043 instrum->UpdateMethodsCode(m, method_header->GetEntryPoint());
1044 }
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001045 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +00001046 // Fill the root table before updating the entry point.
1047 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
1048 DCHECK_LE(roots_data, stack_map);
1049 FillRootTable(roots_data, roots);
1050 {
1051 // Flush data cache, as compiled code references literals in it.
Orion Hodson38d29fd2018-09-07 12:58:37 +01001052 FlushDataCache(roots_data, roots_data + data_size);
Vladimir Marko2196c652017-11-30 16:16:07 +00001053 }
1054 method_code_map_.Put(code_ptr, method);
1055 if (osr) {
1056 number_of_osr_compilations_++;
1057 osr_code_map_.Put(method, code_ptr);
1058 } else {
1059 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1060 method, method_header->GetEntryPoint());
1061 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001062 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001063 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001064 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -07001065 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001066 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1067 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
1068 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -07001069 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
1070 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001071 histogram_code_memory_use_.AddValue(code_size);
1072 if (code_size > kCodeSizeLogThreshold) {
1073 LOG(INFO) << "JIT allocated "
1074 << PrettySize(code_size)
1075 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -07001076 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001077 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001078 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001079
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001080 return reinterpret_cast<uint8_t*>(method_header);
1081}
1082
1083size_t JitCodeCache::CodeCacheSize() {
1084 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001085 return CodeCacheSizeLocked();
1086}
1087
Orion Hodsoneced6922017-06-01 10:54:28 +01001088bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001089 // This function is used only for testing and only with non-native methods.
1090 CHECK(!method->IsNative());
1091
Orion Hodsoneced6922017-06-01 10:54:28 +01001092 MutexLock mu(Thread::Current(), lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +01001093
Vladimir Marko2196c652017-11-30 16:16:07 +00001094 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
1095 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +01001096
1097 if (!in_cache) {
1098 return false;
1099 }
1100
Orion Hodsoneced6922017-06-01 10:54:28 +01001101 method->ClearCounter();
1102 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1103 method, GetQuickToInterpreterBridge());
1104 VLOG(jit)
1105 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
1106 << ArtMethod::PrettyMethod(method) << "@" << method
1107 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1108 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
1109 return true;
1110}
1111
Vladimir Marko2196c652017-11-30 16:16:07 +00001112bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
1113 if (LIKELY(!method->IsNative())) {
1114 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1115 if (info != nullptr) {
1116 RemoveElement(profiling_infos_, info);
1117 }
1118 method->SetProfilingInfo(nullptr);
1119 }
1120
1121 bool in_cache = false;
Calin Juravle016fcbe22018-05-03 19:47:35 -07001122 ScopedCodeCacheWrite ccw(this);
Vladimir Marko2196c652017-11-30 16:16:07 +00001123 if (UNLIKELY(method->IsNative())) {
1124 auto it = jni_stubs_map_.find(JniStubKey(method));
1125 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
1126 in_cache = true;
1127 if (it->second.GetMethods().empty()) {
1128 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +01001129 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +00001130 }
1131 jni_stubs_map_.erase(it);
1132 } else {
1133 it->first.UpdateShorty(it->second.GetMethods().front());
1134 }
1135 }
1136 } else {
1137 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1138 if (it->second == method) {
1139 in_cache = true;
1140 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +01001141 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +00001142 }
1143 it = method_code_map_.erase(it);
1144 } else {
1145 ++it;
1146 }
1147 }
1148
1149 auto osr_it = osr_code_map_.find(method);
1150 if (osr_it != osr_code_map_.end()) {
1151 osr_code_map_.erase(osr_it);
1152 }
1153 }
1154
1155 return in_cache;
1156}
1157
Alex Lightdba61482016-12-21 08:20:29 -08001158// This notifies the code cache that the given method has been redefined and that it should remove
1159// any cached information it has on the method. All threads must be suspended before calling this
1160// method. The compiled code for the method (if there is any) must not be in any threads call stack.
1161void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
1162 MutexLock mu(Thread::Current(), lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001163 RemoveMethodLocked(method, /* release_memory= */ true);
Alex Lightdba61482016-12-21 08:20:29 -08001164}
1165
1166// This invalidates old_method. Once this function returns one can no longer use old_method to
1167// execute code unless it is fixed up. This fixup will happen later in the process of installing a
1168// class redefinition.
1169// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
1170// shouldn't be used since it is no longer logically in the jit code cache.
1171// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
1172void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001173 MutexLock mu(Thread::Current(), lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +00001174 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001175 // Update methods in jni_stubs_map_.
1176 for (auto& entry : jni_stubs_map_) {
1177 JniStubData& data = entry.second;
1178 data.MoveObsoleteMethod(old_method, new_method);
1179 }
Alex Lighteee0bd42017-02-14 15:31:45 +00001180 return;
1181 }
Alex Lightdba61482016-12-21 08:20:29 -08001182 // Update ProfilingInfo to the new one and remove it from the old_method.
1183 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
1184 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
1185 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
1186 old_method->SetProfilingInfo(nullptr);
1187 // Since the JIT should be paused and all threads suspended by the time this is called these
1188 // checks should always pass.
1189 DCHECK(!info->IsInUseByCompiler());
1190 new_method->SetProfilingInfo(info);
Alex Light2d441b12018-06-08 15:33:21 -07001191 // Get rid of the old saved entrypoint if it is there.
1192 info->SetSavedEntryPoint(nullptr);
Alex Lightdba61482016-12-21 08:20:29 -08001193 info->method_ = new_method;
1194 }
1195 // Update method_code_map_ to point to the new method.
1196 for (auto& it : method_code_map_) {
1197 if (it.second == old_method) {
1198 it.second = new_method;
1199 }
1200 }
1201 // Update osr_code_map_ to point to the new method.
1202 auto code_map = osr_code_map_.find(old_method);
1203 if (code_map != osr_code_map_.end()) {
1204 osr_code_map_.Put(new_method, code_map->second);
1205 osr_code_map_.erase(old_method);
1206 }
1207}
1208
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001209size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001210 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001211}
1212
1213size_t JitCodeCache::DataCacheSize() {
1214 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001215 return DataCacheSizeLocked();
1216}
1217
1218size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001219 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001220}
1221
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001222void JitCodeCache::ClearData(Thread* self,
1223 uint8_t* stack_map_data,
1224 uint8_t* roots_data) {
1225 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001226 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001227 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001228}
1229
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001230size_t JitCodeCache::ReserveData(Thread* self,
1231 size_t stack_map_size,
1232 size_t number_of_roots,
1233 ArtMethod* method,
1234 uint8_t** stack_map_data,
1235 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001236 size_t table_size = ComputeRootTableSize(number_of_roots);
David Srbecky8cd54542018-07-15 23:58:44 +01001237 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001238 uint8_t* result = nullptr;
1239
1240 {
1241 ScopedThreadSuspension sts(self, kSuspended);
1242 MutexLock mu(self, lock_);
1243 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001244 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001245 }
1246
1247 if (result == nullptr) {
1248 // Retry.
1249 GarbageCollectCache(self);
1250 ScopedThreadSuspension sts(self, kSuspended);
1251 MutexLock mu(self, lock_);
1252 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001253 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001254 }
1255
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001256 MutexLock mu(self, lock_);
1257 histogram_stack_map_memory_use_.AddValue(size);
1258 if (size > kStackMapSizeLogThreshold) {
1259 LOG(INFO) << "JIT allocated "
1260 << PrettySize(size)
1261 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001262 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001263 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001264 if (result != nullptr) {
1265 *roots_data = result;
1266 *stack_map_data = result + table_size;
1267 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001268 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001269 } else {
1270 *roots_data = nullptr;
1271 *stack_map_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001272 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001273 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001274}
1275
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001276class MarkCodeClosure final : public Closure {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001277 public:
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001278 MarkCodeClosure(JitCodeCache* code_cache, CodeCacheBitmap* bitmap, Barrier* barrier)
1279 : code_cache_(code_cache), bitmap_(bitmap), barrier_(barrier) {}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001280
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001281 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001282 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001283 DCHECK(thread == Thread::Current() || thread->IsSuspended());
Andreas Gampe3d477f32018-11-16 16:40:45 +00001284 StackVisitor::WalkStack(
1285 [&](const art::StackVisitor* stack_visitor) {
1286 const OatQuickMethodHeader* method_header =
1287 stack_visitor->GetCurrentOatQuickMethodHeader();
1288 if (method_header == nullptr) {
1289 return true;
1290 }
1291 const void* code = method_header->GetCode();
1292 if (code_cache_->ContainsPc(code)) {
1293 // Use the atomic set version, as multiple threads are executing this code.
1294 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1295 }
1296 return true;
1297 },
1298 thread,
1299 /* context= */ nullptr,
1300 art::StackVisitor::StackWalkKind::kSkipInlinedFrames);
1301
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001302 if (kIsDebugBuild) {
1303 // The stack walking code queries the side instrumentation stack if it
1304 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1305 // must have been seen. We sanity check this below.
1306 for (const instrumentation::InstrumentationStackFrame& frame
1307 : *thread->GetInstrumentationStack()) {
1308 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1309 // its stack frame, it is not the method owning return_pc_. We just pass null to
1310 // LookupMethodHeader: the method is only checked against in debug builds.
1311 OatQuickMethodHeader* method_header =
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001312 code_cache_->LookupMethodHeader(frame.return_pc_, /* method= */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001313 if (method_header != nullptr) {
1314 const void* code = method_header->GetCode();
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001315 CHECK(bitmap_->Test(FromCodeToAllocation(code)));
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001316 }
1317 }
1318 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001319 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001320 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001321
1322 private:
1323 JitCodeCache* const code_cache_;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001324 CodeCacheBitmap* const bitmap_;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001325 Barrier* const barrier_;
1326};
1327
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001328void JitCodeCache::NotifyCollectionDone(Thread* self) {
1329 collection_in_progress_ = false;
1330 lock_cond_.Broadcast(self);
1331}
1332
1333void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
1334 size_t per_space_footprint = new_footprint / 2;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001335 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001336 DCHECK_EQ(per_space_footprint * 2, new_footprint);
1337 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001338 if (HasCodeMapping()) {
Calin Juravle016fcbe22018-05-03 19:47:35 -07001339 ScopedCodeCacheWrite scc(this);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001340 mspace_set_footprint_limit(exec_mspace_, per_space_footprint);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001341 }
1342}
1343
1344bool JitCodeCache::IncreaseCodeCacheCapacity() {
1345 if (current_capacity_ == max_capacity_) {
1346 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001347 }
1348
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001349 // Double the capacity if we're below 1MB, or increase it by 1MB if
1350 // we're above.
1351 if (current_capacity_ < 1 * MB) {
1352 current_capacity_ *= 2;
1353 } else {
1354 current_capacity_ += 1 * MB;
1355 }
1356 if (current_capacity_ > max_capacity_) {
1357 current_capacity_ = max_capacity_;
1358 }
1359
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001360 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001361
1362 SetFootprintLimit(current_capacity_);
1363
1364 return true;
1365}
1366
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001367void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1368 Barrier barrier(0);
1369 size_t threads_running_checkpoint = 0;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001370 MarkCodeClosure closure(this, GetLiveBitmap(), &barrier);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001371 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1372 // Now that we have run our checkpoint, move to a suspended state and wait
1373 // for other threads to run the checkpoint.
1374 ScopedThreadSuspension sts(self, kSuspended);
1375 if (threads_running_checkpoint != 0) {
1376 barrier.Increment(self, threads_running_checkpoint);
1377 }
1378}
1379
Nicolas Geoffray35122442016-03-02 12:05:30 +00001380bool JitCodeCache::ShouldDoFullCollection() {
1381 if (current_capacity_ == max_capacity_) {
1382 // Always do a full collection when the code cache is full.
1383 return true;
1384 } else if (current_capacity_ < kReservedCapacity) {
1385 // Always do partial collection when the code cache size is below the reserved
1386 // capacity.
1387 return false;
1388 } else if (last_collection_increased_code_cache_) {
1389 // This time do a full collection.
1390 return true;
1391 } else {
1392 // This time do a partial collection.
1393 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001394 }
1395}
1396
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001397void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001398 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001399 if (!garbage_collect_code_) {
1400 MutexLock mu(self, lock_);
1401 IncreaseCodeCacheCapacity();
1402 return;
1403 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001404
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001405 // Wait for an existing collection, or let everyone know we are starting one.
1406 {
1407 ScopedThreadSuspension sts(self, kSuspended);
1408 MutexLock mu(self, lock_);
1409 if (WaitForPotentialCollectionToComplete(self)) {
1410 return;
1411 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001412 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001413 live_bitmap_.reset(CodeCacheBitmap::Create(
1414 "code-cache-bitmap",
Orion Hodson1d3fd082018-09-28 09:38:35 +01001415 reinterpret_cast<uintptr_t>(exec_pages_.Begin()),
1416 reinterpret_cast<uintptr_t>(exec_pages_.Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001417 collection_in_progress_ = true;
1418 }
1419 }
1420
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001421 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001422 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001423 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001424
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001425 bool do_full_collection = false;
1426 {
1427 MutexLock mu(self, lock_);
1428 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001429 }
1430
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001431 VLOG(jit) << "Do "
1432 << (do_full_collection ? "full" : "partial")
1433 << " code cache collection, code="
1434 << PrettySize(CodeCacheSize())
1435 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001436
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001437 DoCollection(self, /* collect_profiling_info= */ do_full_collection);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001438
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001439 VLOG(jit) << "After code cache collection, code="
1440 << PrettySize(CodeCacheSize())
1441 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001442
1443 {
1444 MutexLock mu(self, lock_);
1445
1446 // Increase the code cache only when we do partial collections.
1447 // TODO: base this strategy on how full the code cache is?
1448 if (do_full_collection) {
1449 last_collection_increased_code_cache_ = false;
1450 } else {
1451 last_collection_increased_code_cache_ = true;
1452 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001453 }
1454
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001455 bool next_collection_will_be_full = ShouldDoFullCollection();
1456
1457 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001458 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001459 // Save the entry point of methods we have compiled, and update the entry
1460 // point of those methods to the interpreter. If the method is invoked, the
1461 // interpreter will update its entry point to the compiled code and call it.
1462 for (ProfilingInfo* info : profiling_infos_) {
1463 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1464 if (ContainsPc(entry_point)) {
1465 info->SetSavedEntryPoint(entry_point);
Vladimir Marko2196c652017-11-30 16:16:07 +00001466 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001467 // class of the method. We may be concurrently running a GC which makes accessing
1468 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1469 // checked that the current entry point is JIT compiled code.
1470 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001471 }
1472 }
1473
1474 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Vladimir Marko2196c652017-11-30 16:16:07 +00001475
1476 // Change entry points of native methods back to the GenericJNI entrypoint.
1477 for (const auto& entry : jni_stubs_map_) {
1478 const JniStubData& data = entry.second;
1479 if (!data.IsCompiled()) {
1480 continue;
1481 }
1482 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1483 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1484 const OatQuickMethodHeader* method_header =
1485 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1486 for (ArtMethod* method : data.GetMethods()) {
1487 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1488 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1489 method->SetCounter(new_counter);
1490 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1491 }
1492 }
1493 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001494 }
1495 live_bitmap_.reset(nullptr);
1496 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001497 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001498 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001499 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001500}
1501
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001502void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001503 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001504 std::unordered_set<OatQuickMethodHeader*> method_headers;
1505 {
1506 MutexLock mu(self, lock_);
Calin Juravle016fcbe22018-05-03 19:47:35 -07001507 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -07001508 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001509 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1510 JniStubData* data = &it->second;
1511 if (!data->IsCompiled() || GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
1512 ++it;
1513 } else {
1514 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1515 it = jni_stubs_map_.erase(it);
1516 }
1517 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001518 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1519 const void* code_ptr = it->first;
1520 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1521 if (GetLiveBitmap()->Test(allocation)) {
1522 ++it;
1523 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001524 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1525 method_headers.insert(header);
Mingyao Yang063fc772016-08-02 11:02:54 -07001526 it = method_code_map_.erase(it);
1527 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001528 }
1529 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001530 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001531}
1532
1533void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001534 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001535 {
1536 MutexLock mu(self, lock_);
1537 if (collect_profiling_info) {
1538 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1539 // Also remove the saved entry point from the ProfilingInfo objects.
1540 for (ProfilingInfo* info : profiling_infos_) {
1541 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001542 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001543 info->GetMethod()->SetProfilingInfo(nullptr);
1544 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001545
1546 if (info->GetSavedEntryPoint() != nullptr) {
1547 info->SetSavedEntryPoint(nullptr);
1548 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001549 // give it a chance to be hot again.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001550 ClearMethodCounter(info->GetMethod(), /*was_warm=*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001551 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001552 }
1553 } else if (kIsDebugBuild) {
1554 // Sanity check that the profiling infos do not have a dangling entry point.
1555 for (ProfilingInfo* info : profiling_infos_) {
1556 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001557 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001558 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001559
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001560 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1561 // an entry point is either:
1562 // - an osr compiled code, that will be removed if not in a thread call stack.
1563 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001564 for (const auto& entry : jni_stubs_map_) {
1565 const JniStubData& data = entry.second;
1566 const void* code_ptr = data.GetCode();
1567 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1568 for (ArtMethod* method : data.GetMethods()) {
1569 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1570 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1571 break;
1572 }
1573 }
1574 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001575 for (const auto& it : method_code_map_) {
1576 ArtMethod* method = it.second;
1577 const void* code_ptr = it.first;
1578 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1579 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1580 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1581 }
1582 }
1583
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001584 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001585 // on thread stacks).
1586 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001587 }
1588
1589 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001590 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001591
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001592 // At this point, mutator threads are still running, and entrypoints of methods can
1593 // change. We do know they cannot change to a code cache entry that is not marked,
1594 // therefore we can safely remove those entries.
1595 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001596
Nicolas Geoffray35122442016-03-02 12:05:30 +00001597 if (collect_profiling_info) {
1598 MutexLock mu(self, lock_);
1599 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001600 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001601 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001602 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001603 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1604 // that the compiled code would not get revived. As mutator threads run concurrently,
1605 // they may have revived the compiled code, and now we are in the situation where
1606 // a method has compiled code but no ProfilingInfo.
1607 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1608 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001609 if (ContainsPc(ptr) &&
1610 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001611 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001612 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001613 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001614 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001615 return true;
1616 }
1617 return false;
1618 });
1619 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001620 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001621 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001622}
1623
Nicolas Geoffray35122442016-03-02 12:05:30 +00001624bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001625 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001626 // Check that methods we have compiled do have a ProfilingInfo object. We would
1627 // have memory leaks of compiled code otherwise.
1628 for (const auto& it : method_code_map_) {
1629 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001630 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001631 const void* code_ptr = it.first;
1632 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1633 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1634 // If the code is not dead, then we have a problem. Note that this can even
1635 // happen just after a collection, as mutator threads are running in parallel
1636 // and could deoptimize an existing compiled code.
1637 return false;
1638 }
1639 }
1640 }
1641 return true;
1642}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001643
1644OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001645 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1646 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001647 // On Thumb-2, the pc is offset by one.
1648 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001649 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001650 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1651 return nullptr;
1652 }
1653
Vladimir Marko2196c652017-11-30 16:16:07 +00001654 if (!kIsDebugBuild) {
1655 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1656 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001657 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001658
Vladimir Marko2196c652017-11-30 16:16:07 +00001659 MutexLock mu(Thread::Current(), lock_);
1660 OatQuickMethodHeader* method_header = nullptr;
1661 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1662 if (method != nullptr && UNLIKELY(method->IsNative())) {
1663 auto it = jni_stubs_map_.find(JniStubKey(method));
1664 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1665 return nullptr;
1666 }
1667 const void* code_ptr = it->second.GetCode();
1668 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1669 if (!method_header->Contains(pc)) {
1670 return nullptr;
1671 }
1672 } else {
1673 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1674 if (it != method_code_map_.begin()) {
1675 --it;
1676 const void* code_ptr = it->first;
1677 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1678 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1679 found_method = it->second;
1680 }
1681 }
1682 if (method_header == nullptr && method == nullptr) {
1683 // Scan all compiled JNI stubs as well. This slow search is used only
1684 // for checks in debug build, for release builds the `method` is not null.
1685 for (auto&& entry : jni_stubs_map_) {
1686 const JniStubData& data = entry.second;
1687 if (data.IsCompiled() &&
1688 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1689 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1690 }
1691 }
1692 }
1693 if (method_header == nullptr) {
1694 return nullptr;
1695 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001696 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001697
1698 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001699 // When we are walking the stack to redefine classes and creating obsolete methods it is
1700 // possible that we might have updated the method_code_map by making this method obsolete in a
1701 // previous frame. Therefore we should just check that the non-obsolete version of this method
1702 // is the one we expect. We change to the non-obsolete versions in the error message since the
1703 // obsolete version of the method might not be fully initialized yet. This situation can only
1704 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
Andreas Gampe06c42a52017-07-26 14:17:14 -07001705 // method and it->second should be identical. (See openjdkjvmti/ti_redefine.cc for more
Alex Light1ebe4fe2017-01-30 14:57:11 -08001706 // information.)
Vladimir Marko2196c652017-11-30 16:16:07 +00001707 DCHECK_EQ(found_method->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
Alex Light1ebe4fe2017-01-30 14:57:11 -08001708 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
Vladimir Marko2196c652017-11-30 16:16:07 +00001709 << ArtMethod::PrettyMethod(found_method->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001710 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001711 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001712 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001713}
1714
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001715OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1716 MutexLock mu(Thread::Current(), lock_);
1717 auto it = osr_code_map_.find(method);
1718 if (it == osr_code_map_.end()) {
1719 return nullptr;
1720 }
1721 return OatQuickMethodHeader::FromCodePointer(it->second);
1722}
1723
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001724ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1725 ArtMethod* method,
1726 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001727 bool retry_allocation)
1728 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1729 NO_THREAD_SAFETY_ANALYSIS {
1730 ProfilingInfo* info = nullptr;
1731 if (!retry_allocation) {
1732 // If we are allocating for the interpreter, just try to lock, to avoid
1733 // lock contention with the JIT.
1734 if (lock_.ExclusiveTryLock(self)) {
1735 info = AddProfilingInfoInternal(self, method, entries);
1736 lock_.ExclusiveUnlock(self);
1737 }
1738 } else {
1739 {
1740 MutexLock mu(self, lock_);
1741 info = AddProfilingInfoInternal(self, method, entries);
1742 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001743
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001744 if (info == nullptr) {
1745 GarbageCollectCache(self);
1746 MutexLock mu(self, lock_);
1747 info = AddProfilingInfoInternal(self, method, entries);
1748 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001749 }
1750 return info;
1751}
1752
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001753ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001754 ArtMethod* method,
1755 const std::vector<uint32_t>& entries) {
1756 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001757 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001758 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001759
1760 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001761 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001762 if (info != nullptr) {
1763 return info;
1764 }
1765
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001766 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001767 if (data == nullptr) {
1768 return nullptr;
1769 }
1770 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001771
1772 // Make sure other threads see the data in the profiling info object before the
1773 // store in the ArtMethod's ProfilingInfo pointer.
Orion Hodson27b96762018-03-13 16:06:57 +00001774 std::atomic_thread_fence(std::memory_order_release);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001775
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001776 method->SetProfilingInfo(info);
1777 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001778 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001779 return info;
1780}
1781
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001782// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1783// is already held.
1784void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
Orion Hodson1d3fd082018-09-28 09:38:35 +01001785 if (mspace == exec_mspace_) {
1786 DCHECK(exec_mspace_ != nullptr);
1787 const MemMap* const code_pages = GetUpdatableCodeMapping();
1788 void* result = code_pages->Begin() + exec_end_;
1789 exec_end_ += increment;
1790 return result;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001791 } else {
1792 DCHECK_EQ(data_mspace_, mspace);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001793 void* result = data_pages_.Begin() + data_end_;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001794 data_end_ += increment;
Orion Hodson1d3fd082018-09-28 09:38:35 +01001795 return result;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001796 }
1797}
1798
Calin Juravle99629622016-04-19 16:33:46 +01001799void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001800 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001801 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001802 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001803 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001804 for (const ProfilingInfo* info : profiling_infos_) {
1805 ArtMethod* method = info->GetMethod();
1806 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001807 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1808 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001809 // Skip dex files which are not profiled.
1810 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001811 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001812 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001813
1814 // If the method didn't reach the compilation threshold don't save the inline caches.
1815 // They might be incomplete and cause unnecessary deoptimizations.
1816 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1817 if (method->GetCounter() < jit_compile_threshold) {
1818 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001819 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001820 continue;
1821 }
1822
Calin Juravle940eb0c2017-01-30 19:30:44 -08001823 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001824 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001825 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001826 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001827 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001828 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1829 mirror::Class* cls = cache.classes_[k].Read();
1830 if (cls == nullptr) {
1831 break;
1832 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001833
Calin Juravle13439f02017-02-21 01:17:21 -08001834 // Check if the receiver is in the boot class path or if it's in the
1835 // same class loader as the caller. If not, skip it, as there is not
1836 // much we can do during AOT.
1837 if (!cls->IsBootStrapClassLoaded() &&
1838 caller->GetClassLoader() != cls->GetClassLoader()) {
1839 is_missing_types = true;
1840 continue;
1841 }
1842
Calin Juravle4ca70a32017-02-21 16:22:24 -08001843 const DexFile* class_dex_file = nullptr;
1844 dex::TypeIndex type_index;
1845
1846 if (cls->GetDexCache() == nullptr) {
1847 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001848 // Make a best effort to find the type index in the method's dex file.
1849 // We could search all open dex files but that might turn expensive
1850 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001851 class_dex_file = dex_file;
1852 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1853 } else {
1854 class_dex_file = &(cls->GetDexFile());
1855 type_index = cls->GetDexTypeIndex();
1856 }
1857 if (!type_index.IsValid()) {
1858 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001859 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001860 continue;
1861 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001862 if (ContainsElement(dex_base_locations,
1863 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001864 // Only consider classes from the same apk (including multidex).
1865 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001866 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001867 } else {
1868 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001869 }
1870 }
1871 if (!profile_classes.empty()) {
1872 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001873 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001874 }
1875 }
1876 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001877 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001878 }
1879}
1880
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001881bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1882 MutexLock mu(Thread::Current(), lock_);
1883 return osr_code_map_.find(method) != osr_code_map_.end();
1884}
1885
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001886bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1887 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001888 return false;
1889 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001890
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001891 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001892 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1893 return false;
1894 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001895
Vladimir Marko2196c652017-11-30 16:16:07 +00001896 if (UNLIKELY(method->IsNative())) {
1897 JniStubKey key(method);
1898 auto it = jni_stubs_map_.find(key);
1899 bool new_compilation = false;
1900 if (it == jni_stubs_map_.end()) {
1901 // Create a new entry to mark the stub as being compiled.
1902 it = jni_stubs_map_.Put(key, JniStubData{});
1903 new_compilation = true;
1904 }
1905 JniStubData* data = &it->second;
1906 data->AddMethod(method);
1907 if (data->IsCompiled()) {
1908 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1909 const void* entrypoint = method_header->GetEntryPoint();
1910 // Update also entrypoints of other methods held by the JniStubData.
1911 // We could simply update the entrypoint of `method` but if the last JIT GC has
1912 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1913 // as well change them back as this stub shall not be collected anyway and this
1914 // can avoid a few expensive GenericJNI calls.
1915 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1916 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +00001917 // Call the dedicated method instead of the more generic UpdateMethodsCode, because
1918 // `m` might be in the process of being deleted.
1919 instrumentation->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
Vladimir Marko2196c652017-11-30 16:16:07 +00001920 }
1921 if (collection_in_progress_) {
1922 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1923 }
1924 }
1925 return new_compilation;
1926 } else {
1927 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1928 if (info == nullptr) {
1929 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1930 // Because the counter is not atomic, there are some rare cases where we may not hit the
1931 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001932 ClearMethodCounter(method, /*was_warm=*/ false);
Vladimir Marko2196c652017-11-30 16:16:07 +00001933 return false;
1934 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001935
Vladimir Marko2196c652017-11-30 16:16:07 +00001936 if (info->IsMethodBeingCompiled(osr)) {
1937 return false;
1938 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001939
Vladimir Marko2196c652017-11-30 16:16:07 +00001940 info->SetIsMethodBeingCompiled(true, osr);
1941 return true;
1942 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001943}
1944
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001945ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001946 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001947 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001948 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001949 if (!info->IncrementInlineUse()) {
1950 // Overflow of inlining uses, just bail.
1951 return nullptr;
1952 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001953 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001954 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001955}
1956
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001957void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001958 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001959 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001960 DCHECK(info != nullptr);
1961 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001962}
1963
Vladimir Marko2196c652017-11-30 16:16:07 +00001964void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
1965 DCHECK_EQ(Thread::Current(), self);
1966 MutexLock mu(self, lock_);
1967 if (UNLIKELY(method->IsNative())) {
1968 auto it = jni_stubs_map_.find(JniStubKey(method));
1969 DCHECK(it != jni_stubs_map_.end());
1970 JniStubData* data = &it->second;
1971 DCHECK(ContainsElement(data->GetMethods(), method));
1972 if (UNLIKELY(!data->IsCompiled())) {
1973 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1974 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
1975 } // else CommitCodeInternal() updated entrypoints of all methods in the JniStubData.
1976 } else {
1977 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1978 DCHECK(info->IsMethodBeingCompiled(osr));
1979 info->SetIsMethodBeingCompiled(false, osr);
1980 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001981}
1982
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001983void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1984 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001985 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07001986 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Alex Light2d441b12018-06-08 15:33:21 -07001987 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001988 if ((profiling_info != nullptr) &&
1989 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
Alex Light2d441b12018-06-08 15:33:21 -07001990 // When instrumentation is set, the actual entrypoint is the one in the profiling info.
1991 method_entrypoint = profiling_info->GetSavedEntryPoint();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001992 // Prevent future uses of the compiled code.
1993 profiling_info->SetSavedEntryPoint(nullptr);
1994 }
1995
Alex Light2d441b12018-06-08 15:33:21 -07001996 // Clear the method counter if we are running jitted code since we might want to jit this again in
1997 // the future.
1998 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001999 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07002000 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00002001 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
2002 method, GetQuickToInterpreterBridge());
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002003 ClearMethodCounter(method, /*was_warm=*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00002004 } else {
2005 MutexLock mu(Thread::Current(), lock_);
2006 auto it = osr_code_map_.find(method);
2007 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
2008 // Remove the OSR method, to avoid using it again.
2009 osr_code_map_.erase(it);
2010 }
2011 }
2012}
2013
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002014uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
2015 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
2016 uint8_t* result = reinterpret_cast<uint8_t*>(
Orion Hodson1d3fd082018-09-28 09:38:35 +01002017 mspace_memalign(exec_mspace_, alignment, code_size));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002018 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
2019 // Ensure the header ends up at expected instruction alignment.
2020 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
2021 used_memory_for_code_ += mspace_usable_size(result);
2022 return result;
2023}
2024
Orion Hodsondbd05fe2017-08-10 11:41:35 +01002025void JitCodeCache::FreeCode(uint8_t* code) {
2026 used_memory_for_code_ -= mspace_usable_size(code);
Orion Hodson1d3fd082018-09-28 09:38:35 +01002027 mspace_free(exec_mspace_, code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002028}
2029
2030uint8_t* JitCodeCache::AllocateData(size_t data_size) {
2031 void* result = mspace_malloc(data_mspace_, data_size);
2032 used_memory_for_data_ += mspace_usable_size(result);
2033 return reinterpret_cast<uint8_t*>(result);
2034}
2035
2036void JitCodeCache::FreeData(uint8_t* data) {
2037 used_memory_for_data_ -= mspace_usable_size(data);
2038 mspace_free(data_mspace_, data);
2039}
2040
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002041void JitCodeCache::Dump(std::ostream& os) {
2042 MutexLock mu(Thread::Current(), lock_);
David Srbeckyfb3de3d2018-01-29 16:11:49 +00002043 MutexLock mu2(Thread::Current(), *Locks::native_debug_interface_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002044 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
2045 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
David Srbecky440a9b32018-02-15 17:47:29 +00002046 << "Current JIT mini-debug-info size: " << PrettySize(GetJitNativeDebugInfoMemUsage()) << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002047 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00002048 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002049 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
2050 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
2051 << "Total number of JIT compilations for on stack replacement: "
2052 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002053 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00002054 histogram_stack_map_memory_use_.PrintMemoryUse(os);
2055 histogram_code_memory_use_.PrintMemoryUse(os);
2056 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002057}
2058
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002059} // namespace jit
2060} // namespace art