blob: 5d6fa2fb74b9fc4846f8ec7970b29b47261a8860 [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
93
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000094JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
95 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000096 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000097 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080098 ScopedTrace trace(__PRETTY_FUNCTION__);
David Sehrd1dbb742017-07-17 11:20:38 -070099 CHECK_GT(max_capacity, initial_capacity);
100 CHECK_GE(max_capacity - kMaxMapSpacingPages * kPageSize, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000101
David Sehrd1dbb742017-07-17 11:20:38 -0700102 // Generating debug information is for using the Linux perf tool on
103 // host which does not work with ashmem.
Nicolas Geoffray520dadf2017-07-19 15:33:11 +0100104 // Also, target linux does not support ashmem.
105 bool use_ashmem = !generate_debug_info && !kIsTargetLinux;
David Sehrd1dbb742017-07-17 11:20:38 -0700106
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000107 // With 'perf', we want a 1-1 mapping between an address and a method.
108 bool garbage_collect_code = !generate_debug_info;
109
David Sehrd1dbb742017-07-17 11:20:38 -0700110 // We only use two mappings (separating rw from rx) if we are able to use ashmem.
111 // See the above comment for debug information and not using ashmem.
Nicolas Geoffray520dadf2017-07-19 15:33:11 +0100112 bool use_two_mappings = use_ashmem;
David Sehrd1dbb742017-07-17 11:20:38 -0700113
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000114 // We need to have 32 bit offsets from method headers in code cache which point to things
115 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
116 // Ensure we're below 1 GB to be safe.
117 if (max_capacity > 1 * GB) {
118 std::ostringstream oss;
119 oss << "Maxium code cache capacity is limited to 1 GB, "
120 << PrettySize(max_capacity) << " is too big";
121 *error_msg = oss.str();
122 return nullptr;
123 }
124
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800125 std::string error_str;
126 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000127 // Map in low 4gb to simplify accessing root tables for x86_64.
128 // We could do PC-relative addressing to avoid this problem, but that
129 // would require reserving code and data area before submitting, which
130 // means more windows for the code memory to be RWX.
Andreas Gampee4deaf32017-06-09 15:27:15 -0700131 std::unique_ptr<MemMap> data_map(MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000132 "data-code-cache", nullptr,
133 max_capacity,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700134 kProtData,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000135 /* low_4gb */ true,
136 /* reuse */ false,
137 &error_str,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700138 use_ashmem));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100139 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800140 std::ostringstream oss;
Andreas Gampee4deaf32017-06-09 15:27:15 -0700141 oss << "Failed to create read write cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800142 *error_msg = oss.str();
143 return nullptr;
144 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100145
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000146 // Align both capacities to page size, as that's the unit mspaces use.
147 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
148 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
149
David Sehrd1dbb742017-07-17 11:20:38 -0700150 // Create a region for JIT data and executable code. This will be
151 // laid out as:
152 //
153 // +----------------+ --------------------
154 // : : ^ ^
155 // : post_code_map : | post_code_size |
156 // : [padding] : v |
157 // +----------------+ - |
158 // | | ^ |
159 // | code_map | | code_size |
160 // | [JIT Code] | v |
161 // +----------------+ - | total_mapping_size
162 // : : ^ |
163 // : pre_code_map : | pre_code_size |
164 // : [padding] : v |
165 // +----------------+ - |
166 // | | ^ |
167 // | data_map | | data_size |
168 // | [Jit Data] | v v
169 // +----------------+ --------------------
170 //
171 // The padding regions - pre_code_map and post_code_map - exist to
172 // put some random distance between the writable JIT code mapping
173 // and the executable mapping. The padding is discarded at the end
174 // of this function.
175 size_t total_mapping_size = kMaxMapSpacingPages * kPageSize;
176 size_t data_size = RoundUp((max_capacity - total_mapping_size) / 2, kPageSize);
177 size_t pre_code_size =
178 GetRandomNumber(kMinMapSpacingPages, kMaxMapSpacingPages) * kPageSize;
179 size_t code_size = max_capacity - total_mapping_size - data_size;
180 size_t post_code_size = total_mapping_size - pre_code_size;
181 DCHECK_EQ(code_size + data_size + total_mapping_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100182
David Sehrd1dbb742017-07-17 11:20:38 -0700183 // Create pre-code padding region after data region, discarded after
184 // code and data regions are set-up.
185 std::unique_ptr<MemMap> pre_code_map(SplitMemMap(data_map.get(),
186 "jit-code-cache-padding",
187 data_size,
188 kProtNone,
189 error_msg,
190 use_ashmem));
191 if (pre_code_map == nullptr) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100192 return nullptr;
193 }
David Sehrd1dbb742017-07-17 11:20:38 -0700194 DCHECK_EQ(data_map->Size(), data_size);
195 DCHECK_EQ(pre_code_map->Size(), pre_code_size + code_size + post_code_size);
196
197 // Create code region.
198 unique_fd writable_code_fd;
199 std::unique_ptr<MemMap> code_map(SplitMemMap(pre_code_map.get(),
200 "jit-code-cache",
201 pre_code_size,
202 use_two_mappings ? kProtCode : kProtAll,
203 error_msg,
204 use_ashmem,
205 &writable_code_fd));
206 if (code_map == nullptr) {
207 return nullptr;
208 }
209 DCHECK_EQ(pre_code_map->Size(), pre_code_size);
210 DCHECK_EQ(code_map->Size(), code_size + post_code_size);
211
212 // Padding after code region, discarded after code and data regions
213 // are set-up.
214 std::unique_ptr<MemMap> post_code_map(SplitMemMap(code_map.get(),
215 "jit-code-cache-padding",
216 code_size,
217 kProtNone,
218 error_msg,
219 use_ashmem));
220 if (post_code_map == nullptr) {
221 return nullptr;
222 }
223 DCHECK_EQ(code_map->Size(), code_size);
224 DCHECK_EQ(post_code_map->Size(), post_code_size);
225
226 std::unique_ptr<MemMap> writable_code_map;
227 if (use_two_mappings) {
228 // Allocate the R/W view.
229 writable_code_map.reset(MemMap::MapFile(code_size,
230 kProtData,
231 MAP_SHARED,
232 writable_code_fd.get(),
233 /* start */ 0,
234 /* low_4gb */ true,
235 "jit-writable-code",
236 &error_str));
237 if (writable_code_map == nullptr) {
238 std::ostringstream oss;
239 oss << "Failed to create writable code cache: " << error_str << " size=" << code_size;
240 *error_msg = oss.str();
241 return nullptr;
242 }
243 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000244 data_size = initial_capacity / 2;
245 code_size = initial_capacity - data_size;
246 DCHECK_EQ(code_size + data_size, initial_capacity);
David Sehrd1dbb742017-07-17 11:20:38 -0700247 return new JitCodeCache(writable_code_map.release(),
248 code_map.release(),
249 data_map.release(),
250 code_size,
251 data_size,
252 max_capacity,
253 garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800254}
255
David Sehrd1dbb742017-07-17 11:20:38 -0700256JitCodeCache::JitCodeCache(MemMap* writable_code_map,
257 MemMap* executable_code_map,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000258 MemMap* data_map,
259 size_t initial_code_capacity,
260 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000261 size_t max_capacity,
262 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100263 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000264 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100265 collection_in_progress_(false),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000266 data_map_(data_map),
David Sehrd1dbb742017-07-17 11:20:38 -0700267 executable_code_map_(executable_code_map),
268 writable_code_map_(writable_code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000269 max_capacity_(max_capacity),
270 current_capacity_(initial_code_capacity + initial_data_capacity),
271 code_end_(initial_code_capacity),
272 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000273 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000274 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000275 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000276 used_memory_for_data_(0),
277 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000278 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000279 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000280 number_of_collections_(0),
281 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
282 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000283 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
284 is_weak_access_enabled_(true),
285 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100286
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000287 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
David Sehrd1dbb742017-07-17 11:20:38 -0700288 MemMap* writable_map = GetWritableMemMap();
289 code_mspace_ = create_mspace_with_base(writable_map->Begin(), code_end_, false /*locked*/);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000290 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100291
292 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
293 PLOG(FATAL) << "create_mspace_with_base failed";
294 }
295
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000296 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100297
David Sehrd1dbb742017-07-17 11:20:38 -0700298 if (writable_code_map_ != nullptr) {
299 CHECKED_MPROTECT(writable_code_map_->Begin(), writable_code_map_->Size(), kProtReadOnly);
300 }
301 CHECKED_MPROTECT(executable_code_map_->Begin(), executable_code_map_->Size(), kProtCode);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100302 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100303
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000304 VLOG(jit) << "Created jit code cache: initial data size="
305 << PrettySize(initial_data_capacity)
306 << ", initial code size="
307 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800308}
309
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100310bool JitCodeCache::ContainsPc(const void* ptr) const {
David Sehrd1dbb742017-07-17 11:20:38 -0700311 return executable_code_map_->Begin() <= ptr && ptr < executable_code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800312}
313
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000314bool JitCodeCache::ContainsMethod(ArtMethod* method) {
315 MutexLock mu(Thread::Current(), lock_);
316 for (auto& it : method_code_map_) {
317 if (it.second == method) {
318 return true;
319 }
320 }
321 return false;
322}
323
David Sehrd1dbb742017-07-17 11:20:38 -0700324/* This method is only for CHECK/DCHECK that pointers are within to a region. */
325static bool IsAddressInMap(const void* addr,
326 const MemMap* mem_map,
327 const char* check_name) {
328 if (addr == nullptr || mem_map->HasAddress(addr)) {
329 return true;
330 }
331 LOG(ERROR) << "Is" << check_name << "Address " << addr
332 << " not in [" << reinterpret_cast<void*>(mem_map->Begin())
333 << ", " << reinterpret_cast<void*>(mem_map->Begin() + mem_map->Size()) << ")";
334 return false;
335}
336
337bool JitCodeCache::IsDataAddress(const void* raw_addr) const {
338 return IsAddressInMap(raw_addr, data_map_.get(), "Data");
339}
340
341bool JitCodeCache::IsExecutableAddress(const void* raw_addr) const {
342 return IsAddressInMap(raw_addr, executable_code_map_.get(), "Executable");
343}
344
345bool JitCodeCache::IsWritableAddress(const void* raw_addr) const {
346 return IsAddressInMap(raw_addr, GetWritableMemMap(), "Writable");
347}
348
349// Convert one address within the source map to the same offset within the destination map.
350static void* ConvertAddress(const void* source_address,
351 const MemMap* source_map,
352 const MemMap* destination_map) {
353 DCHECK(source_map->HasAddress(source_address)) << source_address;
354 ptrdiff_t offset = reinterpret_cast<const uint8_t*>(source_address) - source_map->Begin();
355 uintptr_t address = reinterpret_cast<uintptr_t>(destination_map->Begin()) + offset;
356 return reinterpret_cast<void*>(address);
357}
358
359template <typename T>
360T* JitCodeCache::ToExecutableAddress(T* writable_address) const {
361 CHECK(IsWritableAddress(writable_address));
362 if (writable_address == nullptr) {
363 return nullptr;
364 }
365 void* executable_address = ConvertAddress(writable_address,
366 GetWritableMemMap(),
367 executable_code_map_.get());
368 CHECK(IsExecutableAddress(executable_address));
369 return reinterpret_cast<T*>(executable_address);
370}
371
372void* JitCodeCache::ToWritableAddress(const void* executable_address) const {
373 CHECK(IsExecutableAddress(executable_address));
374 if (executable_address == nullptr) {
375 return nullptr;
376 }
377 void* writable_address = ConvertAddress(executable_address,
378 executable_code_map_.get(),
379 GetWritableMemMap());
380 CHECK(IsWritableAddress(writable_address));
381 return writable_address;
382}
383
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800384class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100385 public:
David Sehrd1dbb742017-07-17 11:20:38 -0700386 explicit ScopedCodeCacheWrite(JitCodeCache* code_cache, bool only_for_tlb_shootdown = false)
387 : ScopedTrace("ScopedCodeCacheWrite") {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800388 ScopedTrace trace("mprotect all");
David Sehrd1dbb742017-07-17 11:20:38 -0700389 int prot_to_start_writing = kProtAll;
390 if (code_cache->writable_code_map_ == nullptr) {
391 // If there is only one mapping, use the executable mapping and toggle between rwx and rx.
392 prot_to_start_writing = kProtAll;
393 prot_to_stop_writing_ = kProtCode;
394 } else {
395 // If there are two mappings, use the writable mapping and toggle between rw and r.
396 prot_to_start_writing = kProtData;
397 prot_to_stop_writing_ = kProtReadOnly;
398 }
399 writable_map_ = code_cache->GetWritableMemMap();
400 // If we're using ScopedCacheWrite only for TLB shootdown, we limit the scope of mprotect to
401 // one page.
402 size_ = only_for_tlb_shootdown ? kPageSize : writable_map_->Size();
403 CHECKED_MPROTECT(writable_map_->Begin(), size_, prot_to_start_writing);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800404 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100405 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800406 ScopedTrace trace("mprotect code");
David Sehrd1dbb742017-07-17 11:20:38 -0700407 CHECKED_MPROTECT(writable_map_->Begin(), size_, prot_to_stop_writing_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100408 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100409
David Sehrd1dbb742017-07-17 11:20:38 -0700410 private:
411 int prot_to_stop_writing_;
412 MemMap* writable_map_;
413 size_t size_;
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100414
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100415 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
416};
417
418uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100419 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000420 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700421 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000422 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100423 size_t frame_size_in_bytes,
424 size_t core_spill_mask,
425 size_t fp_spill_mask,
426 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000427 size_t code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000428 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000429 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700430 Handle<mirror::ObjectArray<mirror::Object>> roots,
431 bool has_should_deoptimize_flag,
432 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100433 uint8_t* result = CommitCodeInternal(self,
434 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000435 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700436 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000437 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100438 frame_size_in_bytes,
439 core_spill_mask,
440 fp_spill_mask,
441 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000442 code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000443 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000444 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700445 roots,
446 has_should_deoptimize_flag,
447 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100448 if (result == nullptr) {
449 // Retry.
450 GarbageCollectCache(self);
451 result = CommitCodeInternal(self,
452 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000453 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700454 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000455 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100456 frame_size_in_bytes,
457 core_spill_mask,
458 fp_spill_mask,
459 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000460 code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000461 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000462 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700463 roots,
464 has_should_deoptimize_flag,
465 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100466 }
467 return result;
468}
469
470bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
471 bool in_collection = false;
472 while (collection_in_progress_) {
473 in_collection = true;
474 lock_cond_.Wait(self);
475 }
476 return in_collection;
477}
478
479static uintptr_t FromCodeToAllocation(const void* code) {
480 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
481 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
482}
483
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000484static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
485 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
486}
487
488static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
489 // The length of the table is stored just before the stack map (and therefore at the end of
490 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
491 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
492}
493
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800494static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
495 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
496 // pointer.
497 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
498}
499
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000500static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
501 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
502}
503
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000504static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
505 REQUIRES_SHARED(Locks::mutator_lock_) {
506 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800507 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000508 // Put all roots in `roots_data`.
509 for (uint32_t i = 0; i < length; ++i) {
510 ObjPtr<mirror::Object> object = roots->Get(i);
511 if (kIsDebugBuild) {
512 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000513 if (object->IsString()) {
514 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
515 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
516 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
517 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000518 }
519 gc_roots[i] = GcRoot<mirror::Object>(object);
520 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000521}
522
David Sehrd1dbb742017-07-17 11:20:38 -0700523uint8_t* JitCodeCache::GetRootTable(const void* code_ptr, uint32_t* number_of_roots) {
524 CHECK(IsExecutableAddress(code_ptr));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000525 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
David Sehrd1dbb742017-07-17 11:20:38 -0700526 // GetOptimizedCodeInfoPtr uses offsets relative to the EXECUTABLE address.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000527 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
528 uint32_t roots = GetNumberOfRoots(data);
529 if (number_of_roots != nullptr) {
530 *number_of_roots = roots;
531 }
532 return data - ComputeRootTableSize(roots);
533}
534
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100535// Use a sentinel for marking entries in the JIT table that have been cleared.
536// This helps diagnosing in case the compiled code tries to wrongly access such
537// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700538static mirror::Class* const weak_sentinel =
539 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100540
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000541// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100542static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
543 IsMarkedVisitor* visitor,
544 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000545 REQUIRES_SHARED(Locks::mutator_lock_) {
546 // This does not need a read barrier because this is called by GC.
547 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100548 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000549 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
550 // Look at the classloader of the class to know if it has been unloaded.
551 // This does not need a read barrier because this is called by GC.
552 mirror::Object* class_loader =
553 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
554 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
555 // The class loader is live, update the entry if the class has moved.
556 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
557 // Note that new_object can be null for CMS and newly allocated objects.
558 if (new_cls != nullptr && new_cls != cls) {
559 *root_ptr = GcRoot<mirror::Class>(new_cls);
560 }
561 } else {
562 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100563 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000564 }
565 }
566}
567
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000568void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
569 MutexLock mu(Thread::Current(), lock_);
570 for (const auto& entry : method_code_map_) {
David Sehrd1dbb742017-07-17 11:20:38 -0700571 // GetRootTable takes an EXECUTABLE address.
572 CHECK(IsExecutableAddress(entry.first));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000573 uint32_t number_of_roots = 0;
574 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
575 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
576 for (uint32_t i = 0; i < number_of_roots; ++i) {
577 // This does not need a read barrier because this is called by GC.
578 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100579 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000580 // entry got deleted in a previous sweep.
581 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
582 mirror::Object* new_object = visitor->IsMarked(object);
583 // We know the string is marked because it's a strongly-interned string that
584 // is always alive. The IsMarked implementation of the CMS collector returns
585 // null for newly allocated objects, but we know those haven't moved. Therefore,
586 // only update the entry if we get a different non-null string.
587 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
588 // out of the weak access/creation pause. b/32167580
589 if (new_object != nullptr && new_object != object) {
590 DCHECK(new_object->IsString());
591 roots[i] = GcRoot<mirror::Object>(new_object);
592 }
593 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100594 ProcessWeakClass(
595 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000596 }
597 }
598 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000599 // Walk over inline caches to clear entries containing unloaded classes.
600 for (ProfilingInfo* info : profiling_infos_) {
601 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
602 InlineCache* cache = &info->cache_[i];
603 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100604 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000605 }
606 }
607 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000608}
609
David Sehrd1dbb742017-07-17 11:20:38 -0700610void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
611 CHECK(IsExecutableAddress(code_ptr));
David Srbecky5cc349f2015-12-18 15:04:48 +0000612 // Notify native debugger that we are about to remove the code.
613 // It does nothing if we are not using native debugger.
614 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
David Sehrd1dbb742017-07-17 11:20:38 -0700615 // GetRootTable takes an EXECUTABLE address.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000616 FreeData(GetRootTable(code_ptr));
David Sehrd1dbb742017-07-17 11:20:38 -0700617 FreeRawCode(reinterpret_cast<uint8_t*>(FromCodeToAllocation(code_ptr)));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100618}
619
Mingyao Yang063fc772016-08-02 11:02:54 -0700620void JitCodeCache::FreeAllMethodHeaders(
621 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
David Sehrd1dbb742017-07-17 11:20:38 -0700622 // method_headers are expected to be in the executable region.
Mingyao Yang063fc772016-08-02 11:02:54 -0700623 {
624 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
625 Runtime::Current()->GetClassHierarchyAnalysis()
626 ->RemoveDependentsWithMethodHeaders(method_headers);
627 }
628
629 // We need to remove entries in method_headers from CHA dependencies
630 // first since once we do FreeCode() below, the memory can be reused
631 // so it's possible for the same method_header to start representing
632 // different compile code.
633 MutexLock mu(Thread::Current(), lock_);
David Sehrd1dbb742017-07-17 11:20:38 -0700634 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700635 for (const OatQuickMethodHeader* method_header : method_headers) {
David Sehrd1dbb742017-07-17 11:20:38 -0700636 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700637 }
638}
639
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100640void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800641 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700642 // We use a set to first collect all method_headers whose code need to be
643 // removed. We need to free the underlying code after we remove CHA dependencies
644 // for entries in this set. And it's more efficient to iterate through
645 // the CHA dependency map just once with an unordered_set.
646 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000647 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700648 MutexLock mu(self, lock_);
649 // We do not check if a code cache GC is in progress, as this method comes
650 // with the classlinker_classes_lock_ held, and suspending ourselves could
651 // lead to a deadlock.
652 {
David Sehrd1dbb742017-07-17 11:20:38 -0700653 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700654 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
655 if (alloc.ContainsUnsafe(it->second)) {
David Sehrd1dbb742017-07-17 11:20:38 -0700656 CHECK(IsExecutableAddress(OatQuickMethodHeader::FromCodePointer(it->first)));
Mingyao Yang063fc772016-08-02 11:02:54 -0700657 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
658 it = method_code_map_.erase(it);
659 } else {
660 ++it;
661 }
662 }
663 }
664 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
665 if (alloc.ContainsUnsafe(it->first)) {
666 // Note that the code has already been pushed to method_headers in the loop
667 // above and is going to be removed in FreeCode() below.
668 it = osr_code_map_.erase(it);
669 } else {
670 ++it;
671 }
672 }
673 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
674 ProfilingInfo* info = *it;
675 if (alloc.ContainsUnsafe(info->GetMethod())) {
676 info->GetMethod()->SetProfilingInfo(nullptr);
677 FreeData(reinterpret_cast<uint8_t*>(info));
678 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000679 } else {
680 ++it;
681 }
682 }
683 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700684 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100685}
686
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000687bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
688 return kUseReadBarrier
689 ? self->GetWeakRefAccessEnabled()
690 : is_weak_access_enabled_.LoadSequentiallyConsistent();
691}
692
693void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
694 if (IsWeakAccessEnabled(self)) {
695 return;
696 }
697 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000698 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000699 while (!IsWeakAccessEnabled(self)) {
700 inline_cache_cond_.Wait(self);
701 }
702}
703
704void JitCodeCache::BroadcastForInlineCacheAccess() {
705 Thread* self = Thread::Current();
706 MutexLock mu(self, lock_);
707 inline_cache_cond_.Broadcast(self);
708}
709
710void JitCodeCache::AllowInlineCacheAccess() {
711 DCHECK(!kUseReadBarrier);
712 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
713 BroadcastForInlineCacheAccess();
714}
715
716void JitCodeCache::DisallowInlineCacheAccess() {
717 DCHECK(!kUseReadBarrier);
718 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
719}
720
721void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
722 Handle<mirror::ObjectArray<mirror::Class>> array) {
723 WaitUntilInlineCacheAccessible(Thread::Current());
724 // Note that we don't need to lock `lock_` here, the compiler calling
725 // this method has already ensured the inline cache will not be deleted.
726 for (size_t in_cache = 0, in_array = 0;
727 in_cache < InlineCache::kIndividualCacheSize;
728 ++in_cache) {
729 mirror::Class* object = ic.classes_[in_cache].Read();
730 if (object != nullptr) {
731 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000732 }
733 }
734}
735
Mathieu Chartierf044c222017-05-31 15:27:54 -0700736static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
737 if (was_warm) {
738 method->AddAccessFlags(kAccPreviouslyWarm);
739 }
740 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
741 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100742 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
743 // the warmup threshold is 1.
744 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
745 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700746}
747
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100748uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
749 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000750 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700751 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000752 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100753 size_t frame_size_in_bytes,
754 size_t core_spill_mask,
755 size_t fp_spill_mask,
756 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000757 size_t code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000758 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000759 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700760 Handle<mirror::ObjectArray<mirror::Object>> roots,
761 bool has_should_deoptimize_flag,
762 const ArenaSet<ArtMethod*>&
763 cha_single_implementation_list) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000764 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100765 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
766 // Ensure the header ends up at expected instruction alignment.
767 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
768 size_t total_size = header_size + code_size;
769
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100770 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100771 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000772 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100773 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000774 ScopedThreadSuspension sts(self, kSuspended);
775 MutexLock mu(self, lock_);
776 WaitForPotentialCollectionToComplete(self);
777 {
David Sehrd1dbb742017-07-17 11:20:38 -0700778 ScopedCodeCacheWrite scc(this);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000779 memory = AllocateCode(total_size);
780 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000781 return nullptr;
782 }
David Sehrd1dbb742017-07-17 11:20:38 -0700783 uint8_t* writable_ptr = memory + header_size;
784 code_ptr = ToExecutableAddress(writable_ptr);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000785
David Sehrd1dbb742017-07-17 11:20:38 -0700786 std::copy(code, code + code_size, writable_ptr);
787 OatQuickMethodHeader* writable_method_header =
788 OatQuickMethodHeader::FromCodePointer(writable_ptr);
789 // We need to be able to write the OatQuickMethodHeader, so we use writable_method_header.
790 // Otherwise, the offsets encoded in OatQuickMethodHeader are used relative to an executable
791 // address, so we use code_ptr.
792 new (writable_method_header) OatQuickMethodHeader(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000793 code_ptr - stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700794 code_ptr - method_info,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000795 frame_size_in_bytes,
796 core_spill_mask,
797 fp_spill_mask,
798 code_size);
Kevin Brodskyb93ce182016-12-15 14:23:09 +0000799 // Flush caches before we remove write permission because some ARMv8 Qualcomm kernels may
800 // trigger a segfault if a page fault occurs when requesting a cache maintenance operation.
801 // This is a kernel bug that we need to work around until affected devices (e.g. Nexus 5X and
802 // 6P) stop being supported or their kernels are fixed.
Artem Udovichenkob18a6692016-11-17 10:51:58 +0300803 //
Kevin Brodskyb93ce182016-12-15 14:23:09 +0000804 // For reference, this behavior is caused by this commit:
805 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
Artem Udovichenkob18a6692016-11-17 10:51:58 +0300806 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
807 reinterpret_cast<char*>(code_ptr + code_size));
David Sehrd1dbb742017-07-17 11:20:38 -0700808 if (writable_ptr != code_ptr) {
809 FlushDataCache(reinterpret_cast<char*>(writable_ptr),
810 reinterpret_cast<char*>(writable_ptr + code_size));
811 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700812 DCHECK(!Runtime::Current()->IsAotCompiler());
813 if (has_should_deoptimize_flag) {
David Sehrd1dbb742017-07-17 11:20:38 -0700814 writable_method_header->SetHasShouldDeoptimizeFlag();
Mingyao Yang063fc772016-08-02 11:02:54 -0700815 }
David Sehrd1dbb742017-07-17 11:20:38 -0700816 // All the pointers exported from the cache are executable addresses.
817 method_header = ToExecutableAddress(writable_method_header);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100818 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100819
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000820 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100821 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000822 // We need to update the entry point in the runnable state for the instrumentation.
823 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700824 // Need cha_lock_ for checking all single-implementation flags and register
825 // dependencies.
826 MutexLock cha_mu(self, *Locks::cha_lock_);
827 bool single_impl_still_valid = true;
828 for (ArtMethod* single_impl : cha_single_implementation_list) {
829 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700830 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
831 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700832 single_impl_still_valid = false;
Mathieu Chartierf044c222017-05-31 15:27:54 -0700833 ClearMethodCounter(method, /*was_warm*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700834 break;
835 }
836 }
837
838 // Discard the code if any single-implementation assumptions are now invalid.
839 if (!single_impl_still_valid) {
840 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
841 return nullptr;
842 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000843 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800844 << "Should not be using cha on debuggable apps/runs!";
845
Mingyao Yang063fc772016-08-02 11:02:54 -0700846 for (ArtMethod* single_impl : cha_single_implementation_list) {
847 Runtime::Current()->GetClassHierarchyAnalysis()->AddDependency(
848 single_impl, method, method_header);
849 }
850
851 // The following needs to be guarded by cha_lock_ also. Otherwise it's
852 // possible that the compiled code is considered invalidated by some class linking,
853 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000854 MutexLock mu(self, lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000855 // Fill the root table before updating the entry point.
David Sehrd1dbb742017-07-17 11:20:38 -0700856 CHECK(IsDataAddress(roots_data));
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000857 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100858 DCHECK_LE(roots_data, stack_map);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000859 FillRootTable(roots_data, roots);
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100860 {
861 // Flush data cache, as compiled code references literals in it.
862 // We also need a TLB shootdown to act as memory barrier across cores.
David Sehrd1dbb742017-07-17 11:20:38 -0700863 ScopedCodeCacheWrite ccw(this, /* only_for_tlb_shootdown */ true);
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100864 FlushDataCache(reinterpret_cast<char*>(roots_data),
865 reinterpret_cast<char*>(roots_data + data_size));
866 }
867 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000868 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000869 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000870 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100871 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000872 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
873 method, method_header->GetEntryPoint());
874 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000875 if (collection_in_progress_) {
876 // We need to update the live bitmap if there is a GC to ensure it sees this new
877 // code.
878 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
879 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000880 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000881 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100882 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700883 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000884 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
885 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
886 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700887 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
888 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000889 histogram_code_memory_use_.AddValue(code_size);
890 if (code_size > kCodeSizeLogThreshold) {
891 LOG(INFO) << "JIT allocated "
892 << PrettySize(code_size)
893 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700894 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000895 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000896 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100897
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100898 return reinterpret_cast<uint8_t*>(method_header);
899}
900
901size_t JitCodeCache::CodeCacheSize() {
902 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000903 return CodeCacheSizeLocked();
904}
905
Orion Hodsoneced6922017-06-01 10:54:28 +0100906bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
907 MutexLock mu(Thread::Current(), lock_);
908 if (method->IsNative()) {
909 return false;
910 }
911
912 bool in_cache = false;
913 {
David Sehrd1dbb742017-07-17 11:20:38 -0700914 ScopedCodeCacheWrite ccw(this);
Orion Hodsoneced6922017-06-01 10:54:28 +0100915 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
916 if (code_iter->second == method) {
917 if (release_memory) {
David Sehrd1dbb742017-07-17 11:20:38 -0700918 FreeCodeAndData(code_iter->first);
Orion Hodsoneced6922017-06-01 10:54:28 +0100919 }
920 code_iter = method_code_map_.erase(code_iter);
921 in_cache = true;
922 continue;
923 }
924 ++code_iter;
925 }
926 }
927
928 bool osr = false;
929 auto code_map = osr_code_map_.find(method);
930 if (code_map != osr_code_map_.end()) {
931 osr_code_map_.erase(code_map);
932 osr = true;
933 }
934
935 if (!in_cache) {
936 return false;
937 }
938
939 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
940 if (info != nullptr) {
941 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
942 DCHECK(profile != profiling_infos_.end());
943 profiling_infos_.erase(profile);
944 }
945 method->SetProfilingInfo(nullptr);
946 method->ClearCounter();
947 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
948 method, GetQuickToInterpreterBridge());
949 VLOG(jit)
950 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
951 << ArtMethod::PrettyMethod(method) << "@" << method
952 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
953 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
954 return true;
955}
956
Alex Lightdba61482016-12-21 08:20:29 -0800957// This notifies the code cache that the given method has been redefined and that it should remove
958// any cached information it has on the method. All threads must be suspended before calling this
959// method. The compiled code for the method (if there is any) must not be in any threads call stack.
960void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
961 MutexLock mu(Thread::Current(), lock_);
962 if (method->IsNative()) {
963 return;
964 }
965 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
966 if (info != nullptr) {
967 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
968 DCHECK(profile != profiling_infos_.end());
969 profiling_infos_.erase(profile);
970 }
971 method->SetProfilingInfo(nullptr);
David Sehrd1dbb742017-07-17 11:20:38 -0700972 ScopedCodeCacheWrite ccw(this);
Andreas Gampe39e67382017-05-15 19:26:38 -0700973 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
Alex Lightdba61482016-12-21 08:20:29 -0800974 if (code_iter->second == method) {
David Sehrd1dbb742017-07-17 11:20:38 -0700975 FreeCodeAndData(code_iter->first);
Andreas Gampe39e67382017-05-15 19:26:38 -0700976 code_iter = method_code_map_.erase(code_iter);
977 continue;
Alex Lightdba61482016-12-21 08:20:29 -0800978 }
Andreas Gampe39e67382017-05-15 19:26:38 -0700979 ++code_iter;
Alex Lightdba61482016-12-21 08:20:29 -0800980 }
981 auto code_map = osr_code_map_.find(method);
982 if (code_map != osr_code_map_.end()) {
983 osr_code_map_.erase(code_map);
984 }
985}
986
987// This invalidates old_method. Once this function returns one can no longer use old_method to
988// execute code unless it is fixed up. This fixup will happen later in the process of installing a
989// class redefinition.
990// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
991// shouldn't be used since it is no longer logically in the jit code cache.
992// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
993void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000994 // Native methods have no profiling info and need no special handling from the JIT code cache.
995 if (old_method->IsNative()) {
996 return;
997 }
Alex Lightdba61482016-12-21 08:20:29 -0800998 MutexLock mu(Thread::Current(), lock_);
999 // Update ProfilingInfo to the new one and remove it from the old_method.
1000 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
1001 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
1002 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
1003 old_method->SetProfilingInfo(nullptr);
1004 // Since the JIT should be paused and all threads suspended by the time this is called these
1005 // checks should always pass.
1006 DCHECK(!info->IsInUseByCompiler());
1007 new_method->SetProfilingInfo(info);
1008 info->method_ = new_method;
1009 }
1010 // Update method_code_map_ to point to the new method.
1011 for (auto& it : method_code_map_) {
1012 if (it.second == old_method) {
1013 it.second = new_method;
1014 }
1015 }
1016 // Update osr_code_map_ to point to the new method.
1017 auto code_map = osr_code_map_.find(old_method);
1018 if (code_map != osr_code_map_.end()) {
1019 osr_code_map_.Put(new_method, code_map->second);
1020 osr_code_map_.erase(old_method);
1021 }
1022}
1023
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001024size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001025 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001026}
1027
1028size_t JitCodeCache::DataCacheSize() {
1029 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001030 return DataCacheSizeLocked();
1031}
1032
1033size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001034 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001035}
1036
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001037void JitCodeCache::ClearData(Thread* self,
1038 uint8_t* stack_map_data,
1039 uint8_t* roots_data) {
1040 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
David Sehrd1dbb742017-07-17 11:20:38 -07001041 CHECK(IsDataAddress(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001042 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001043 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001044}
1045
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001046size_t JitCodeCache::ReserveData(Thread* self,
1047 size_t stack_map_size,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001048 size_t method_info_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001049 size_t number_of_roots,
1050 ArtMethod* method,
1051 uint8_t** stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001052 uint8_t** method_info_data,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001053 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001054 size_t table_size = ComputeRootTableSize(number_of_roots);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001055 size_t size = RoundUp(stack_map_size + method_info_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001056 uint8_t* result = nullptr;
1057
1058 {
1059 ScopedThreadSuspension sts(self, kSuspended);
1060 MutexLock mu(self, lock_);
1061 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001062 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001063 }
1064
1065 if (result == nullptr) {
1066 // Retry.
1067 GarbageCollectCache(self);
1068 ScopedThreadSuspension sts(self, kSuspended);
1069 MutexLock mu(self, lock_);
1070 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001071 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001072 }
1073
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001074 MutexLock mu(self, lock_);
1075 histogram_stack_map_memory_use_.AddValue(size);
1076 if (size > kStackMapSizeLogThreshold) {
1077 LOG(INFO) << "JIT allocated "
1078 << PrettySize(size)
1079 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001080 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001081 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001082 if (result != nullptr) {
1083 *roots_data = result;
1084 *stack_map_data = result + table_size;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001085 *method_info_data = *stack_map_data + stack_map_size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001086 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001087 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001088 } else {
1089 *roots_data = nullptr;
1090 *stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001091 *method_info_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001092 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001093 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001094}
1095
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001096class MarkCodeVisitor FINAL : public StackVisitor {
1097 public:
1098 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
1099 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
1100 code_cache_(code_cache_in),
1101 bitmap_(code_cache_->GetLiveBitmap()) {}
1102
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001103 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001104 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
1105 if (method_header == nullptr) {
1106 return true;
1107 }
1108 const void* code = method_header->GetCode();
1109 if (code_cache_->ContainsPc(code)) {
1110 // Use the atomic set version, as multiple threads are executing this code.
1111 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1112 }
1113 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001114 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001115
1116 private:
1117 JitCodeCache* const code_cache_;
1118 CodeCacheBitmap* const bitmap_;
1119};
1120
1121class MarkCodeClosure FINAL : public Closure {
1122 public:
1123 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
1124 : code_cache_(code_cache), barrier_(barrier) {}
1125
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001126 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001127 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001128 DCHECK(thread == Thread::Current() || thread->IsSuspended());
1129 MarkCodeVisitor visitor(thread, code_cache_);
1130 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001131 if (kIsDebugBuild) {
1132 // The stack walking code queries the side instrumentation stack if it
1133 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1134 // must have been seen. We sanity check this below.
1135 for (const instrumentation::InstrumentationStackFrame& frame
1136 : *thread->GetInstrumentationStack()) {
1137 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1138 // its stack frame, it is not the method owning return_pc_. We just pass null to
1139 // LookupMethodHeader: the method is only checked against in debug builds.
1140 OatQuickMethodHeader* method_header =
1141 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
1142 if (method_header != nullptr) {
1143 const void* code = method_header->GetCode();
1144 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
1145 }
1146 }
1147 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001148 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001149 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001150
1151 private:
1152 JitCodeCache* const code_cache_;
1153 Barrier* const barrier_;
1154};
1155
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001156void JitCodeCache::NotifyCollectionDone(Thread* self) {
1157 collection_in_progress_ = false;
1158 lock_cond_.Broadcast(self);
1159}
1160
1161void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
1162 size_t per_space_footprint = new_footprint / 2;
David Sehrd1dbb742017-07-17 11:20:38 -07001163 CHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001164 DCHECK_EQ(per_space_footprint * 2, new_footprint);
1165 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
1166 {
David Sehrd1dbb742017-07-17 11:20:38 -07001167 ScopedCodeCacheWrite scc(this);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001168 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
1169 }
1170}
1171
1172bool JitCodeCache::IncreaseCodeCacheCapacity() {
1173 if (current_capacity_ == max_capacity_) {
1174 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001175 }
1176
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001177 // Double the capacity if we're below 1MB, or increase it by 1MB if
1178 // we're above.
1179 if (current_capacity_ < 1 * MB) {
1180 current_capacity_ *= 2;
1181 } else {
1182 current_capacity_ += 1 * MB;
1183 }
1184 if (current_capacity_ > max_capacity_) {
1185 current_capacity_ = max_capacity_;
1186 }
1187
1188 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
1189 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
1190 }
1191
1192 SetFootprintLimit(current_capacity_);
1193
1194 return true;
1195}
1196
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001197void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1198 Barrier barrier(0);
1199 size_t threads_running_checkpoint = 0;
1200 MarkCodeClosure closure(this, &barrier);
1201 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1202 // Now that we have run our checkpoint, move to a suspended state and wait
1203 // for other threads to run the checkpoint.
1204 ScopedThreadSuspension sts(self, kSuspended);
1205 if (threads_running_checkpoint != 0) {
1206 barrier.Increment(self, threads_running_checkpoint);
1207 }
1208}
1209
Nicolas Geoffray35122442016-03-02 12:05:30 +00001210bool JitCodeCache::ShouldDoFullCollection() {
1211 if (current_capacity_ == max_capacity_) {
1212 // Always do a full collection when the code cache is full.
1213 return true;
1214 } else if (current_capacity_ < kReservedCapacity) {
1215 // Always do partial collection when the code cache size is below the reserved
1216 // capacity.
1217 return false;
1218 } else if (last_collection_increased_code_cache_) {
1219 // This time do a full collection.
1220 return true;
1221 } else {
1222 // This time do a partial collection.
1223 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001224 }
1225}
1226
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001227void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001228 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001229 if (!garbage_collect_code_) {
1230 MutexLock mu(self, lock_);
1231 IncreaseCodeCacheCapacity();
1232 return;
1233 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001234
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001235 // Wait for an existing collection, or let everyone know we are starting one.
1236 {
1237 ScopedThreadSuspension sts(self, kSuspended);
1238 MutexLock mu(self, lock_);
1239 if (WaitForPotentialCollectionToComplete(self)) {
1240 return;
1241 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001242 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001243 live_bitmap_.reset(CodeCacheBitmap::Create(
1244 "code-cache-bitmap",
David Sehrd1dbb742017-07-17 11:20:38 -07001245 reinterpret_cast<uintptr_t>(executable_code_map_->Begin()),
1246 reinterpret_cast<uintptr_t>(executable_code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001247 collection_in_progress_ = true;
1248 }
1249 }
1250
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001251 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001252 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001253 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001254
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001255 bool do_full_collection = false;
1256 {
1257 MutexLock mu(self, lock_);
1258 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001259 }
1260
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001261 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
1262 LOG(INFO) << "Do "
1263 << (do_full_collection ? "full" : "partial")
1264 << " code cache collection, code="
1265 << PrettySize(CodeCacheSize())
1266 << ", data=" << PrettySize(DataCacheSize());
1267 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001268
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001269 DoCollection(self, /* collect_profiling_info */ do_full_collection);
1270
1271 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
1272 LOG(INFO) << "After code cache collection, code="
1273 << PrettySize(CodeCacheSize())
1274 << ", data=" << PrettySize(DataCacheSize());
1275 }
1276
1277 {
1278 MutexLock mu(self, lock_);
1279
1280 // Increase the code cache only when we do partial collections.
1281 // TODO: base this strategy on how full the code cache is?
1282 if (do_full_collection) {
1283 last_collection_increased_code_cache_ = false;
1284 } else {
1285 last_collection_increased_code_cache_ = true;
1286 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001287 }
1288
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001289 bool next_collection_will_be_full = ShouldDoFullCollection();
1290
1291 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001292 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001293 // Save the entry point of methods we have compiled, and update the entry
1294 // point of those methods to the interpreter. If the method is invoked, the
1295 // interpreter will update its entry point to the compiled code and call it.
1296 for (ProfilingInfo* info : profiling_infos_) {
1297 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1298 if (ContainsPc(entry_point)) {
1299 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001300 // Don't call Instrumentation::UpdateMethods, as it can check the declaring
1301 // class of the method. We may be concurrently running a GC which makes accessing
1302 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1303 // checked that the current entry point is JIT compiled code.
1304 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001305 }
1306 }
1307
1308 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
1309 }
1310 live_bitmap_.reset(nullptr);
1311 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001312 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001313 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001314 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001315}
1316
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001317void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001318 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001319 std::unordered_set<OatQuickMethodHeader*> method_headers;
1320 {
1321 MutexLock mu(self, lock_);
David Sehrd1dbb742017-07-17 11:20:38 -07001322 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -07001323 // Iterate over all compiled code and remove entries that are not marked.
1324 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1325 const void* code_ptr = it->first;
David Sehrd1dbb742017-07-17 11:20:38 -07001326 CHECK(IsExecutableAddress(code_ptr));
Mingyao Yang063fc772016-08-02 11:02:54 -07001327 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1328 if (GetLiveBitmap()->Test(allocation)) {
1329 ++it;
1330 } else {
David Sehrd1dbb742017-07-17 11:20:38 -07001331 CHECK(IsExecutableAddress(it->first));
Mingyao Yang063fc772016-08-02 11:02:54 -07001332 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
1333 it = method_code_map_.erase(it);
1334 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001335 }
1336 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001337 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001338}
1339
1340void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001341 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001342 {
1343 MutexLock mu(self, lock_);
1344 if (collect_profiling_info) {
1345 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1346 // Also remove the saved entry point from the ProfilingInfo objects.
1347 for (ProfilingInfo* info : profiling_infos_) {
1348 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001349 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001350 info->GetMethod()->SetProfilingInfo(nullptr);
1351 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001352
1353 if (info->GetSavedEntryPoint() != nullptr) {
1354 info->SetSavedEntryPoint(nullptr);
1355 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001356 // give it a chance to be hot again.
1357 ClearMethodCounter(info->GetMethod(), /*was_warm*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001358 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001359 }
1360 } else if (kIsDebugBuild) {
1361 // Sanity check that the profiling infos do not have a dangling entry point.
1362 for (ProfilingInfo* info : profiling_infos_) {
1363 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001364 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001365 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001366
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001367 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1368 // an entry point is either:
1369 // - an osr compiled code, that will be removed if not in a thread call stack.
1370 // - discarded compiled code, that will be removed if not in a thread call stack.
1371 for (const auto& it : method_code_map_) {
1372 ArtMethod* method = it.second;
1373 const void* code_ptr = it.first;
David Sehrd1dbb742017-07-17 11:20:38 -07001374 CHECK(IsExecutableAddress(code_ptr));
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001375 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1376 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1377 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1378 }
1379 }
1380
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001381 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001382 // on thread stacks).
1383 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001384 }
1385
1386 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001387 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001388
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001389 // At this point, mutator threads are still running, and entrypoints of methods can
1390 // change. We do know they cannot change to a code cache entry that is not marked,
1391 // therefore we can safely remove those entries.
1392 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001393
Nicolas Geoffray35122442016-03-02 12:05:30 +00001394 if (collect_profiling_info) {
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +01001395 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001396 MutexLock mu(self, lock_);
1397 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001398 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001399 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
David Sehrd1dbb742017-07-17 11:20:38 -07001400 CHECK(IsDataAddress(info));
Nicolas Geoffray35122442016-03-02 12:05:30 +00001401 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001402 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1403 // that the compiled code would not get revived. As mutator threads run concurrently,
1404 // they may have revived the compiled code, and now we are in the situation where
1405 // a method has compiled code but no ProfilingInfo.
1406 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1407 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001408 if (ContainsPc(ptr) &&
1409 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001410 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001411 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001412 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001413 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001414 return true;
1415 }
1416 return false;
1417 });
1418 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001419 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001420 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001421}
1422
Nicolas Geoffray35122442016-03-02 12:05:30 +00001423bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001424 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001425 // Check that methods we have compiled do have a ProfilingInfo object. We would
1426 // have memory leaks of compiled code otherwise.
1427 for (const auto& it : method_code_map_) {
1428 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001429 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001430 const void* code_ptr = it.first;
1431 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1432 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1433 // If the code is not dead, then we have a problem. Note that this can even
1434 // happen just after a collection, as mutator threads are running in parallel
1435 // and could deoptimize an existing compiled code.
1436 return false;
1437 }
1438 }
1439 }
1440 return true;
1441}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001442
1443OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
1444 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
1445 if (kRuntimeISA == kArm) {
1446 // On Thumb-2, the pc is offset by one.
1447 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001448 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001449 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1450 return nullptr;
1451 }
1452
1453 MutexLock mu(Thread::Current(), lock_);
1454 if (method_code_map_.empty()) {
1455 return nullptr;
1456 }
1457 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1458 --it;
1459
1460 const void* code_ptr = it->first;
David Sehrd1dbb742017-07-17 11:20:38 -07001461 CHECK(IsExecutableAddress(code_ptr));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001462 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1463 if (!method_header->Contains(pc)) {
1464 return nullptr;
1465 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001466 if (kIsDebugBuild && method != nullptr) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001467 // When we are walking the stack to redefine classes and creating obsolete methods it is
1468 // possible that we might have updated the method_code_map by making this method obsolete in a
1469 // previous frame. Therefore we should just check that the non-obsolete version of this method
1470 // is the one we expect. We change to the non-obsolete versions in the error message since the
1471 // obsolete version of the method might not be fully initialized yet. This situation can only
1472 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
1473 // method and it->second should be identical. (See runtime/openjdkjvmti/ti_redefine.cc for more
1474 // information.)
1475 DCHECK_EQ(it->second->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
1476 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
1477 << ArtMethod::PrettyMethod(it->second->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001478 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001479 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001480 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001481}
1482
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001483OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1484 MutexLock mu(Thread::Current(), lock_);
1485 auto it = osr_code_map_.find(method);
1486 if (it == osr_code_map_.end()) {
1487 return nullptr;
1488 }
1489 return OatQuickMethodHeader::FromCodePointer(it->second);
1490}
1491
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001492ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1493 ArtMethod* method,
1494 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001495 bool retry_allocation)
1496 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1497 NO_THREAD_SAFETY_ANALYSIS {
1498 ProfilingInfo* info = nullptr;
1499 if (!retry_allocation) {
1500 // If we are allocating for the interpreter, just try to lock, to avoid
1501 // lock contention with the JIT.
1502 if (lock_.ExclusiveTryLock(self)) {
1503 info = AddProfilingInfoInternal(self, method, entries);
1504 lock_.ExclusiveUnlock(self);
1505 }
1506 } else {
1507 {
1508 MutexLock mu(self, lock_);
1509 info = AddProfilingInfoInternal(self, method, entries);
1510 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001511
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001512 if (info == nullptr) {
1513 GarbageCollectCache(self);
1514 MutexLock mu(self, lock_);
1515 info = AddProfilingInfoInternal(self, method, entries);
1516 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001517 }
1518 return info;
1519}
1520
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001521ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001522 ArtMethod* method,
1523 const std::vector<uint32_t>& entries) {
1524 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001525 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001526 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001527
1528 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001529 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001530 if (info != nullptr) {
1531 return info;
1532 }
1533
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001534 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001535 if (data == nullptr) {
1536 return nullptr;
1537 }
1538 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001539
1540 // Make sure other threads see the data in the profiling info object before the
1541 // store in the ArtMethod's ProfilingInfo pointer.
1542 QuasiAtomic::ThreadFenceRelease();
1543
David Sehrd1dbb742017-07-17 11:20:38 -07001544 CHECK(IsDataAddress(info));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001545 method->SetProfilingInfo(info);
1546 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001547 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001548 return info;
1549}
1550
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001551// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1552// is already held.
1553void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1554 if (code_mspace_ == mspace) {
1555 size_t result = code_end_;
1556 code_end_ += increment;
David Sehrd1dbb742017-07-17 11:20:38 -07001557 MemMap* writable_map = GetWritableMemMap();
1558 return reinterpret_cast<void*>(result + writable_map->Begin());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001559 } else {
1560 DCHECK_EQ(data_mspace_, mspace);
1561 size_t result = data_end_;
1562 data_end_ += increment;
1563 return reinterpret_cast<void*>(result + data_map_->Begin());
1564 }
1565}
1566
Calin Juravle99629622016-04-19 16:33:46 +01001567void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001568 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001569 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001570 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001571 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001572 for (const ProfilingInfo* info : profiling_infos_) {
1573 ArtMethod* method = info->GetMethod();
1574 const DexFile* dex_file = method->GetDexFile();
Calin Juravle940eb0c2017-01-30 19:30:44 -08001575 if (!ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
1576 // Skip dex files which are not profiled.
1577 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001578 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001579 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001580
1581 // If the method didn't reach the compilation threshold don't save the inline caches.
1582 // They might be incomplete and cause unnecessary deoptimizations.
1583 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1584 if (method->GetCounter() < jit_compile_threshold) {
1585 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001586 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001587 continue;
1588 }
1589
Calin Juravle940eb0c2017-01-30 19:30:44 -08001590 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001591 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001592 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001593 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001594 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001595 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1596 mirror::Class* cls = cache.classes_[k].Read();
1597 if (cls == nullptr) {
1598 break;
1599 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001600
Calin Juravle13439f02017-02-21 01:17:21 -08001601 // Check if the receiver is in the boot class path or if it's in the
1602 // same class loader as the caller. If not, skip it, as there is not
1603 // much we can do during AOT.
1604 if (!cls->IsBootStrapClassLoaded() &&
1605 caller->GetClassLoader() != cls->GetClassLoader()) {
1606 is_missing_types = true;
1607 continue;
1608 }
1609
Calin Juravle4ca70a32017-02-21 16:22:24 -08001610 const DexFile* class_dex_file = nullptr;
1611 dex::TypeIndex type_index;
1612
1613 if (cls->GetDexCache() == nullptr) {
1614 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001615 // Make a best effort to find the type index in the method's dex file.
1616 // We could search all open dex files but that might turn expensive
1617 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001618 class_dex_file = dex_file;
1619 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1620 } else {
1621 class_dex_file = &(cls->GetDexFile());
1622 type_index = cls->GetDexTypeIndex();
1623 }
1624 if (!type_index.IsValid()) {
1625 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001626 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001627 continue;
1628 }
1629 if (ContainsElement(dex_base_locations, class_dex_file->GetBaseLocation())) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001630 // Only consider classes from the same apk (including multidex).
1631 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001632 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001633 } else {
1634 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001635 }
1636 }
1637 if (!profile_classes.empty()) {
1638 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001639 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001640 }
1641 }
1642 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001643 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001644 }
1645}
1646
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001647uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1648 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001649}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001650
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001651bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1652 MutexLock mu(Thread::Current(), lock_);
1653 return osr_code_map_.find(method) != osr_code_map_.end();
1654}
1655
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001656bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1657 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001658 return false;
1659 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001660
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001661 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001662 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1663 return false;
1664 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001665
Andreas Gampe542451c2016-07-26 09:02:02 -07001666 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001667 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001668 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Jeff Hao00286db2017-05-30 16:53:07 -07001669 // Because the counter is not atomic, there are some rare cases where we may not hit the
1670 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
Mathieu Chartierf044c222017-05-31 15:27:54 -07001671 ClearMethodCounter(method, /*was_warm*/ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001672 return false;
1673 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001674
buzbee454b3b62016-04-07 14:42:47 -07001675 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001676 return false;
1677 }
1678
buzbee454b3b62016-04-07 14:42:47 -07001679 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001680 return true;
1681}
1682
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001683ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001684 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001685 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001686 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001687 if (!info->IncrementInlineUse()) {
1688 // Overflow of inlining uses, just bail.
1689 return nullptr;
1690 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001691 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001692 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001693}
1694
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001695void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001696 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001697 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001698 DCHECK(info != nullptr);
1699 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001700}
1701
buzbee454b3b62016-04-07 14:42:47 -07001702void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001703 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001704 DCHECK(info->IsMethodBeingCompiled(osr));
1705 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001706}
1707
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001708size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1709 MutexLock mu(Thread::Current(), lock_);
David Sehrd1dbb742017-07-17 11:20:38 -07001710 CHECK(IsExecutableAddress(ptr));
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001711 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1712}
1713
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001714void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1715 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001716 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001717 if ((profiling_info != nullptr) &&
1718 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1719 // Prevent future uses of the compiled code.
1720 profiling_info->SetSavedEntryPoint(nullptr);
1721 }
1722
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001723 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001724 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001725 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001726 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1727 method, GetQuickToInterpreterBridge());
Mathieu Chartierf044c222017-05-31 15:27:54 -07001728 ClearMethodCounter(method, /*was_warm*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001729 } else {
1730 MutexLock mu(Thread::Current(), lock_);
1731 auto it = osr_code_map_.find(method);
1732 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1733 // Remove the OSR method, to avoid using it again.
1734 osr_code_map_.erase(it);
1735 }
1736 }
1737}
1738
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001739uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1740 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1741 uint8_t* result = reinterpret_cast<uint8_t*>(
1742 mspace_memalign(code_mspace_, alignment, code_size));
1743 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1744 // Ensure the header ends up at expected instruction alignment.
1745 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
David Sehrd1dbb742017-07-17 11:20:38 -07001746 CHECK(IsWritableAddress(result));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001747 used_memory_for_code_ += mspace_usable_size(result);
1748 return result;
1749}
1750
David Sehrd1dbb742017-07-17 11:20:38 -07001751void JitCodeCache::FreeRawCode(void* code) {
1752 CHECK(IsExecutableAddress(code));
1753 void* writable_code = ToWritableAddress(code);
1754 used_memory_for_code_ -= mspace_usable_size(writable_code);
1755 mspace_free(code_mspace_, writable_code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001756}
1757
1758uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1759 void* result = mspace_malloc(data_mspace_, data_size);
David Sehrd1dbb742017-07-17 11:20:38 -07001760 CHECK(IsDataAddress(reinterpret_cast<uint8_t*>(result)));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001761 used_memory_for_data_ += mspace_usable_size(result);
1762 return reinterpret_cast<uint8_t*>(result);
1763}
1764
1765void JitCodeCache::FreeData(uint8_t* data) {
David Sehrd1dbb742017-07-17 11:20:38 -07001766 CHECK(IsDataAddress(data));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001767 used_memory_for_data_ -= mspace_usable_size(data);
1768 mspace_free(data_mspace_, data);
1769}
1770
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001771void JitCodeCache::Dump(std::ostream& os) {
1772 MutexLock mu(Thread::Current(), lock_);
1773 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1774 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1775 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1776 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1777 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1778 << "Total number of JIT compilations for on stack replacement: "
1779 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001780 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001781 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1782 histogram_code_memory_use_.PrintMemoryUse(os);
1783 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001784}
1785
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001786} // namespace jit
1787} // namespace art