blob: 31319f110611f275bb8628e8edc97c526802d4da [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 Gampe5629d2d2017-05-15 16:28:13 -070021#include "arch/context.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070022#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070023#include "base/enums.h"
Calin Juravle66f55232015-12-08 15:09:10 +000024#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080025#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010026#include "base/time_utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070027#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000028#include "debugger_interface.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010029#include "entrypoints/runtime_asm_entrypoints.h"
30#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010031#include "gc/scoped_gc_critical_section.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070032#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000033#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000034#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010035#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080036#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080037#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070038#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070039#include "object_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070040#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070041#include "stack.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010042#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080043
44namespace art {
45namespace jit {
46
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010047static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
48static constexpr int kProtData = PROT_READ | PROT_WRITE;
49static constexpr int kProtCode = PROT_READ | PROT_EXEC;
David Sehrd1dbb742017-07-17 11:20:38 -070050static constexpr int kProtReadOnly = PROT_READ;
51static constexpr int kProtNone = PROT_NONE;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010052
Nicolas Geoffray933330a2016-03-16 14:20:06 +000053static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
54static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
David Sehrd1dbb742017-07-17 11:20:38 -070055static constexpr size_t kMinMapSpacingPages = 1;
56static constexpr size_t kMaxMapSpacingPages = 128;
Nicolas Geoffray933330a2016-03-16 14:20:06 +000057
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010058#define CHECKED_MPROTECT(memory, size, prot) \
59 do { \
60 int rc = mprotect(memory, size, prot); \
61 if (UNLIKELY(rc != 0)) { \
62 errno = rc; \
63 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
64 } \
65 } while (false) \
66
David Sehrd1dbb742017-07-17 11:20:38 -070067static MemMap* SplitMemMap(MemMap* existing_map,
68 const char* name,
69 size_t split_offset,
70 int split_prot,
71 std::string* error_msg,
72 bool use_ashmem,
73 unique_fd* shmem_fd = nullptr) {
74 std::string error_str;
75 uint8_t* divider = existing_map->Begin() + split_offset;
76 MemMap* new_map = existing_map->RemapAtEnd(divider,
77 name,
78 split_prot,
79 MAP_SHARED,
80 &error_str,
81 use_ashmem,
82 shmem_fd);
83 if (new_map == nullptr) {
84 std::ostringstream oss;
85 oss << "Failed to create spacing for " << name << ": "
86 << error_str << " offset=" << split_offset;
87 *error_msg = oss.str();
88 return nullptr;
89 }
90 return new_map;
91}
92
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000093JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
94 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000095 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000096 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080097 ScopedTrace trace(__PRETTY_FUNCTION__);
David Sehrd1dbb742017-07-17 11:20:38 -070098 CHECK_GT(max_capacity, initial_capacity);
99 CHECK_GE(max_capacity - kMaxMapSpacingPages * kPageSize, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000100
David Sehrd1dbb742017-07-17 11:20:38 -0700101 // Generating debug information is for using the Linux perf tool on
102 // host which does not work with ashmem.
Nicolas Geoffray520dadf2017-07-19 15:33:11 +0100103 // Also, target linux does not support ashmem.
104 bool use_ashmem = !generate_debug_info && !kIsTargetLinux;
David Sehrd1dbb742017-07-17 11:20:38 -0700105
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000106 // With 'perf', we want a 1-1 mapping between an address and a method.
107 bool garbage_collect_code = !generate_debug_info;
108
David Sehrd1dbb742017-07-17 11:20:38 -0700109 // We only use two mappings (separating rw from rx) if we are able to use ashmem.
110 // See the above comment for debug information and not using ashmem.
Nicolas Geoffray520dadf2017-07-19 15:33:11 +0100111 bool use_two_mappings = use_ashmem;
David Sehrd1dbb742017-07-17 11:20:38 -0700112
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000113 // We need to have 32 bit offsets from method headers in code cache which point to things
114 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
115 // Ensure we're below 1 GB to be safe.
116 if (max_capacity > 1 * GB) {
117 std::ostringstream oss;
118 oss << "Maxium code cache capacity is limited to 1 GB, "
119 << PrettySize(max_capacity) << " is too big";
120 *error_msg = oss.str();
121 return nullptr;
122 }
123
Orion Hodson56fe32e2017-07-21 11:42:10 +0100124 // Align both capacities to page size, as that's the unit mspaces use.
125 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
126 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
127
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800128 std::string error_str;
129 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000130 // Map in low 4gb to simplify accessing root tables for x86_64.
131 // We could do PC-relative addressing to avoid this problem, but that
132 // would require reserving code and data area before submitting, which
133 // means more windows for the code memory to be RWX.
Andreas Gampee4deaf32017-06-09 15:27:15 -0700134 std::unique_ptr<MemMap> data_map(MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000135 "data-code-cache", nullptr,
136 max_capacity,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700137 kProtData,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000138 /* low_4gb */ true,
139 /* reuse */ false,
140 &error_str,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700141 use_ashmem));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100142 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800143 std::ostringstream oss;
Andreas Gampee4deaf32017-06-09 15:27:15 -0700144 oss << "Failed to create read write cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800145 *error_msg = oss.str();
146 return nullptr;
147 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100148
David Sehrd1dbb742017-07-17 11:20:38 -0700149 // Create a region for JIT data and executable code. This will be
150 // laid out as:
151 //
152 // +----------------+ --------------------
Orion Hodson56fe32e2017-07-21 11:42:10 +0100153 // | code_sync_map_ | ^ code_sync_size ^
154 // | | v |
155 // +----------------+ -- |
156 // : : ^ |
David Sehrd1dbb742017-07-17 11:20:38 -0700157 // : post_code_map : | post_code_size |
158 // : [padding] : v |
159 // +----------------+ - |
160 // | | ^ |
Orion Hodson56fe32e2017-07-21 11:42:10 +0100161 // | code_map | | code_size | total_mapping_size
David Sehrd1dbb742017-07-17 11:20:38 -0700162 // | [JIT Code] | v |
Orion Hodson56fe32e2017-07-21 11:42:10 +0100163 // +----------------+ - |
David Sehrd1dbb742017-07-17 11:20:38 -0700164 // : : ^ |
165 // : pre_code_map : | pre_code_size |
166 // : [padding] : v |
167 // +----------------+ - |
168 // | | ^ |
169 // | data_map | | data_size |
170 // | [Jit Data] | v v
171 // +----------------+ --------------------
172 //
Orion Hodson56fe32e2017-07-21 11:42:10 +0100173 // The code_sync_map_ contains a page that we use flush CPU instruction
174 // pipelines (see FlushInstructionPipelines()).
175 //
David Sehrd1dbb742017-07-17 11:20:38 -0700176 // The padding regions - pre_code_map and post_code_map - exist to
177 // put some random distance between the writable JIT code mapping
178 // and the executable mapping. The padding is discarded at the end
179 // of this function.
Orion Hodson56fe32e2017-07-21 11:42:10 +0100180 //
181 size_t data_size = (max_capacity - kMaxMapSpacingPages * kPageSize) / 2;
David Sehrd1dbb742017-07-17 11:20:38 -0700182 size_t pre_code_size =
Orion Hodson56fe32e2017-07-21 11:42:10 +0100183 GetRandomNumber(kMinMapSpacingPages, kMaxMapSpacingPages - 1) * kPageSize;
184 size_t code_size = max_capacity - data_size - kMaxMapSpacingPages * kPageSize;
185 size_t code_sync_size = kPageSize;
186 size_t post_code_size = kMaxMapSpacingPages * kPageSize - pre_code_size - code_sync_size;
187 DCHECK_EQ(data_size, code_size);
188 DCHECK_EQ(pre_code_size + post_code_size + code_sync_size, kMaxMapSpacingPages * kPageSize);
189 DCHECK_EQ(data_size + pre_code_size + code_size + post_code_size + code_sync_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100190
David Sehrd1dbb742017-07-17 11:20:38 -0700191 // Create pre-code padding region after data region, discarded after
192 // code and data regions are set-up.
193 std::unique_ptr<MemMap> pre_code_map(SplitMemMap(data_map.get(),
194 "jit-code-cache-padding",
195 data_size,
196 kProtNone,
197 error_msg,
198 use_ashmem));
199 if (pre_code_map == nullptr) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100200 return nullptr;
201 }
David Sehrd1dbb742017-07-17 11:20:38 -0700202 DCHECK_EQ(data_map->Size(), data_size);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100203 DCHECK_EQ(pre_code_map->Size(), pre_code_size + code_size + post_code_size + code_sync_size);
David Sehrd1dbb742017-07-17 11:20:38 -0700204
205 // Create code region.
206 unique_fd writable_code_fd;
207 std::unique_ptr<MemMap> code_map(SplitMemMap(pre_code_map.get(),
208 "jit-code-cache",
209 pre_code_size,
210 use_two_mappings ? kProtCode : kProtAll,
211 error_msg,
212 use_ashmem,
213 &writable_code_fd));
214 if (code_map == nullptr) {
215 return nullptr;
216 }
217 DCHECK_EQ(pre_code_map->Size(), pre_code_size);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100218 DCHECK_EQ(code_map->Size(), code_size + post_code_size + code_sync_size);
David Sehrd1dbb742017-07-17 11:20:38 -0700219
220 // Padding after code region, discarded after code and data regions
221 // are set-up.
222 std::unique_ptr<MemMap> post_code_map(SplitMemMap(code_map.get(),
223 "jit-code-cache-padding",
224 code_size,
225 kProtNone,
226 error_msg,
227 use_ashmem));
228 if (post_code_map == nullptr) {
229 return nullptr;
230 }
231 DCHECK_EQ(code_map->Size(), code_size);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100232 DCHECK_EQ(post_code_map->Size(), post_code_size + code_sync_size);
233
234 std::unique_ptr<MemMap> code_sync_map(SplitMemMap(post_code_map.get(),
235 "jit-code-sync",
236 post_code_size,
Nicolas Geoffray8bb17862017-08-03 17:42:37 +0000237 kProtCode,
Orion Hodson56fe32e2017-07-21 11:42:10 +0100238 error_msg,
239 use_ashmem));
240 if (code_sync_map == nullptr) {
241 return nullptr;
242 }
David Sehrd1dbb742017-07-17 11:20:38 -0700243 DCHECK_EQ(post_code_map->Size(), post_code_size);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100244 DCHECK_EQ(code_sync_map->Size(), code_sync_size);
David Sehrd1dbb742017-07-17 11:20:38 -0700245
246 std::unique_ptr<MemMap> writable_code_map;
247 if (use_two_mappings) {
248 // Allocate the R/W view.
249 writable_code_map.reset(MemMap::MapFile(code_size,
250 kProtData,
251 MAP_SHARED,
252 writable_code_fd.get(),
253 /* start */ 0,
254 /* low_4gb */ true,
255 "jit-writable-code",
256 &error_str));
257 if (writable_code_map == nullptr) {
258 std::ostringstream oss;
259 oss << "Failed to create writable code cache: " << error_str << " size=" << code_size;
260 *error_msg = oss.str();
261 return nullptr;
262 }
263 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000264 data_size = initial_capacity / 2;
265 code_size = initial_capacity - data_size;
266 DCHECK_EQ(code_size + data_size, initial_capacity);
David Sehrd1dbb742017-07-17 11:20:38 -0700267 return new JitCodeCache(writable_code_map.release(),
268 code_map.release(),
269 data_map.release(),
Orion Hodson56fe32e2017-07-21 11:42:10 +0100270 code_sync_map.release(),
David Sehrd1dbb742017-07-17 11:20:38 -0700271 code_size,
272 data_size,
273 max_capacity,
274 garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800275}
276
David Sehrd1dbb742017-07-17 11:20:38 -0700277JitCodeCache::JitCodeCache(MemMap* writable_code_map,
278 MemMap* executable_code_map,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000279 MemMap* data_map,
Orion Hodson56fe32e2017-07-21 11:42:10 +0100280 MemMap* code_sync_map,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000281 size_t initial_code_capacity,
282 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000283 size_t max_capacity,
284 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100285 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000286 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100287 collection_in_progress_(false),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000288 data_map_(data_map),
David Sehrd1dbb742017-07-17 11:20:38 -0700289 executable_code_map_(executable_code_map),
290 writable_code_map_(writable_code_map),
Orion Hodson56fe32e2017-07-21 11:42:10 +0100291 code_sync_map_(code_sync_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000292 max_capacity_(max_capacity),
293 current_capacity_(initial_code_capacity + initial_data_capacity),
294 code_end_(initial_code_capacity),
295 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000296 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000297 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000298 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000299 used_memory_for_data_(0),
300 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000301 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000302 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000303 number_of_collections_(0),
304 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
305 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000306 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
307 is_weak_access_enabled_(true),
308 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100309
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000310 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
David Sehrd1dbb742017-07-17 11:20:38 -0700311 MemMap* writable_map = GetWritableMemMap();
312 code_mspace_ = create_mspace_with_base(writable_map->Begin(), code_end_, false /*locked*/);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000313 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100314
315 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
316 PLOG(FATAL) << "create_mspace_with_base failed";
317 }
318
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000319 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100320
David Sehrd1dbb742017-07-17 11:20:38 -0700321 if (writable_code_map_ != nullptr) {
322 CHECKED_MPROTECT(writable_code_map_->Begin(), writable_code_map_->Size(), kProtReadOnly);
323 }
324 CHECKED_MPROTECT(executable_code_map_->Begin(), executable_code_map_->Size(), kProtCode);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100325 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100326
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000327 VLOG(jit) << "Created jit code cache: initial data size="
328 << PrettySize(initial_data_capacity)
329 << ", initial code size="
330 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800331}
332
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100333bool JitCodeCache::ContainsPc(const void* ptr) const {
David Sehrd1dbb742017-07-17 11:20:38 -0700334 return executable_code_map_->Begin() <= ptr && ptr < executable_code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800335}
336
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000337bool JitCodeCache::ContainsMethod(ArtMethod* method) {
338 MutexLock mu(Thread::Current(), lock_);
339 for (auto& it : method_code_map_) {
340 if (it.second == method) {
341 return true;
342 }
343 }
344 return false;
345}
346
David Sehrd1dbb742017-07-17 11:20:38 -0700347/* This method is only for CHECK/DCHECK that pointers are within to a region. */
348static bool IsAddressInMap(const void* addr,
349 const MemMap* mem_map,
350 const char* check_name) {
351 if (addr == nullptr || mem_map->HasAddress(addr)) {
352 return true;
353 }
354 LOG(ERROR) << "Is" << check_name << "Address " << addr
355 << " not in [" << reinterpret_cast<void*>(mem_map->Begin())
356 << ", " << reinterpret_cast<void*>(mem_map->Begin() + mem_map->Size()) << ")";
357 return false;
358}
359
360bool JitCodeCache::IsDataAddress(const void* raw_addr) const {
361 return IsAddressInMap(raw_addr, data_map_.get(), "Data");
362}
363
364bool JitCodeCache::IsExecutableAddress(const void* raw_addr) const {
365 return IsAddressInMap(raw_addr, executable_code_map_.get(), "Executable");
366}
367
368bool JitCodeCache::IsWritableAddress(const void* raw_addr) const {
369 return IsAddressInMap(raw_addr, GetWritableMemMap(), "Writable");
370}
371
372// Convert one address within the source map to the same offset within the destination map.
373static void* ConvertAddress(const void* source_address,
374 const MemMap* source_map,
375 const MemMap* destination_map) {
376 DCHECK(source_map->HasAddress(source_address)) << source_address;
377 ptrdiff_t offset = reinterpret_cast<const uint8_t*>(source_address) - source_map->Begin();
378 uintptr_t address = reinterpret_cast<uintptr_t>(destination_map->Begin()) + offset;
379 return reinterpret_cast<void*>(address);
380}
381
382template <typename T>
383T* JitCodeCache::ToExecutableAddress(T* writable_address) const {
384 CHECK(IsWritableAddress(writable_address));
385 if (writable_address == nullptr) {
386 return nullptr;
387 }
388 void* executable_address = ConvertAddress(writable_address,
389 GetWritableMemMap(),
390 executable_code_map_.get());
391 CHECK(IsExecutableAddress(executable_address));
392 return reinterpret_cast<T*>(executable_address);
393}
394
395void* JitCodeCache::ToWritableAddress(const void* executable_address) const {
396 CHECK(IsExecutableAddress(executable_address));
397 if (executable_address == nullptr) {
398 return nullptr;
399 }
400 void* writable_address = ConvertAddress(executable_address,
401 executable_code_map_.get(),
402 GetWritableMemMap());
403 CHECK(IsWritableAddress(writable_address));
404 return writable_address;
405}
406
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800407class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100408 public:
Orion Hodson56fe32e2017-07-21 11:42:10 +0100409 explicit ScopedCodeCacheWrite(JitCodeCache* code_cache)
David Sehrd1dbb742017-07-17 11:20:38 -0700410 : ScopedTrace("ScopedCodeCacheWrite") {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800411 ScopedTrace trace("mprotect all");
David Sehrd1dbb742017-07-17 11:20:38 -0700412 int prot_to_start_writing = kProtAll;
413 if (code_cache->writable_code_map_ == nullptr) {
414 // If there is only one mapping, use the executable mapping and toggle between rwx and rx.
415 prot_to_start_writing = kProtAll;
416 prot_to_stop_writing_ = kProtCode;
417 } else {
418 // If there are two mappings, use the writable mapping and toggle between rw and r.
419 prot_to_start_writing = kProtData;
420 prot_to_stop_writing_ = kProtReadOnly;
421 }
422 writable_map_ = code_cache->GetWritableMemMap();
423 // If we're using ScopedCacheWrite only for TLB shootdown, we limit the scope of mprotect to
424 // one page.
Orion Hodson56fe32e2017-07-21 11:42:10 +0100425 size_ = writable_map_->Size();
David Sehrd1dbb742017-07-17 11:20:38 -0700426 CHECKED_MPROTECT(writable_map_->Begin(), size_, prot_to_start_writing);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800427 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100428 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800429 ScopedTrace trace("mprotect code");
David Sehrd1dbb742017-07-17 11:20:38 -0700430 CHECKED_MPROTECT(writable_map_->Begin(), size_, prot_to_stop_writing_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100431 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100432
David Sehrd1dbb742017-07-17 11:20:38 -0700433 private:
434 int prot_to_stop_writing_;
435 MemMap* writable_map_;
436 size_t size_;
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100437
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100438 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
439};
440
441uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100442 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000443 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700444 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000445 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100446 size_t frame_size_in_bytes,
447 size_t core_spill_mask,
448 size_t fp_spill_mask,
449 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000450 size_t code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000451 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700452 Handle<mirror::ObjectArray<mirror::Object>> roots,
453 bool has_should_deoptimize_flag,
454 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100455 uint8_t* result = CommitCodeInternal(self,
456 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000457 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700458 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000459 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100460 frame_size_in_bytes,
461 core_spill_mask,
462 fp_spill_mask,
463 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000464 code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000465 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700466 roots,
467 has_should_deoptimize_flag,
468 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100469 if (result == nullptr) {
470 // Retry.
471 GarbageCollectCache(self);
472 result = CommitCodeInternal(self,
473 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000474 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700475 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000476 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100477 frame_size_in_bytes,
478 core_spill_mask,
479 fp_spill_mask,
480 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000481 code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000482 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700483 roots,
484 has_should_deoptimize_flag,
485 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100486 }
487 return result;
488}
489
490bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
491 bool in_collection = false;
492 while (collection_in_progress_) {
493 in_collection = true;
494 lock_cond_.Wait(self);
495 }
496 return in_collection;
497}
498
499static uintptr_t FromCodeToAllocation(const void* code) {
500 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
501 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
502}
503
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000504static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
505 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
506}
507
508static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
509 // The length of the table is stored just before the stack map (and therefore at the end of
510 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
511 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
512}
513
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800514static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
515 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
516 // pointer.
517 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
518}
519
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000520static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
521 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
522}
523
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000524static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
525 REQUIRES_SHARED(Locks::mutator_lock_) {
526 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800527 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000528 // Put all roots in `roots_data`.
529 for (uint32_t i = 0; i < length; ++i) {
530 ObjPtr<mirror::Object> object = roots->Get(i);
531 if (kIsDebugBuild) {
532 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000533 if (object->IsString()) {
534 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
535 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
536 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
537 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000538 }
539 gc_roots[i] = GcRoot<mirror::Object>(object);
540 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000541}
542
David Sehrd1dbb742017-07-17 11:20:38 -0700543uint8_t* JitCodeCache::GetRootTable(const void* code_ptr, uint32_t* number_of_roots) {
544 CHECK(IsExecutableAddress(code_ptr));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000545 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
David Sehrd1dbb742017-07-17 11:20:38 -0700546 // GetOptimizedCodeInfoPtr uses offsets relative to the EXECUTABLE address.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000547 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
548 uint32_t roots = GetNumberOfRoots(data);
549 if (number_of_roots != nullptr) {
550 *number_of_roots = roots;
551 }
552 return data - ComputeRootTableSize(roots);
553}
554
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100555// Use a sentinel for marking entries in the JIT table that have been cleared.
556// This helps diagnosing in case the compiled code tries to wrongly access such
557// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700558static mirror::Class* const weak_sentinel =
559 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100560
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000561// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100562static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
563 IsMarkedVisitor* visitor,
564 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000565 REQUIRES_SHARED(Locks::mutator_lock_) {
566 // This does not need a read barrier because this is called by GC.
567 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100568 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000569 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
570 // Look at the classloader of the class to know if it has been unloaded.
571 // This does not need a read barrier because this is called by GC.
572 mirror::Object* class_loader =
573 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
574 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
575 // The class loader is live, update the entry if the class has moved.
576 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
577 // Note that new_object can be null for CMS and newly allocated objects.
578 if (new_cls != nullptr && new_cls != cls) {
579 *root_ptr = GcRoot<mirror::Class>(new_cls);
580 }
581 } else {
582 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100583 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000584 }
585 }
586}
587
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000588void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
589 MutexLock mu(Thread::Current(), lock_);
590 for (const auto& entry : method_code_map_) {
David Sehrd1dbb742017-07-17 11:20:38 -0700591 // GetRootTable takes an EXECUTABLE address.
592 CHECK(IsExecutableAddress(entry.first));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000593 uint32_t number_of_roots = 0;
594 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
595 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
596 for (uint32_t i = 0; i < number_of_roots; ++i) {
597 // This does not need a read barrier because this is called by GC.
598 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100599 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000600 // entry got deleted in a previous sweep.
601 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
602 mirror::Object* new_object = visitor->IsMarked(object);
603 // We know the string is marked because it's a strongly-interned string that
604 // is always alive. The IsMarked implementation of the CMS collector returns
605 // null for newly allocated objects, but we know those haven't moved. Therefore,
606 // only update the entry if we get a different non-null string.
607 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
608 // out of the weak access/creation pause. b/32167580
609 if (new_object != nullptr && new_object != object) {
610 DCHECK(new_object->IsString());
611 roots[i] = GcRoot<mirror::Object>(new_object);
612 }
613 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100614 ProcessWeakClass(
615 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000616 }
617 }
618 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000619 // Walk over inline caches to clear entries containing unloaded classes.
620 for (ProfilingInfo* info : profiling_infos_) {
621 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
622 InlineCache* cache = &info->cache_[i];
623 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100624 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000625 }
626 }
627 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000628}
629
David Sehrd1dbb742017-07-17 11:20:38 -0700630void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
631 CHECK(IsExecutableAddress(code_ptr));
David Srbecky5cc349f2015-12-18 15:04:48 +0000632 // Notify native debugger that we are about to remove the code.
633 // It does nothing if we are not using native debugger.
634 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
David Sehrd1dbb742017-07-17 11:20:38 -0700635 // GetRootTable takes an EXECUTABLE address.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000636 FreeData(GetRootTable(code_ptr));
David Sehrd1dbb742017-07-17 11:20:38 -0700637 FreeRawCode(reinterpret_cast<uint8_t*>(FromCodeToAllocation(code_ptr)));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100638}
639
Mingyao Yang063fc772016-08-02 11:02:54 -0700640void JitCodeCache::FreeAllMethodHeaders(
641 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
David Sehrd1dbb742017-07-17 11:20:38 -0700642 // method_headers are expected to be in the executable region.
Mingyao Yang063fc772016-08-02 11:02:54 -0700643 {
644 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700645 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
Mingyao Yang063fc772016-08-02 11:02:54 -0700646 ->RemoveDependentsWithMethodHeaders(method_headers);
647 }
648
649 // We need to remove entries in method_headers from CHA dependencies
650 // first since once we do FreeCode() below, the memory can be reused
651 // so it's possible for the same method_header to start representing
652 // different compile code.
653 MutexLock mu(Thread::Current(), lock_);
David Sehrd1dbb742017-07-17 11:20:38 -0700654 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700655 for (const OatQuickMethodHeader* method_header : method_headers) {
David Sehrd1dbb742017-07-17 11:20:38 -0700656 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700657 }
658}
659
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100660void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800661 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700662 // We use a set to first collect all method_headers whose code need to be
663 // removed. We need to free the underlying code after we remove CHA dependencies
664 // for entries in this set. And it's more efficient to iterate through
665 // the CHA dependency map just once with an unordered_set.
666 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000667 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700668 MutexLock mu(self, lock_);
669 // We do not check if a code cache GC is in progress, as this method comes
670 // with the classlinker_classes_lock_ held, and suspending ourselves could
671 // lead to a deadlock.
672 {
David Sehrd1dbb742017-07-17 11:20:38 -0700673 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700674 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
675 if (alloc.ContainsUnsafe(it->second)) {
David Sehrd1dbb742017-07-17 11:20:38 -0700676 CHECK(IsExecutableAddress(OatQuickMethodHeader::FromCodePointer(it->first)));
Mingyao Yang063fc772016-08-02 11:02:54 -0700677 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
678 it = method_code_map_.erase(it);
679 } else {
680 ++it;
681 }
682 }
683 }
684 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
685 if (alloc.ContainsUnsafe(it->first)) {
686 // Note that the code has already been pushed to method_headers in the loop
687 // above and is going to be removed in FreeCode() below.
688 it = osr_code_map_.erase(it);
689 } else {
690 ++it;
691 }
692 }
693 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
694 ProfilingInfo* info = *it;
695 if (alloc.ContainsUnsafe(info->GetMethod())) {
696 info->GetMethod()->SetProfilingInfo(nullptr);
697 FreeData(reinterpret_cast<uint8_t*>(info));
698 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000699 } else {
700 ++it;
701 }
702 }
703 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700704 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100705}
706
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000707bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
708 return kUseReadBarrier
709 ? self->GetWeakRefAccessEnabled()
710 : is_weak_access_enabled_.LoadSequentiallyConsistent();
711}
712
713void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
714 if (IsWeakAccessEnabled(self)) {
715 return;
716 }
717 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000718 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000719 while (!IsWeakAccessEnabled(self)) {
720 inline_cache_cond_.Wait(self);
721 }
722}
723
724void JitCodeCache::BroadcastForInlineCacheAccess() {
725 Thread* self = Thread::Current();
726 MutexLock mu(self, lock_);
727 inline_cache_cond_.Broadcast(self);
728}
729
730void JitCodeCache::AllowInlineCacheAccess() {
731 DCHECK(!kUseReadBarrier);
732 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
733 BroadcastForInlineCacheAccess();
734}
735
736void JitCodeCache::DisallowInlineCacheAccess() {
737 DCHECK(!kUseReadBarrier);
738 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
739}
740
741void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
742 Handle<mirror::ObjectArray<mirror::Class>> array) {
743 WaitUntilInlineCacheAccessible(Thread::Current());
744 // Note that we don't need to lock `lock_` here, the compiler calling
745 // this method has already ensured the inline cache will not be deleted.
746 for (size_t in_cache = 0, in_array = 0;
747 in_cache < InlineCache::kIndividualCacheSize;
748 ++in_cache) {
749 mirror::Class* object = ic.classes_[in_cache].Read();
750 if (object != nullptr) {
751 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000752 }
753 }
754}
755
Mathieu Chartierf044c222017-05-31 15:27:54 -0700756static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
757 if (was_warm) {
758 method->AddAccessFlags(kAccPreviouslyWarm);
759 }
760 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
761 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100762 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
763 // the warmup threshold is 1.
764 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
765 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700766}
767
Orion Hodson56fe32e2017-07-21 11:42:10 +0100768static void FlushInstructionPiplines(uint8_t* sync_page) {
769 // After updating the JIT code cache we need to force all CPUs to
770 // flush their instruction pipelines. In the absence of system call
771 // to do this explicitly, we can achieve this indirectly by toggling
Nicolas Geoffray8bb17862017-08-03 17:42:37 +0000772 // permissions on an executable page. This should send an IPI to
Orion Hodson56fe32e2017-07-21 11:42:10 +0100773 // each core to update the TLB entry with the interrupt raised on
774 // each core causing the instruction pipeline to be flushed.
Nicolas Geoffray8bb17862017-08-03 17:42:37 +0000775 CHECKED_MPROTECT(sync_page, kPageSize, kProtAll);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100776 // Ensure the sync_page is present otherwise a TLB update may not be
777 // necessary.
778 sync_page[0] = 0;
Nicolas Geoffray8bb17862017-08-03 17:42:37 +0000779 CHECKED_MPROTECT(sync_page, kPageSize, kProtCode);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100780}
781
Orion Hodson3ecac072017-07-20 15:28:44 +0100782#ifdef __aarch64__
783
784static void FlushJitCodeCacheRange(uint8_t* code_ptr,
Orion Hodson17272ab2017-07-21 14:32:52 +0100785 uint8_t* writable_ptr,
Orion Hodson3ecac072017-07-20 15:28:44 +0100786 size_t code_size) {
787 // Cache maintenance instructions can cause permission faults when a
788 // page is not present (e.g. swapped out or not backed). These
789 // faults should be handled by the kernel, but a bug in some Linux
790 // kernels may surface these permission faults to user-land which
791 // does not currently deal with them (b/63885946). To work around
792 // this, we read a value from each page to fault it in before
793 // attempting to perform cache maintenance operations.
794 //
795 // For reference, this behavior is caused by this commit:
796 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
797
798 // The cache-line size could be probed for from the CPU, but
799 // assuming a safe lower bound is safe for CPUs that have different
800 // cache-line sizes for big and little cores.
801 static const uintptr_t kSafeCacheLineSize = 32;
802
Orion Hodson17272ab2017-07-21 14:32:52 +0100803 // Ensure stores are present in L1 data cache.
804 __asm __volatile("dsb ish" ::: "memory");
Orion Hodson3ecac072017-07-20 15:28:44 +0100805
Orion Hodson3ecac072017-07-20 15:28:44 +0100806 volatile uint8_t mutant;
Orion Hodson17272ab2017-07-21 14:32:52 +0100807
808 // Push dirty cache-lines out to the point of unification (PoU). The
809 // point of unification is the first point in the cache/memory
810 // hierarchy where the instruction cache and data cache have the
811 // same view of memory. The PoU is where an instruction fetch will
812 // fetch the new code generated by the JIT.
813 //
814 // See: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.den0024a/ch11s04.html
815 uintptr_t writable_addr = RoundDown(reinterpret_cast<uintptr_t>(writable_ptr),
816 kSafeCacheLineSize);
817 uintptr_t writable_end = RoundUp(reinterpret_cast<uintptr_t>(writable_ptr) + code_size,
818 kSafeCacheLineSize);
819 while (writable_addr < writable_end) {
Orion Hodson3ecac072017-07-20 15:28:44 +0100820 // Read from the cache-line to minimize the chance that a cache
821 // maintenance instruction causes a fault (see kernel bug comment
822 // above).
Orion Hodson17272ab2017-07-21 14:32:52 +0100823 mutant = *reinterpret_cast<const uint8_t*>(writable_addr);
824
825 // Flush cache-line
826 __asm volatile("dc cvau, %0" :: "r"(writable_addr) : "memory");
827 writable_addr += kSafeCacheLineSize;
828 }
829
830 __asm __volatile("dsb ish" ::: "memory");
831
832 uintptr_t code_addr = RoundDown(reinterpret_cast<uintptr_t>(code_ptr), kSafeCacheLineSize);
833 const uintptr_t code_end = RoundUp(reinterpret_cast<uintptr_t>(code_ptr) + code_size,
834 kSafeCacheLineSize);
835 while (code_addr < code_end) {
836 // Read from the cache-line to minimize the chance that a cache
837 // maintenance instruction causes a fault (see kernel bug comment
838 // above).
839 mutant = *reinterpret_cast<const uint8_t*>(code_addr);
Orion Hodson3ecac072017-07-20 15:28:44 +0100840
841 // Invalidating the data cache line is only strictly necessary
842 // when the JIT code cache has two mappings (the default). We know
843 // this cache line is clean so this is just invalidating it (using
Orion Hodson17272ab2017-07-21 14:32:52 +0100844 // "dc ivac" would be preferable, but counts as a write and this
845 // memory may not be mapped write permission).
846 __asm volatile("dc cvau, %0" :: "r"(code_addr) : "memory");
Orion Hodson3ecac072017-07-20 15:28:44 +0100847
848 // Invalidate the instruction cache line to force instructions in
849 // range to be re-fetched following update.
Orion Hodson17272ab2017-07-21 14:32:52 +0100850 __asm volatile("ic ivau, %0" :: "r"(code_addr) : "memory");
Orion Hodson3ecac072017-07-20 15:28:44 +0100851
Orion Hodson17272ab2017-07-21 14:32:52 +0100852 code_addr += kSafeCacheLineSize;
Orion Hodson3ecac072017-07-20 15:28:44 +0100853 }
854
Orion Hodson17272ab2017-07-21 14:32:52 +0100855 // Wait for code cache invalidations to complete.
856 __asm __volatile("dsb ish" ::: "memory");
857
858 // Reset fetched instruction stream.
859 __asm __volatile("isb");
Orion Hodson3ecac072017-07-20 15:28:44 +0100860}
861
862#else // __aarch64
863
864static void FlushJitCodeCacheRange(uint8_t* code_ptr,
865 uint8_t* writable_ptr,
866 size_t code_size) {
867 if (writable_ptr != code_ptr) {
868 // When there are two mappings of the JIT code cache, RX and
869 // RW, flush the RW version first as we've just dirtied the
870 // cache lines with new code. Flushing the RX version first
871 // can cause a permission fault as the those addresses are not
872 // writable, but can appear dirty in the cache. There is a lot
873 // of potential subtlety here depending on how the cache is
874 // indexed and tagged.
875 //
876 // Flushing the RX version after the RW version is just
877 // invalidating cachelines in the instruction cache. This is
878 // necessary as the instruction cache will often have a
879 // different set of cache lines present and because the JIT
880 // code cache can start a new function at any boundary within
881 // a cache-line.
882 FlushDataCache(reinterpret_cast<char*>(writable_ptr),
883 reinterpret_cast<char*>(writable_ptr + code_size));
884 }
885 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
886 reinterpret_cast<char*>(code_ptr + code_size));
887}
888
889#endif // __aarch64
890
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100891uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
892 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000893 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700894 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000895 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100896 size_t frame_size_in_bytes,
897 size_t core_spill_mask,
898 size_t fp_spill_mask,
899 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000900 size_t code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000901 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700902 Handle<mirror::ObjectArray<mirror::Object>> roots,
903 bool has_should_deoptimize_flag,
904 const ArenaSet<ArtMethod*>&
905 cha_single_implementation_list) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000906 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100907 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
908 // Ensure the header ends up at expected instruction alignment.
909 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
910 size_t total_size = header_size + code_size;
911
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100912 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100913 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000914 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100915 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000916 ScopedThreadSuspension sts(self, kSuspended);
917 MutexLock mu(self, lock_);
918 WaitForPotentialCollectionToComplete(self);
919 {
David Sehrd1dbb742017-07-17 11:20:38 -0700920 ScopedCodeCacheWrite scc(this);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000921 memory = AllocateCode(total_size);
922 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000923 return nullptr;
924 }
David Sehrd1dbb742017-07-17 11:20:38 -0700925 uint8_t* writable_ptr = memory + header_size;
926 code_ptr = ToExecutableAddress(writable_ptr);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000927
David Sehrd1dbb742017-07-17 11:20:38 -0700928 std::copy(code, code + code_size, writable_ptr);
929 OatQuickMethodHeader* writable_method_header =
930 OatQuickMethodHeader::FromCodePointer(writable_ptr);
931 // We need to be able to write the OatQuickMethodHeader, so we use writable_method_header.
932 // Otherwise, the offsets encoded in OatQuickMethodHeader are used relative to an executable
933 // address, so we use code_ptr.
934 new (writable_method_header) OatQuickMethodHeader(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000935 code_ptr - stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700936 code_ptr - method_info,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000937 frame_size_in_bytes,
938 core_spill_mask,
939 fp_spill_mask,
940 code_size);
Orion Hodson3ecac072017-07-20 15:28:44 +0100941
942 FlushJitCodeCacheRange(code_ptr, writable_ptr, code_size);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100943 FlushInstructionPiplines(code_sync_map_->Begin());
Orion Hodson43ce5f82017-07-19 10:34:27 +0100944
Mingyao Yang063fc772016-08-02 11:02:54 -0700945 DCHECK(!Runtime::Current()->IsAotCompiler());
946 if (has_should_deoptimize_flag) {
David Sehrd1dbb742017-07-17 11:20:38 -0700947 writable_method_header->SetHasShouldDeoptimizeFlag();
Mingyao Yang063fc772016-08-02 11:02:54 -0700948 }
David Sehrd1dbb742017-07-17 11:20:38 -0700949 // All the pointers exported from the cache are executable addresses.
950 method_header = ToExecutableAddress(writable_method_header);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100951 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100952
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000953 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100954 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000955 // We need to update the entry point in the runnable state for the instrumentation.
956 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700957 // Need cha_lock_ for checking all single-implementation flags and register
958 // dependencies.
959 MutexLock cha_mu(self, *Locks::cha_lock_);
960 bool single_impl_still_valid = true;
961 for (ArtMethod* single_impl : cha_single_implementation_list) {
962 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700963 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
964 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700965 single_impl_still_valid = false;
Mathieu Chartierf044c222017-05-31 15:27:54 -0700966 ClearMethodCounter(method, /*was_warm*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700967 break;
968 }
969 }
970
971 // Discard the code if any single-implementation assumptions are now invalid.
972 if (!single_impl_still_valid) {
973 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
974 return nullptr;
975 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000976 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800977 << "Should not be using cha on debuggable apps/runs!";
978
Mingyao Yang063fc772016-08-02 11:02:54 -0700979 for (ArtMethod* single_impl : cha_single_implementation_list) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700980 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()->AddDependency(
Mingyao Yang063fc772016-08-02 11:02:54 -0700981 single_impl, method, method_header);
982 }
983
984 // The following needs to be guarded by cha_lock_ also. Otherwise it's
985 // possible that the compiled code is considered invalidated by some class linking,
986 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000987 MutexLock mu(self, lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000988 // Fill the root table before updating the entry point.
David Sehrd1dbb742017-07-17 11:20:38 -0700989 CHECK(IsDataAddress(roots_data));
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000990 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100991 DCHECK_LE(roots_data, stack_map);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000992 FillRootTable(roots_data, roots);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100993
994 // Ensure the updates to the root table are visible with a store fence.
995 QuasiAtomic::ThreadFenceSequentiallyConsistent();
996
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100997 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000998 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000999 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001000 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001001 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001002 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1003 method, method_header->GetEntryPoint());
1004 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001005 if (collection_in_progress_) {
1006 // We need to update the live bitmap if there is a GC to ensure it sees this new
1007 // code.
1008 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1009 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001010 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001011 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001012 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -07001013 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001014 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1015 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
1016 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -07001017 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
1018 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001019 histogram_code_memory_use_.AddValue(code_size);
1020 if (code_size > kCodeSizeLogThreshold) {
1021 LOG(INFO) << "JIT allocated "
1022 << PrettySize(code_size)
1023 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -07001024 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001025 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001026 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001027
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001028 return reinterpret_cast<uint8_t*>(method_header);
1029}
1030
1031size_t JitCodeCache::CodeCacheSize() {
1032 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001033 return CodeCacheSizeLocked();
1034}
1035
Orion Hodsoneced6922017-06-01 10:54:28 +01001036bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
1037 MutexLock mu(Thread::Current(), lock_);
1038 if (method->IsNative()) {
1039 return false;
1040 }
1041
1042 bool in_cache = false;
1043 {
David Sehrd1dbb742017-07-17 11:20:38 -07001044 ScopedCodeCacheWrite ccw(this);
Orion Hodsoneced6922017-06-01 10:54:28 +01001045 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
1046 if (code_iter->second == method) {
1047 if (release_memory) {
David Sehrd1dbb742017-07-17 11:20:38 -07001048 FreeCodeAndData(code_iter->first);
Orion Hodsoneced6922017-06-01 10:54:28 +01001049 }
1050 code_iter = method_code_map_.erase(code_iter);
1051 in_cache = true;
1052 continue;
1053 }
1054 ++code_iter;
1055 }
1056 }
1057
1058 bool osr = false;
1059 auto code_map = osr_code_map_.find(method);
1060 if (code_map != osr_code_map_.end()) {
1061 osr_code_map_.erase(code_map);
1062 osr = true;
1063 }
1064
1065 if (!in_cache) {
1066 return false;
1067 }
1068
1069 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1070 if (info != nullptr) {
1071 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
1072 DCHECK(profile != profiling_infos_.end());
1073 profiling_infos_.erase(profile);
1074 }
1075 method->SetProfilingInfo(nullptr);
1076 method->ClearCounter();
1077 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1078 method, GetQuickToInterpreterBridge());
1079 VLOG(jit)
1080 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
1081 << ArtMethod::PrettyMethod(method) << "@" << method
1082 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1083 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
1084 return true;
1085}
1086
Alex Lightdba61482016-12-21 08:20:29 -08001087// This notifies the code cache that the given method has been redefined and that it should remove
1088// any cached information it has on the method. All threads must be suspended before calling this
1089// method. The compiled code for the method (if there is any) must not be in any threads call stack.
1090void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
1091 MutexLock mu(Thread::Current(), lock_);
1092 if (method->IsNative()) {
1093 return;
1094 }
1095 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1096 if (info != nullptr) {
1097 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
1098 DCHECK(profile != profiling_infos_.end());
1099 profiling_infos_.erase(profile);
1100 }
1101 method->SetProfilingInfo(nullptr);
David Sehrd1dbb742017-07-17 11:20:38 -07001102 ScopedCodeCacheWrite ccw(this);
Andreas Gampe39e67382017-05-15 19:26:38 -07001103 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
Alex Lightdba61482016-12-21 08:20:29 -08001104 if (code_iter->second == method) {
David Sehrd1dbb742017-07-17 11:20:38 -07001105 FreeCodeAndData(code_iter->first);
Andreas Gampe39e67382017-05-15 19:26:38 -07001106 code_iter = method_code_map_.erase(code_iter);
1107 continue;
Alex Lightdba61482016-12-21 08:20:29 -08001108 }
Andreas Gampe39e67382017-05-15 19:26:38 -07001109 ++code_iter;
Alex Lightdba61482016-12-21 08:20:29 -08001110 }
1111 auto code_map = osr_code_map_.find(method);
1112 if (code_map != osr_code_map_.end()) {
1113 osr_code_map_.erase(code_map);
1114 }
1115}
1116
1117// This invalidates old_method. Once this function returns one can no longer use old_method to
1118// execute code unless it is fixed up. This fixup will happen later in the process of installing a
1119// class redefinition.
1120// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
1121// shouldn't be used since it is no longer logically in the jit code cache.
1122// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
1123void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Alex Lighteee0bd42017-02-14 15:31:45 +00001124 // Native methods have no profiling info and need no special handling from the JIT code cache.
1125 if (old_method->IsNative()) {
1126 return;
1127 }
Alex Lightdba61482016-12-21 08:20:29 -08001128 MutexLock mu(Thread::Current(), lock_);
1129 // Update ProfilingInfo to the new one and remove it from the old_method.
1130 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
1131 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
1132 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
1133 old_method->SetProfilingInfo(nullptr);
1134 // Since the JIT should be paused and all threads suspended by the time this is called these
1135 // checks should always pass.
1136 DCHECK(!info->IsInUseByCompiler());
1137 new_method->SetProfilingInfo(info);
1138 info->method_ = new_method;
1139 }
1140 // Update method_code_map_ to point to the new method.
1141 for (auto& it : method_code_map_) {
1142 if (it.second == old_method) {
1143 it.second = new_method;
1144 }
1145 }
1146 // Update osr_code_map_ to point to the new method.
1147 auto code_map = osr_code_map_.find(old_method);
1148 if (code_map != osr_code_map_.end()) {
1149 osr_code_map_.Put(new_method, code_map->second);
1150 osr_code_map_.erase(old_method);
1151 }
1152}
1153
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001154size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001155 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001156}
1157
1158size_t JitCodeCache::DataCacheSize() {
1159 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001160 return DataCacheSizeLocked();
1161}
1162
1163size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001164 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001165}
1166
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001167void JitCodeCache::ClearData(Thread* self,
1168 uint8_t* stack_map_data,
1169 uint8_t* roots_data) {
1170 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
David Sehrd1dbb742017-07-17 11:20:38 -07001171 CHECK(IsDataAddress(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001172 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001173 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001174}
1175
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001176size_t JitCodeCache::ReserveData(Thread* self,
1177 size_t stack_map_size,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001178 size_t method_info_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001179 size_t number_of_roots,
1180 ArtMethod* method,
1181 uint8_t** stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001182 uint8_t** method_info_data,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001183 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001184 size_t table_size = ComputeRootTableSize(number_of_roots);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001185 size_t size = RoundUp(stack_map_size + method_info_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001186 uint8_t* result = nullptr;
1187
1188 {
1189 ScopedThreadSuspension sts(self, kSuspended);
1190 MutexLock mu(self, lock_);
1191 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001192 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001193 }
1194
1195 if (result == nullptr) {
1196 // Retry.
1197 GarbageCollectCache(self);
1198 ScopedThreadSuspension sts(self, kSuspended);
1199 MutexLock mu(self, lock_);
1200 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001201 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001202 }
1203
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001204 MutexLock mu(self, lock_);
1205 histogram_stack_map_memory_use_.AddValue(size);
1206 if (size > kStackMapSizeLogThreshold) {
1207 LOG(INFO) << "JIT allocated "
1208 << PrettySize(size)
1209 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001210 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001211 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001212 if (result != nullptr) {
1213 *roots_data = result;
1214 *stack_map_data = result + table_size;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001215 *method_info_data = *stack_map_data + stack_map_size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001216 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001217 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001218 } else {
1219 *roots_data = nullptr;
1220 *stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001221 *method_info_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001222 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001223 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001224}
1225
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001226class MarkCodeVisitor FINAL : public StackVisitor {
1227 public:
1228 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
1229 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
1230 code_cache_(code_cache_in),
1231 bitmap_(code_cache_->GetLiveBitmap()) {}
1232
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001233 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001234 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
1235 if (method_header == nullptr) {
1236 return true;
1237 }
1238 const void* code = method_header->GetCode();
1239 if (code_cache_->ContainsPc(code)) {
1240 // Use the atomic set version, as multiple threads are executing this code.
1241 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1242 }
1243 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001244 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001245
1246 private:
1247 JitCodeCache* const code_cache_;
1248 CodeCacheBitmap* const bitmap_;
1249};
1250
1251class MarkCodeClosure FINAL : public Closure {
1252 public:
1253 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
1254 : code_cache_(code_cache), barrier_(barrier) {}
1255
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001256 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001257 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001258 DCHECK(thread == Thread::Current() || thread->IsSuspended());
1259 MarkCodeVisitor visitor(thread, code_cache_);
1260 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001261 if (kIsDebugBuild) {
1262 // The stack walking code queries the side instrumentation stack if it
1263 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1264 // must have been seen. We sanity check this below.
1265 for (const instrumentation::InstrumentationStackFrame& frame
1266 : *thread->GetInstrumentationStack()) {
1267 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1268 // its stack frame, it is not the method owning return_pc_. We just pass null to
1269 // LookupMethodHeader: the method is only checked against in debug builds.
1270 OatQuickMethodHeader* method_header =
1271 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
1272 if (method_header != nullptr) {
1273 const void* code = method_header->GetCode();
1274 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
1275 }
1276 }
1277 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001278 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001279 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001280
1281 private:
1282 JitCodeCache* const code_cache_;
1283 Barrier* const barrier_;
1284};
1285
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001286void JitCodeCache::NotifyCollectionDone(Thread* self) {
1287 collection_in_progress_ = false;
1288 lock_cond_.Broadcast(self);
1289}
1290
1291void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
1292 size_t per_space_footprint = new_footprint / 2;
David Sehrd1dbb742017-07-17 11:20:38 -07001293 CHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001294 DCHECK_EQ(per_space_footprint * 2, new_footprint);
1295 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
1296 {
David Sehrd1dbb742017-07-17 11:20:38 -07001297 ScopedCodeCacheWrite scc(this);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001298 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
1299 }
1300}
1301
1302bool JitCodeCache::IncreaseCodeCacheCapacity() {
1303 if (current_capacity_ == max_capacity_) {
1304 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001305 }
1306
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001307 // Double the capacity if we're below 1MB, or increase it by 1MB if
1308 // we're above.
1309 if (current_capacity_ < 1 * MB) {
1310 current_capacity_ *= 2;
1311 } else {
1312 current_capacity_ += 1 * MB;
1313 }
1314 if (current_capacity_ > max_capacity_) {
1315 current_capacity_ = max_capacity_;
1316 }
1317
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001318 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001319
1320 SetFootprintLimit(current_capacity_);
1321
1322 return true;
1323}
1324
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001325void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1326 Barrier barrier(0);
1327 size_t threads_running_checkpoint = 0;
1328 MarkCodeClosure closure(this, &barrier);
1329 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1330 // Now that we have run our checkpoint, move to a suspended state and wait
1331 // for other threads to run the checkpoint.
1332 ScopedThreadSuspension sts(self, kSuspended);
1333 if (threads_running_checkpoint != 0) {
1334 barrier.Increment(self, threads_running_checkpoint);
1335 }
1336}
1337
Nicolas Geoffray35122442016-03-02 12:05:30 +00001338bool JitCodeCache::ShouldDoFullCollection() {
1339 if (current_capacity_ == max_capacity_) {
1340 // Always do a full collection when the code cache is full.
1341 return true;
1342 } else if (current_capacity_ < kReservedCapacity) {
1343 // Always do partial collection when the code cache size is below the reserved
1344 // capacity.
1345 return false;
1346 } else if (last_collection_increased_code_cache_) {
1347 // This time do a full collection.
1348 return true;
1349 } else {
1350 // This time do a partial collection.
1351 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001352 }
1353}
1354
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001355void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001356 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001357 if (!garbage_collect_code_) {
1358 MutexLock mu(self, lock_);
1359 IncreaseCodeCacheCapacity();
1360 return;
1361 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001362
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001363 // Wait for an existing collection, or let everyone know we are starting one.
1364 {
1365 ScopedThreadSuspension sts(self, kSuspended);
1366 MutexLock mu(self, lock_);
1367 if (WaitForPotentialCollectionToComplete(self)) {
1368 return;
1369 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001370 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001371 live_bitmap_.reset(CodeCacheBitmap::Create(
1372 "code-cache-bitmap",
David Sehrd1dbb742017-07-17 11:20:38 -07001373 reinterpret_cast<uintptr_t>(executable_code_map_->Begin()),
1374 reinterpret_cast<uintptr_t>(executable_code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001375 collection_in_progress_ = true;
1376 }
1377 }
1378
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001379 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001380 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001381 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001382
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001383 bool do_full_collection = false;
1384 {
1385 MutexLock mu(self, lock_);
1386 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001387 }
1388
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001389 VLOG(jit) << "Do "
1390 << (do_full_collection ? "full" : "partial")
1391 << " code cache collection, code="
1392 << PrettySize(CodeCacheSize())
1393 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001394
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001395 DoCollection(self, /* collect_profiling_info */ do_full_collection);
1396
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001397 VLOG(jit) << "After code cache collection, code="
1398 << PrettySize(CodeCacheSize())
1399 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001400
1401 {
1402 MutexLock mu(self, lock_);
1403
1404 // Increase the code cache only when we do partial collections.
1405 // TODO: base this strategy on how full the code cache is?
1406 if (do_full_collection) {
1407 last_collection_increased_code_cache_ = false;
1408 } else {
1409 last_collection_increased_code_cache_ = true;
1410 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001411 }
1412
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001413 bool next_collection_will_be_full = ShouldDoFullCollection();
1414
1415 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001416 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001417 // Save the entry point of methods we have compiled, and update the entry
1418 // point of those methods to the interpreter. If the method is invoked, the
1419 // interpreter will update its entry point to the compiled code and call it.
1420 for (ProfilingInfo* info : profiling_infos_) {
1421 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1422 if (ContainsPc(entry_point)) {
1423 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001424 // Don't call Instrumentation::UpdateMethods, as it can check the declaring
1425 // class of the method. We may be concurrently running a GC which makes accessing
1426 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1427 // checked that the current entry point is JIT compiled code.
1428 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001429 }
1430 }
1431
1432 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
1433 }
1434 live_bitmap_.reset(nullptr);
1435 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001436 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001437 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001438 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001439}
1440
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001441void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001442 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001443 std::unordered_set<OatQuickMethodHeader*> method_headers;
1444 {
1445 MutexLock mu(self, lock_);
David Sehrd1dbb742017-07-17 11:20:38 -07001446 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -07001447 // Iterate over all compiled code and remove entries that are not marked.
1448 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1449 const void* code_ptr = it->first;
David Sehrd1dbb742017-07-17 11:20:38 -07001450 CHECK(IsExecutableAddress(code_ptr));
Mingyao Yang063fc772016-08-02 11:02:54 -07001451 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1452 if (GetLiveBitmap()->Test(allocation)) {
1453 ++it;
1454 } else {
David Sehrd1dbb742017-07-17 11:20:38 -07001455 CHECK(IsExecutableAddress(it->first));
Mingyao Yang063fc772016-08-02 11:02:54 -07001456 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
1457 it = method_code_map_.erase(it);
1458 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001459 }
1460 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001461 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001462}
1463
1464void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001465 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001466 {
1467 MutexLock mu(self, lock_);
1468 if (collect_profiling_info) {
1469 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1470 // Also remove the saved entry point from the ProfilingInfo objects.
1471 for (ProfilingInfo* info : profiling_infos_) {
1472 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001473 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001474 info->GetMethod()->SetProfilingInfo(nullptr);
1475 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001476
1477 if (info->GetSavedEntryPoint() != nullptr) {
1478 info->SetSavedEntryPoint(nullptr);
1479 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001480 // give it a chance to be hot again.
1481 ClearMethodCounter(info->GetMethod(), /*was_warm*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001482 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001483 }
1484 } else if (kIsDebugBuild) {
1485 // Sanity check that the profiling infos do not have a dangling entry point.
1486 for (ProfilingInfo* info : profiling_infos_) {
1487 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001488 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001489 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001490
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001491 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1492 // an entry point is either:
1493 // - an osr compiled code, that will be removed if not in a thread call stack.
1494 // - discarded compiled code, that will be removed if not in a thread call stack.
1495 for (const auto& it : method_code_map_) {
1496 ArtMethod* method = it.second;
1497 const void* code_ptr = it.first;
David Sehrd1dbb742017-07-17 11:20:38 -07001498 CHECK(IsExecutableAddress(code_ptr));
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001499 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1500 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1501 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1502 }
1503 }
1504
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001505 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001506 // on thread stacks).
1507 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001508 }
1509
1510 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001511 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001512
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001513 // At this point, mutator threads are still running, and entrypoints of methods can
1514 // change. We do know they cannot change to a code cache entry that is not marked,
1515 // therefore we can safely remove those entries.
1516 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001517
Nicolas Geoffray35122442016-03-02 12:05:30 +00001518 if (collect_profiling_info) {
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +01001519 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001520 MutexLock mu(self, lock_);
1521 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001522 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001523 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
David Sehrd1dbb742017-07-17 11:20:38 -07001524 CHECK(IsDataAddress(info));
Nicolas Geoffray35122442016-03-02 12:05:30 +00001525 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001526 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1527 // that the compiled code would not get revived. As mutator threads run concurrently,
1528 // they may have revived the compiled code, and now we are in the situation where
1529 // a method has compiled code but no ProfilingInfo.
1530 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1531 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001532 if (ContainsPc(ptr) &&
1533 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001534 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001535 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001536 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001537 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001538 return true;
1539 }
1540 return false;
1541 });
1542 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001543 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001544 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001545}
1546
Nicolas Geoffray35122442016-03-02 12:05:30 +00001547bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001548 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001549 // Check that methods we have compiled do have a ProfilingInfo object. We would
1550 // have memory leaks of compiled code otherwise.
1551 for (const auto& it : method_code_map_) {
1552 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001553 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001554 const void* code_ptr = it.first;
1555 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1556 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1557 // If the code is not dead, then we have a problem. Note that this can even
1558 // happen just after a collection, as mutator threads are running in parallel
1559 // and could deoptimize an existing compiled code.
1560 return false;
1561 }
1562 }
1563 }
1564 return true;
1565}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001566
1567OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
1568 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
1569 if (kRuntimeISA == kArm) {
1570 // On Thumb-2, the pc is offset by one.
1571 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001572 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001573 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1574 return nullptr;
1575 }
1576
1577 MutexLock mu(Thread::Current(), lock_);
1578 if (method_code_map_.empty()) {
1579 return nullptr;
1580 }
1581 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1582 --it;
1583
1584 const void* code_ptr = it->first;
David Sehrd1dbb742017-07-17 11:20:38 -07001585 CHECK(IsExecutableAddress(code_ptr));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001586 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1587 if (!method_header->Contains(pc)) {
1588 return nullptr;
1589 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001590 if (kIsDebugBuild && method != nullptr) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001591 // When we are walking the stack to redefine classes and creating obsolete methods it is
1592 // possible that we might have updated the method_code_map by making this method obsolete in a
1593 // previous frame. Therefore we should just check that the non-obsolete version of this method
1594 // is the one we expect. We change to the non-obsolete versions in the error message since the
1595 // obsolete version of the method might not be fully initialized yet. This situation can only
1596 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
Andreas Gampe06c42a52017-07-26 14:17:14 -07001597 // method and it->second should be identical. (See openjdkjvmti/ti_redefine.cc for more
Alex Light1ebe4fe2017-01-30 14:57:11 -08001598 // information.)
1599 DCHECK_EQ(it->second->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
1600 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
1601 << ArtMethod::PrettyMethod(it->second->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001602 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001603 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001604 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001605}
1606
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001607OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1608 MutexLock mu(Thread::Current(), lock_);
1609 auto it = osr_code_map_.find(method);
1610 if (it == osr_code_map_.end()) {
1611 return nullptr;
1612 }
1613 return OatQuickMethodHeader::FromCodePointer(it->second);
1614}
1615
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001616ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1617 ArtMethod* method,
1618 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001619 bool retry_allocation)
1620 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1621 NO_THREAD_SAFETY_ANALYSIS {
1622 ProfilingInfo* info = nullptr;
1623 if (!retry_allocation) {
1624 // If we are allocating for the interpreter, just try to lock, to avoid
1625 // lock contention with the JIT.
1626 if (lock_.ExclusiveTryLock(self)) {
1627 info = AddProfilingInfoInternal(self, method, entries);
1628 lock_.ExclusiveUnlock(self);
1629 }
1630 } else {
1631 {
1632 MutexLock mu(self, lock_);
1633 info = AddProfilingInfoInternal(self, method, entries);
1634 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001635
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001636 if (info == nullptr) {
1637 GarbageCollectCache(self);
1638 MutexLock mu(self, lock_);
1639 info = AddProfilingInfoInternal(self, method, entries);
1640 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001641 }
1642 return info;
1643}
1644
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001645ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001646 ArtMethod* method,
1647 const std::vector<uint32_t>& entries) {
1648 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001649 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001650 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001651
1652 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001653 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001654 if (info != nullptr) {
1655 return info;
1656 }
1657
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001658 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001659 if (data == nullptr) {
1660 return nullptr;
1661 }
1662 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001663
1664 // Make sure other threads see the data in the profiling info object before the
1665 // store in the ArtMethod's ProfilingInfo pointer.
1666 QuasiAtomic::ThreadFenceRelease();
1667
David Sehrd1dbb742017-07-17 11:20:38 -07001668 CHECK(IsDataAddress(info));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001669 method->SetProfilingInfo(info);
1670 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001671 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001672 return info;
1673}
1674
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001675// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1676// is already held.
1677void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1678 if (code_mspace_ == mspace) {
1679 size_t result = code_end_;
1680 code_end_ += increment;
David Sehrd1dbb742017-07-17 11:20:38 -07001681 MemMap* writable_map = GetWritableMemMap();
1682 return reinterpret_cast<void*>(result + writable_map->Begin());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001683 } else {
1684 DCHECK_EQ(data_mspace_, mspace);
1685 size_t result = data_end_;
1686 data_end_ += increment;
1687 return reinterpret_cast<void*>(result + data_map_->Begin());
1688 }
1689}
1690
Calin Juravle99629622016-04-19 16:33:46 +01001691void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001692 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001693 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001694 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001695 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001696 for (const ProfilingInfo* info : profiling_infos_) {
1697 ArtMethod* method = info->GetMethod();
1698 const DexFile* dex_file = method->GetDexFile();
Calin Juravle940eb0c2017-01-30 19:30:44 -08001699 if (!ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
1700 // Skip dex files which are not profiled.
1701 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001702 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001703 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001704
1705 // If the method didn't reach the compilation threshold don't save the inline caches.
1706 // They might be incomplete and cause unnecessary deoptimizations.
1707 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1708 if (method->GetCounter() < jit_compile_threshold) {
1709 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001710 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001711 continue;
1712 }
1713
Calin Juravle940eb0c2017-01-30 19:30:44 -08001714 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001715 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001716 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001717 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001718 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001719 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1720 mirror::Class* cls = cache.classes_[k].Read();
1721 if (cls == nullptr) {
1722 break;
1723 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001724
Calin Juravle13439f02017-02-21 01:17:21 -08001725 // Check if the receiver is in the boot class path or if it's in the
1726 // same class loader as the caller. If not, skip it, as there is not
1727 // much we can do during AOT.
1728 if (!cls->IsBootStrapClassLoaded() &&
1729 caller->GetClassLoader() != cls->GetClassLoader()) {
1730 is_missing_types = true;
1731 continue;
1732 }
1733
Calin Juravle4ca70a32017-02-21 16:22:24 -08001734 const DexFile* class_dex_file = nullptr;
1735 dex::TypeIndex type_index;
1736
1737 if (cls->GetDexCache() == nullptr) {
1738 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001739 // Make a best effort to find the type index in the method's dex file.
1740 // We could search all open dex files but that might turn expensive
1741 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001742 class_dex_file = dex_file;
1743 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1744 } else {
1745 class_dex_file = &(cls->GetDexFile());
1746 type_index = cls->GetDexTypeIndex();
1747 }
1748 if (!type_index.IsValid()) {
1749 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001750 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001751 continue;
1752 }
1753 if (ContainsElement(dex_base_locations, class_dex_file->GetBaseLocation())) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001754 // Only consider classes from the same apk (including multidex).
1755 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001756 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001757 } else {
1758 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001759 }
1760 }
1761 if (!profile_classes.empty()) {
1762 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001763 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001764 }
1765 }
1766 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001767 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001768 }
1769}
1770
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001771uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1772 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001773}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001774
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001775bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1776 MutexLock mu(Thread::Current(), lock_);
1777 return osr_code_map_.find(method) != osr_code_map_.end();
1778}
1779
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001780bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1781 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001782 return false;
1783 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001784
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001785 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001786 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1787 return false;
1788 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001789
Andreas Gampe542451c2016-07-26 09:02:02 -07001790 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001791 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001792 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Jeff Hao00286db2017-05-30 16:53:07 -07001793 // Because the counter is not atomic, there are some rare cases where we may not hit the
1794 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
Mathieu Chartierf044c222017-05-31 15:27:54 -07001795 ClearMethodCounter(method, /*was_warm*/ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001796 return false;
1797 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001798
buzbee454b3b62016-04-07 14:42:47 -07001799 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001800 return false;
1801 }
1802
buzbee454b3b62016-04-07 14:42:47 -07001803 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001804 return true;
1805}
1806
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001807ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001808 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001809 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001810 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001811 if (!info->IncrementInlineUse()) {
1812 // Overflow of inlining uses, just bail.
1813 return nullptr;
1814 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001815 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001816 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001817}
1818
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001819void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001820 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001821 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001822 DCHECK(info != nullptr);
1823 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001824}
1825
buzbee454b3b62016-04-07 14:42:47 -07001826void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001827 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001828 DCHECK(info->IsMethodBeingCompiled(osr));
1829 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001830}
1831
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001832size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1833 MutexLock mu(Thread::Current(), lock_);
David Sehrd1dbb742017-07-17 11:20:38 -07001834 CHECK(IsExecutableAddress(ptr));
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001835 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1836}
1837
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001838void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1839 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001840 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001841 if ((profiling_info != nullptr) &&
1842 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1843 // Prevent future uses of the compiled code.
1844 profiling_info->SetSavedEntryPoint(nullptr);
1845 }
1846
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001847 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001848 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001849 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001850 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1851 method, GetQuickToInterpreterBridge());
Mathieu Chartierf044c222017-05-31 15:27:54 -07001852 ClearMethodCounter(method, /*was_warm*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001853 } else {
1854 MutexLock mu(Thread::Current(), lock_);
1855 auto it = osr_code_map_.find(method);
1856 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1857 // Remove the OSR method, to avoid using it again.
1858 osr_code_map_.erase(it);
1859 }
1860 }
1861}
1862
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001863uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1864 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1865 uint8_t* result = reinterpret_cast<uint8_t*>(
1866 mspace_memalign(code_mspace_, alignment, code_size));
1867 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1868 // Ensure the header ends up at expected instruction alignment.
1869 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
David Sehrd1dbb742017-07-17 11:20:38 -07001870 CHECK(IsWritableAddress(result));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001871 used_memory_for_code_ += mspace_usable_size(result);
1872 return result;
1873}
1874
David Sehrd1dbb742017-07-17 11:20:38 -07001875void JitCodeCache::FreeRawCode(void* code) {
1876 CHECK(IsExecutableAddress(code));
1877 void* writable_code = ToWritableAddress(code);
1878 used_memory_for_code_ -= mspace_usable_size(writable_code);
1879 mspace_free(code_mspace_, writable_code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001880}
1881
1882uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1883 void* result = mspace_malloc(data_mspace_, data_size);
David Sehrd1dbb742017-07-17 11:20:38 -07001884 CHECK(IsDataAddress(reinterpret_cast<uint8_t*>(result)));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001885 used_memory_for_data_ += mspace_usable_size(result);
1886 return reinterpret_cast<uint8_t*>(result);
1887}
1888
1889void JitCodeCache::FreeData(uint8_t* data) {
David Sehrd1dbb742017-07-17 11:20:38 -07001890 CHECK(IsDataAddress(data));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001891 used_memory_for_data_ -= mspace_usable_size(data);
1892 mspace_free(data_mspace_, data);
1893}
1894
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001895void JitCodeCache::Dump(std::ostream& os) {
1896 MutexLock mu(Thread::Current(), lock_);
1897 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1898 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1899 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1900 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1901 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1902 << "Total number of JIT compilations for on stack replacement: "
1903 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001904 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001905 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1906 histogram_code_memory_use_.PrintMemoryUse(os);
1907 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001908}
1909
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001910} // namespace jit
1911} // namespace art