blob: c8c13cb20f9b2aad89e0d3238edf5d844e690f9d [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"
Andreas Gampe170331f2017-12-07 18:41:03 -080024#include "base/logging.h" // For VLOG.
Calin Juravle66f55232015-12-08 15:09:10 +000025#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080026#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010027#include "base/time_utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070028#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000029#include "debugger_interface.h"
David Sehr9e734c72018-01-04 17:56:19 -080030#include "dex/dex_file_loader.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010031#include "entrypoints/runtime_asm_entrypoints.h"
32#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010033#include "gc/scoped_gc_critical_section.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000034#include "handle.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070035#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000036#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000037#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010038#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080039#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080040#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070041#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070042#include "object_callbacks.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000043#include "profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070044#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070045#include "stack.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000046#include "thread-current-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010047#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080048
49namespace art {
50namespace jit {
51
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010052static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
53static constexpr int kProtData = PROT_READ | PROT_WRITE;
54static constexpr int kProtCode = PROT_READ | PROT_EXEC;
55
Nicolas Geoffray933330a2016-03-16 14:20:06 +000056static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
57static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
58
Vladimir Marko2196c652017-11-30 16:16:07 +000059class JitCodeCache::JniStubKey {
60 public:
61 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
62 : shorty_(method->GetShorty()),
63 is_static_(method->IsStatic()),
64 is_fast_native_(method->IsFastNative()),
65 is_critical_native_(method->IsCriticalNative()),
66 is_synchronized_(method->IsSynchronized()) {
67 DCHECK(!(is_fast_native_ && is_critical_native_));
68 }
69
70 bool operator<(const JniStubKey& rhs) const {
71 if (is_static_ != rhs.is_static_) {
72 return rhs.is_static_;
73 }
74 if (is_synchronized_ != rhs.is_synchronized_) {
75 return rhs.is_synchronized_;
76 }
77 if (is_fast_native_ != rhs.is_fast_native_) {
78 return rhs.is_fast_native_;
79 }
80 if (is_critical_native_ != rhs.is_critical_native_) {
81 return rhs.is_critical_native_;
82 }
83 return strcmp(shorty_, rhs.shorty_) < 0;
84 }
85
86 // Update the shorty to point to another method's shorty. Call this function when removing
87 // the method that references the old shorty from JniCodeData and not removing the entire
88 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
89 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
90 const char* shorty = method->GetShorty();
91 DCHECK_STREQ(shorty_, shorty);
92 shorty_ = shorty;
93 }
94
95 private:
96 // The shorty points to a DexFile data and may need to change
97 // to point to the same shorty in a different DexFile.
98 mutable const char* shorty_;
99
100 const bool is_static_;
101 const bool is_fast_native_;
102 const bool is_critical_native_;
103 const bool is_synchronized_;
104};
105
106class JitCodeCache::JniStubData {
107 public:
108 JniStubData() : code_(nullptr), methods_() {}
109
110 void SetCode(const void* code) {
111 DCHECK(code != nullptr);
112 code_ = code;
113 }
114
115 const void* GetCode() const {
116 return code_;
117 }
118
119 bool IsCompiled() const {
120 return GetCode() != nullptr;
121 }
122
123 void AddMethod(ArtMethod* method) {
124 if (!ContainsElement(methods_, method)) {
125 methods_.push_back(method);
126 }
127 }
128
129 const std::vector<ArtMethod*>& GetMethods() const {
130 return methods_;
131 }
132
133 void RemoveMethodsIn(const LinearAlloc& alloc) {
134 auto kept_end = std::remove_if(
135 methods_.begin(),
136 methods_.end(),
137 [&alloc](ArtMethod* method) { return alloc.ContainsUnsafe(method); });
138 methods_.erase(kept_end, methods_.end());
139 }
140
141 bool RemoveMethod(ArtMethod* method) {
142 auto it = std::find(methods_.begin(), methods_.end(), method);
143 if (it != methods_.end()) {
144 methods_.erase(it);
145 return true;
146 } else {
147 return false;
148 }
149 }
150
151 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
152 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
153 }
154
155 private:
156 const void* code_;
157 std::vector<ArtMethod*> methods_;
158};
159
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000160JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
161 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000162 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000163 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800164 ScopedTrace trace(__PRETTY_FUNCTION__);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100165 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000166
David Sehrd1dbb742017-07-17 11:20:38 -0700167 // Generating debug information is for using the Linux perf tool on
168 // host which does not work with ashmem.
Nicolas Geoffray520dadf2017-07-19 15:33:11 +0100169 // Also, target linux does not support ashmem.
170 bool use_ashmem = !generate_debug_info && !kIsTargetLinux;
David Sehrd1dbb742017-07-17 11:20:38 -0700171
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000172 // With 'perf', we want a 1-1 mapping between an address and a method.
173 bool garbage_collect_code = !generate_debug_info;
174
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000175 // We need to have 32 bit offsets from method headers in code cache which point to things
176 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
177 // Ensure we're below 1 GB to be safe.
178 if (max_capacity > 1 * GB) {
179 std::ostringstream oss;
180 oss << "Maxium code cache capacity is limited to 1 GB, "
181 << PrettySize(max_capacity) << " is too big";
182 *error_msg = oss.str();
183 return nullptr;
184 }
185
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800186 std::string error_str;
187 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000188 // Map in low 4gb to simplify accessing root tables for x86_64.
189 // We could do PC-relative addressing to avoid this problem, but that
190 // would require reserving code and data area before submitting, which
191 // means more windows for the code memory to be RWX.
Andreas Gampee4deaf32017-06-09 15:27:15 -0700192 std::unique_ptr<MemMap> data_map(MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000193 "data-code-cache", nullptr,
194 max_capacity,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700195 kProtData,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000196 /* low_4gb */ true,
197 /* reuse */ false,
198 &error_str,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700199 use_ashmem));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100200 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800201 std::ostringstream oss;
Andreas Gampee4deaf32017-06-09 15:27:15 -0700202 oss << "Failed to create read write cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800203 *error_msg = oss.str();
204 return nullptr;
205 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100206
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100207 // Align both capacities to page size, as that's the unit mspaces use.
208 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
209 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100210
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100211 // Data cache is 1 / 2 of the map.
212 // TODO: Make this variable?
213 size_t data_size = max_capacity / 2;
214 size_t code_size = max_capacity - data_size;
215 DCHECK_EQ(code_size + data_size, max_capacity);
216 uint8_t* divider = data_map->Begin() + data_size;
David Sehrd1dbb742017-07-17 11:20:38 -0700217
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100218 MemMap* code_map =
219 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
David Sehrd1dbb742017-07-17 11:20:38 -0700220 if (code_map == nullptr) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100221 std::ostringstream oss;
222 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
223 *error_msg = oss.str();
David Sehrd1dbb742017-07-17 11:20:38 -0700224 return nullptr;
225 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100226 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000227 data_size = initial_capacity / 2;
228 code_size = initial_capacity - data_size;
229 DCHECK_EQ(code_size + data_size, initial_capacity);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100230 return new JitCodeCache(
231 code_map, data_map.release(), code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800232}
233
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100234JitCodeCache::JitCodeCache(MemMap* code_map,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000235 MemMap* data_map,
236 size_t initial_code_capacity,
237 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000238 size_t max_capacity,
239 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100240 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000241 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100242 collection_in_progress_(false),
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100243 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000244 data_map_(data_map),
245 max_capacity_(max_capacity),
246 current_capacity_(initial_code_capacity + initial_data_capacity),
247 code_end_(initial_code_capacity),
248 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000249 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000250 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000251 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000252 used_memory_for_data_(0),
253 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000254 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000255 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000256 number_of_collections_(0),
257 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
258 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000259 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
260 is_weak_access_enabled_(true),
261 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100262
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000263 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100264 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000265 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100266
267 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
268 PLOG(FATAL) << "create_mspace_with_base failed";
269 }
270
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000271 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100272
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700273 CheckedCall(mprotect,
274 "mprotect jit code cache",
275 code_map_->Begin(),
276 code_map_->Size(),
277 kProtCode);
278 CheckedCall(mprotect,
279 "mprotect jit data cache",
280 data_map_->Begin(),
281 data_map_->Size(),
282 kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100283
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000284 VLOG(jit) << "Created jit code cache: initial data size="
285 << PrettySize(initial_data_capacity)
286 << ", initial code size="
287 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800288}
289
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000290JitCodeCache::~JitCodeCache() {}
291
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100292bool JitCodeCache::ContainsPc(const void* ptr) const {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100293 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800294}
295
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000296bool JitCodeCache::ContainsMethod(ArtMethod* method) {
297 MutexLock mu(Thread::Current(), lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000298 if (UNLIKELY(method->IsNative())) {
299 auto it = jni_stubs_map_.find(JniStubKey(method));
300 if (it != jni_stubs_map_.end() &&
301 it->second.IsCompiled() &&
302 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000303 return true;
304 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000305 } else {
306 for (const auto& it : method_code_map_) {
307 if (it.second == method) {
308 return true;
309 }
310 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000311 }
312 return false;
313}
314
Vladimir Marko2196c652017-11-30 16:16:07 +0000315const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
316 DCHECK(method->IsNative());
317 MutexLock mu(Thread::Current(), lock_);
318 auto it = jni_stubs_map_.find(JniStubKey(method));
319 if (it != jni_stubs_map_.end()) {
320 JniStubData& data = it->second;
321 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
322 return data.GetCode();
323 }
324 }
325 return nullptr;
326}
327
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800328class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100329 public:
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100330 explicit ScopedCodeCacheWrite(MemMap* code_map, bool only_for_tlb_shootdown = false)
331 : ScopedTrace("ScopedCodeCacheWrite"),
332 code_map_(code_map),
333 only_for_tlb_shootdown_(only_for_tlb_shootdown) {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800334 ScopedTrace trace("mprotect all");
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700335 CheckedCall(mprotect,
336 "make code writable",
337 code_map_->Begin(),
338 only_for_tlb_shootdown_ ? kPageSize : code_map_->Size(),
339 kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800340 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100341 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800342 ScopedTrace trace("mprotect code");
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700343 CheckedCall(mprotect,
344 "make code protected",
345 code_map_->Begin(),
346 only_for_tlb_shootdown_ ? kPageSize : code_map_->Size(),
347 kProtCode);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100348 }
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700349
David Sehrd1dbb742017-07-17 11:20:38 -0700350 private:
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100351 MemMap* const code_map_;
352
353 // If we're using ScopedCacheWrite only for TLB shootdown, we limit the scope of mprotect to
354 // one page.
355 const bool only_for_tlb_shootdown_;
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100356
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100357 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
358};
359
360uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100361 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000362 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700363 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000364 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100365 size_t frame_size_in_bytes,
366 size_t core_spill_mask,
367 size_t fp_spill_mask,
368 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000369 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100370 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000371 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700372 Handle<mirror::ObjectArray<mirror::Object>> roots,
373 bool has_should_deoptimize_flag,
374 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100375 uint8_t* result = CommitCodeInternal(self,
376 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000377 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700378 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000379 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100380 frame_size_in_bytes,
381 core_spill_mask,
382 fp_spill_mask,
383 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000384 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100385 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000386 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700387 roots,
388 has_should_deoptimize_flag,
389 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100390 if (result == nullptr) {
391 // Retry.
392 GarbageCollectCache(self);
393 result = CommitCodeInternal(self,
394 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000395 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700396 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000397 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100398 frame_size_in_bytes,
399 core_spill_mask,
400 fp_spill_mask,
401 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000402 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100403 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000404 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700405 roots,
406 has_should_deoptimize_flag,
407 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100408 }
409 return result;
410}
411
412bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
413 bool in_collection = false;
414 while (collection_in_progress_) {
415 in_collection = true;
416 lock_cond_.Wait(self);
417 }
418 return in_collection;
419}
420
421static uintptr_t FromCodeToAllocation(const void* code) {
422 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
423 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
424}
425
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000426static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
427 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
428}
429
430static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
431 // The length of the table is stored just before the stack map (and therefore at the end of
432 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
433 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
434}
435
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800436static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
437 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
438 // pointer.
439 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
440}
441
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000442static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
443 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
444}
445
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000446static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
447 REQUIRES_SHARED(Locks::mutator_lock_) {
448 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800449 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000450 // Put all roots in `roots_data`.
451 for (uint32_t i = 0; i < length; ++i) {
452 ObjPtr<mirror::Object> object = roots->Get(i);
453 if (kIsDebugBuild) {
454 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000455 if (object->IsString()) {
456 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
457 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
458 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
459 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000460 }
461 gc_roots[i] = GcRoot<mirror::Object>(object);
462 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000463}
464
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100465static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000466 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
467 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
468 uint32_t roots = GetNumberOfRoots(data);
469 if (number_of_roots != nullptr) {
470 *number_of_roots = roots;
471 }
472 return data - ComputeRootTableSize(roots);
473}
474
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100475// Use a sentinel for marking entries in the JIT table that have been cleared.
476// This helps diagnosing in case the compiled code tries to wrongly access such
477// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700478static mirror::Class* const weak_sentinel =
479 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100480
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000481// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100482static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
483 IsMarkedVisitor* visitor,
484 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000485 REQUIRES_SHARED(Locks::mutator_lock_) {
486 // This does not need a read barrier because this is called by GC.
487 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100488 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000489 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
490 // Look at the classloader of the class to know if it has been unloaded.
491 // This does not need a read barrier because this is called by GC.
492 mirror::Object* class_loader =
493 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
494 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
495 // The class loader is live, update the entry if the class has moved.
496 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
497 // Note that new_object can be null for CMS and newly allocated objects.
498 if (new_cls != nullptr && new_cls != cls) {
499 *root_ptr = GcRoot<mirror::Class>(new_cls);
500 }
501 } else {
502 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100503 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000504 }
505 }
506}
507
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000508void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
509 MutexLock mu(Thread::Current(), lock_);
510 for (const auto& entry : method_code_map_) {
511 uint32_t number_of_roots = 0;
512 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
513 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
514 for (uint32_t i = 0; i < number_of_roots; ++i) {
515 // This does not need a read barrier because this is called by GC.
516 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100517 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000518 // entry got deleted in a previous sweep.
519 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
520 mirror::Object* new_object = visitor->IsMarked(object);
521 // We know the string is marked because it's a strongly-interned string that
522 // is always alive. The IsMarked implementation of the CMS collector returns
523 // null for newly allocated objects, but we know those haven't moved. Therefore,
524 // only update the entry if we get a different non-null string.
525 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
526 // out of the weak access/creation pause. b/32167580
527 if (new_object != nullptr && new_object != object) {
528 DCHECK(new_object->IsString());
529 roots[i] = GcRoot<mirror::Object>(new_object);
530 }
531 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100532 ProcessWeakClass(
533 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000534 }
535 }
536 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000537 // Walk over inline caches to clear entries containing unloaded classes.
538 for (ProfilingInfo* info : profiling_infos_) {
539 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
540 InlineCache* cache = &info->cache_[i];
541 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100542 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000543 }
544 }
545 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000546}
547
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100548void JitCodeCache::FreeCode(const void* code_ptr) {
549 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000550 // Notify native debugger that we are about to remove the code.
551 // It does nothing if we are not using native debugger.
David Srbeckyfb3de3d2018-01-29 16:11:49 +0000552 MutexLock mu(Thread::Current(), *Locks::native_debug_interface_lock_);
David Srbeckyc684f332018-01-19 17:38:06 +0000553 JITCodeEntry* entry = GetJITCodeEntry(reinterpret_cast<uintptr_t>(code_ptr));
554 if (entry != nullptr) {
555 DecrementJITCodeEntryRefcount(entry, reinterpret_cast<uintptr_t>(code_ptr));
556 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000557 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
558 FreeData(GetRootTable(code_ptr));
559 } // else this is a JNI stub without any data.
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100560 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100561}
562
Mingyao Yang063fc772016-08-02 11:02:54 -0700563void JitCodeCache::FreeAllMethodHeaders(
564 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
565 {
566 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700567 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
Mingyao Yang063fc772016-08-02 11:02:54 -0700568 ->RemoveDependentsWithMethodHeaders(method_headers);
569 }
570
571 // We need to remove entries in method_headers from CHA dependencies
572 // first since once we do FreeCode() below, the memory can be reused
573 // so it's possible for the same method_header to start representing
574 // different compile code.
575 MutexLock mu(Thread::Current(), lock_);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100576 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -0700577 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100578 FreeCode(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700579 }
580}
581
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100582void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800583 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700584 // We use a set to first collect all method_headers whose code need to be
585 // removed. We need to free the underlying code after we remove CHA dependencies
586 // for entries in this set. And it's more efficient to iterate through
587 // the CHA dependency map just once with an unordered_set.
588 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000589 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700590 MutexLock mu(self, lock_);
591 // We do not check if a code cache GC is in progress, as this method comes
592 // with the classlinker_classes_lock_ held, and suspending ourselves could
593 // lead to a deadlock.
594 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100595 ScopedCodeCacheWrite scc(code_map_.get());
Vladimir Marko2196c652017-11-30 16:16:07 +0000596 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
597 it->second.RemoveMethodsIn(alloc);
598 if (it->second.GetMethods().empty()) {
599 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
600 it = jni_stubs_map_.erase(it);
601 } else {
602 it->first.UpdateShorty(it->second.GetMethods().front());
603 ++it;
604 }
605 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700606 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
607 if (alloc.ContainsUnsafe(it->second)) {
608 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
609 it = method_code_map_.erase(it);
610 } else {
611 ++it;
612 }
613 }
614 }
615 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
616 if (alloc.ContainsUnsafe(it->first)) {
617 // Note that the code has already been pushed to method_headers in the loop
618 // above and is going to be removed in FreeCode() below.
619 it = osr_code_map_.erase(it);
620 } else {
621 ++it;
622 }
623 }
624 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
625 ProfilingInfo* info = *it;
626 if (alloc.ContainsUnsafe(info->GetMethod())) {
627 info->GetMethod()->SetProfilingInfo(nullptr);
628 FreeData(reinterpret_cast<uint8_t*>(info));
629 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000630 } else {
631 ++it;
632 }
633 }
634 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700635 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100636}
637
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000638bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
639 return kUseReadBarrier
640 ? self->GetWeakRefAccessEnabled()
641 : is_weak_access_enabled_.LoadSequentiallyConsistent();
642}
643
644void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
645 if (IsWeakAccessEnabled(self)) {
646 return;
647 }
648 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000649 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000650 while (!IsWeakAccessEnabled(self)) {
651 inline_cache_cond_.Wait(self);
652 }
653}
654
655void JitCodeCache::BroadcastForInlineCacheAccess() {
656 Thread* self = Thread::Current();
657 MutexLock mu(self, lock_);
658 inline_cache_cond_.Broadcast(self);
659}
660
661void JitCodeCache::AllowInlineCacheAccess() {
662 DCHECK(!kUseReadBarrier);
663 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
664 BroadcastForInlineCacheAccess();
665}
666
667void JitCodeCache::DisallowInlineCacheAccess() {
668 DCHECK(!kUseReadBarrier);
669 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
670}
671
672void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
673 Handle<mirror::ObjectArray<mirror::Class>> array) {
674 WaitUntilInlineCacheAccessible(Thread::Current());
675 // Note that we don't need to lock `lock_` here, the compiler calling
676 // this method has already ensured the inline cache will not be deleted.
677 for (size_t in_cache = 0, in_array = 0;
678 in_cache < InlineCache::kIndividualCacheSize;
679 ++in_cache) {
680 mirror::Class* object = ic.classes_[in_cache].Read();
681 if (object != nullptr) {
682 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000683 }
684 }
685}
686
Mathieu Chartierf044c222017-05-31 15:27:54 -0700687static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
688 if (was_warm) {
Orion Hodsoncfcc9cf2017-09-29 15:07:27 +0100689 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700690 }
691 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
692 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100693 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
694 // the warmup threshold is 1.
695 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
696 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700697}
698
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100699uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
700 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000701 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700702 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000703 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100704 size_t frame_size_in_bytes,
705 size_t core_spill_mask,
706 size_t fp_spill_mask,
707 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000708 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100709 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000710 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700711 Handle<mirror::ObjectArray<mirror::Object>> roots,
712 bool has_should_deoptimize_flag,
713 const ArenaSet<ArtMethod*>&
714 cha_single_implementation_list) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000715 DCHECK_NE(stack_map != nullptr, method->IsNative());
716 DCHECK(!method->IsNative() || !osr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100717 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
718 // Ensure the header ends up at expected instruction alignment.
719 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
720 size_t total_size = header_size + code_size;
721
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100722 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100723 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000724 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100725 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000726 ScopedThreadSuspension sts(self, kSuspended);
727 MutexLock mu(self, lock_);
728 WaitForPotentialCollectionToComplete(self);
729 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100730 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000731 memory = AllocateCode(total_size);
732 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000733 return nullptr;
734 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100735 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000736
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100737 std::copy(code, code + code_size, code_ptr);
738 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
739 new (method_header) OatQuickMethodHeader(
Vladimir Marko2196c652017-11-30 16:16:07 +0000740 (stack_map != nullptr) ? code_ptr - stack_map : 0u,
741 (method_info != nullptr) ? code_ptr - method_info : 0u,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000742 frame_size_in_bytes,
743 core_spill_mask,
744 fp_spill_mask,
745 code_size);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100746 // Flush caches before we remove write permission because some ARMv8 Qualcomm kernels may
747 // trigger a segfault if a page fault occurs when requesting a cache maintenance operation.
748 // This is a kernel bug that we need to work around until affected devices (e.g. Nexus 5X and
749 // 6P) stop being supported or their kernels are fixed.
750 //
751 // For reference, this behavior is caused by this commit:
752 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
753 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
754 reinterpret_cast<char*>(code_ptr + code_size));
Mingyao Yang063fc772016-08-02 11:02:54 -0700755 DCHECK(!Runtime::Current()->IsAotCompiler());
756 if (has_should_deoptimize_flag) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100757 method_header->SetHasShouldDeoptimizeFlag();
Mingyao Yang063fc772016-08-02 11:02:54 -0700758 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100759 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100760
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000761 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100762 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000763 // We need to update the entry point in the runnable state for the instrumentation.
764 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700765 // Need cha_lock_ for checking all single-implementation flags and register
766 // dependencies.
767 MutexLock cha_mu(self, *Locks::cha_lock_);
768 bool single_impl_still_valid = true;
769 for (ArtMethod* single_impl : cha_single_implementation_list) {
770 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700771 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
772 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700773 single_impl_still_valid = false;
Mathieu Chartierf044c222017-05-31 15:27:54 -0700774 ClearMethodCounter(method, /*was_warm*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700775 break;
776 }
777 }
778
779 // Discard the code if any single-implementation assumptions are now invalid.
780 if (!single_impl_still_valid) {
781 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
782 return nullptr;
783 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000784 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800785 << "Should not be using cha on debuggable apps/runs!";
786
Mingyao Yang063fc772016-08-02 11:02:54 -0700787 for (ArtMethod* single_impl : cha_single_implementation_list) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700788 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()->AddDependency(
Mingyao Yang063fc772016-08-02 11:02:54 -0700789 single_impl, method, method_header);
790 }
791
792 // The following needs to be guarded by cha_lock_ also. Otherwise it's
793 // possible that the compiled code is considered invalidated by some class linking,
794 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000795 MutexLock mu(self, lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000796 if (UNLIKELY(method->IsNative())) {
797 DCHECK(stack_map == nullptr);
798 DCHECK(roots_data == nullptr);
799 auto it = jni_stubs_map_.find(JniStubKey(method));
800 DCHECK(it != jni_stubs_map_.end())
801 << "Entry inserted in NotifyCompilationOf() should be alive.";
802 JniStubData* data = &it->second;
803 DCHECK(ContainsElement(data->GetMethods(), method))
804 << "Entry inserted in NotifyCompilationOf() should contain this method.";
805 data->SetCode(code_ptr);
806 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
807 for (ArtMethod* m : data->GetMethods()) {
808 instrum->UpdateMethodsCode(m, method_header->GetEntryPoint());
809 }
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100810 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +0000811 // Fill the root table before updating the entry point.
812 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
813 DCHECK_LE(roots_data, stack_map);
814 FillRootTable(roots_data, roots);
815 {
816 // Flush data cache, as compiled code references literals in it.
817 // We also need a TLB shootdown to act as memory barrier across cores.
818 ScopedCodeCacheWrite ccw(code_map_.get(), /* only_for_tlb_shootdown */ true);
819 FlushDataCache(reinterpret_cast<char*>(roots_data),
820 reinterpret_cast<char*>(roots_data + data_size));
821 }
822 method_code_map_.Put(code_ptr, method);
823 if (osr) {
824 number_of_osr_compilations_++;
825 osr_code_map_.Put(method, code_ptr);
826 } else {
827 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
828 method, method_header->GetEntryPoint());
829 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000830 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000831 if (collection_in_progress_) {
832 // We need to update the live bitmap if there is a GC to ensure it sees this new
833 // code.
834 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
835 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000836 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000837 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100838 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700839 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000840 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
841 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
842 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700843 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
844 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000845 histogram_code_memory_use_.AddValue(code_size);
846 if (code_size > kCodeSizeLogThreshold) {
847 LOG(INFO) << "JIT allocated "
848 << PrettySize(code_size)
849 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700850 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000851 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000852 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100853
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100854 return reinterpret_cast<uint8_t*>(method_header);
855}
856
857size_t JitCodeCache::CodeCacheSize() {
858 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000859 return CodeCacheSizeLocked();
860}
861
Orion Hodsoneced6922017-06-01 10:54:28 +0100862bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000863 // This function is used only for testing and only with non-native methods.
864 CHECK(!method->IsNative());
865
Orion Hodsoneced6922017-06-01 10:54:28 +0100866 MutexLock mu(Thread::Current(), lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +0100867
Vladimir Marko2196c652017-11-30 16:16:07 +0000868 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
869 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +0100870
871 if (!in_cache) {
872 return false;
873 }
874
Orion Hodsoneced6922017-06-01 10:54:28 +0100875 method->ClearCounter();
876 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
877 method, GetQuickToInterpreterBridge());
878 VLOG(jit)
879 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
880 << ArtMethod::PrettyMethod(method) << "@" << method
881 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
882 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
883 return true;
884}
885
Vladimir Marko2196c652017-11-30 16:16:07 +0000886bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
887 if (LIKELY(!method->IsNative())) {
888 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
889 if (info != nullptr) {
890 RemoveElement(profiling_infos_, info);
891 }
892 method->SetProfilingInfo(nullptr);
893 }
894
895 bool in_cache = false;
896 ScopedCodeCacheWrite ccw(code_map_.get());
897 if (UNLIKELY(method->IsNative())) {
898 auto it = jni_stubs_map_.find(JniStubKey(method));
899 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
900 in_cache = true;
901 if (it->second.GetMethods().empty()) {
902 if (release_memory) {
903 FreeCode(it->second.GetCode());
904 }
905 jni_stubs_map_.erase(it);
906 } else {
907 it->first.UpdateShorty(it->second.GetMethods().front());
908 }
909 }
910 } else {
911 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
912 if (it->second == method) {
913 in_cache = true;
914 if (release_memory) {
915 FreeCode(it->first);
916 }
917 it = method_code_map_.erase(it);
918 } else {
919 ++it;
920 }
921 }
922
923 auto osr_it = osr_code_map_.find(method);
924 if (osr_it != osr_code_map_.end()) {
925 osr_code_map_.erase(osr_it);
926 }
927 }
928
929 return in_cache;
930}
931
Alex Lightdba61482016-12-21 08:20:29 -0800932// This notifies the code cache that the given method has been redefined and that it should remove
933// any cached information it has on the method. All threads must be suspended before calling this
934// method. The compiled code for the method (if there is any) must not be in any threads call stack.
935void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
936 MutexLock mu(Thread::Current(), lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000937 RemoveMethodLocked(method, /* release_memory */ true);
Alex Lightdba61482016-12-21 08:20:29 -0800938}
939
940// This invalidates old_method. Once this function returns one can no longer use old_method to
941// execute code unless it is fixed up. This fixup will happen later in the process of installing a
942// class redefinition.
943// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
944// shouldn't be used since it is no longer logically in the jit code cache.
945// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
946void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000947 MutexLock mu(Thread::Current(), lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +0000948 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000949 // Update methods in jni_stubs_map_.
950 for (auto& entry : jni_stubs_map_) {
951 JniStubData& data = entry.second;
952 data.MoveObsoleteMethod(old_method, new_method);
953 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000954 return;
955 }
Alex Lightdba61482016-12-21 08:20:29 -0800956 // Update ProfilingInfo to the new one and remove it from the old_method.
957 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
958 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
959 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
960 old_method->SetProfilingInfo(nullptr);
961 // Since the JIT should be paused and all threads suspended by the time this is called these
962 // checks should always pass.
963 DCHECK(!info->IsInUseByCompiler());
964 new_method->SetProfilingInfo(info);
965 info->method_ = new_method;
966 }
967 // Update method_code_map_ to point to the new method.
968 for (auto& it : method_code_map_) {
969 if (it.second == old_method) {
970 it.second = new_method;
971 }
972 }
973 // Update osr_code_map_ to point to the new method.
974 auto code_map = osr_code_map_.find(old_method);
975 if (code_map != osr_code_map_.end()) {
976 osr_code_map_.Put(new_method, code_map->second);
977 osr_code_map_.erase(old_method);
978 }
979}
980
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000981size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000982 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100983}
984
985size_t JitCodeCache::DataCacheSize() {
986 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000987 return DataCacheSizeLocked();
988}
989
990size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000991 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800992}
993
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000994void JitCodeCache::ClearData(Thread* self,
995 uint8_t* stack_map_data,
996 uint8_t* roots_data) {
997 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000998 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000999 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001000}
1001
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001002size_t JitCodeCache::ReserveData(Thread* self,
1003 size_t stack_map_size,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001004 size_t method_info_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001005 size_t number_of_roots,
1006 ArtMethod* method,
1007 uint8_t** stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001008 uint8_t** method_info_data,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001009 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001010 size_t table_size = ComputeRootTableSize(number_of_roots);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001011 size_t size = RoundUp(stack_map_size + method_info_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001012 uint8_t* result = nullptr;
1013
1014 {
1015 ScopedThreadSuspension sts(self, kSuspended);
1016 MutexLock mu(self, lock_);
1017 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001018 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001019 }
1020
1021 if (result == nullptr) {
1022 // Retry.
1023 GarbageCollectCache(self);
1024 ScopedThreadSuspension sts(self, kSuspended);
1025 MutexLock mu(self, lock_);
1026 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001027 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001028 }
1029
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001030 MutexLock mu(self, lock_);
1031 histogram_stack_map_memory_use_.AddValue(size);
1032 if (size > kStackMapSizeLogThreshold) {
1033 LOG(INFO) << "JIT allocated "
1034 << PrettySize(size)
1035 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001036 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001037 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001038 if (result != nullptr) {
1039 *roots_data = result;
1040 *stack_map_data = result + table_size;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001041 *method_info_data = *stack_map_data + stack_map_size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001042 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001043 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001044 } else {
1045 *roots_data = nullptr;
1046 *stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001047 *method_info_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001048 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001049 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001050}
1051
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001052class MarkCodeVisitor FINAL : public StackVisitor {
1053 public:
1054 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
1055 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
1056 code_cache_(code_cache_in),
1057 bitmap_(code_cache_->GetLiveBitmap()) {}
1058
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001059 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001060 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
1061 if (method_header == nullptr) {
1062 return true;
1063 }
1064 const void* code = method_header->GetCode();
1065 if (code_cache_->ContainsPc(code)) {
1066 // Use the atomic set version, as multiple threads are executing this code.
1067 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1068 }
1069 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001070 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001071
1072 private:
1073 JitCodeCache* const code_cache_;
1074 CodeCacheBitmap* const bitmap_;
1075};
1076
1077class MarkCodeClosure FINAL : public Closure {
1078 public:
1079 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
1080 : code_cache_(code_cache), barrier_(barrier) {}
1081
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001082 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001083 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001084 DCHECK(thread == Thread::Current() || thread->IsSuspended());
1085 MarkCodeVisitor visitor(thread, code_cache_);
1086 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001087 if (kIsDebugBuild) {
1088 // The stack walking code queries the side instrumentation stack if it
1089 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1090 // must have been seen. We sanity check this below.
1091 for (const instrumentation::InstrumentationStackFrame& frame
1092 : *thread->GetInstrumentationStack()) {
1093 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1094 // its stack frame, it is not the method owning return_pc_. We just pass null to
1095 // LookupMethodHeader: the method is only checked against in debug builds.
1096 OatQuickMethodHeader* method_header =
Vladimir Marko2196c652017-11-30 16:16:07 +00001097 code_cache_->LookupMethodHeader(frame.return_pc_, /* method */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001098 if (method_header != nullptr) {
1099 const void* code = method_header->GetCode();
1100 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
1101 }
1102 }
1103 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001104 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001105 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001106
1107 private:
1108 JitCodeCache* const code_cache_;
1109 Barrier* const barrier_;
1110};
1111
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001112void JitCodeCache::NotifyCollectionDone(Thread* self) {
1113 collection_in_progress_ = false;
1114 lock_cond_.Broadcast(self);
1115}
1116
1117void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
1118 size_t per_space_footprint = new_footprint / 2;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001119 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001120 DCHECK_EQ(per_space_footprint * 2, new_footprint);
1121 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
1122 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001123 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001124 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
1125 }
1126}
1127
1128bool JitCodeCache::IncreaseCodeCacheCapacity() {
1129 if (current_capacity_ == max_capacity_) {
1130 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001131 }
1132
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001133 // Double the capacity if we're below 1MB, or increase it by 1MB if
1134 // we're above.
1135 if (current_capacity_ < 1 * MB) {
1136 current_capacity_ *= 2;
1137 } else {
1138 current_capacity_ += 1 * MB;
1139 }
1140 if (current_capacity_ > max_capacity_) {
1141 current_capacity_ = max_capacity_;
1142 }
1143
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001144 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001145
1146 SetFootprintLimit(current_capacity_);
1147
1148 return true;
1149}
1150
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001151void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1152 Barrier barrier(0);
1153 size_t threads_running_checkpoint = 0;
1154 MarkCodeClosure closure(this, &barrier);
1155 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1156 // Now that we have run our checkpoint, move to a suspended state and wait
1157 // for other threads to run the checkpoint.
1158 ScopedThreadSuspension sts(self, kSuspended);
1159 if (threads_running_checkpoint != 0) {
1160 barrier.Increment(self, threads_running_checkpoint);
1161 }
1162}
1163
Nicolas Geoffray35122442016-03-02 12:05:30 +00001164bool JitCodeCache::ShouldDoFullCollection() {
1165 if (current_capacity_ == max_capacity_) {
1166 // Always do a full collection when the code cache is full.
1167 return true;
1168 } else if (current_capacity_ < kReservedCapacity) {
1169 // Always do partial collection when the code cache size is below the reserved
1170 // capacity.
1171 return false;
1172 } else if (last_collection_increased_code_cache_) {
1173 // This time do a full collection.
1174 return true;
1175 } else {
1176 // This time do a partial collection.
1177 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001178 }
1179}
1180
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001181void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001182 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001183 if (!garbage_collect_code_) {
1184 MutexLock mu(self, lock_);
1185 IncreaseCodeCacheCapacity();
1186 return;
1187 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001188
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001189 // Wait for an existing collection, or let everyone know we are starting one.
1190 {
1191 ScopedThreadSuspension sts(self, kSuspended);
1192 MutexLock mu(self, lock_);
1193 if (WaitForPotentialCollectionToComplete(self)) {
1194 return;
1195 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001196 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001197 live_bitmap_.reset(CodeCacheBitmap::Create(
1198 "code-cache-bitmap",
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001199 reinterpret_cast<uintptr_t>(code_map_->Begin()),
1200 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001201 collection_in_progress_ = true;
1202 }
1203 }
1204
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001205 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001206 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001207 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001208
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001209 bool do_full_collection = false;
1210 {
1211 MutexLock mu(self, lock_);
1212 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001213 }
1214
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001215 VLOG(jit) << "Do "
1216 << (do_full_collection ? "full" : "partial")
1217 << " code cache collection, code="
1218 << PrettySize(CodeCacheSize())
1219 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001220
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001221 DoCollection(self, /* collect_profiling_info */ do_full_collection);
1222
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001223 VLOG(jit) << "After code cache collection, code="
1224 << PrettySize(CodeCacheSize())
1225 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001226
1227 {
1228 MutexLock mu(self, lock_);
1229
1230 // Increase the code cache only when we do partial collections.
1231 // TODO: base this strategy on how full the code cache is?
1232 if (do_full_collection) {
1233 last_collection_increased_code_cache_ = false;
1234 } else {
1235 last_collection_increased_code_cache_ = true;
1236 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001237 }
1238
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001239 bool next_collection_will_be_full = ShouldDoFullCollection();
1240
1241 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001242 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001243 // Save the entry point of methods we have compiled, and update the entry
1244 // point of those methods to the interpreter. If the method is invoked, the
1245 // interpreter will update its entry point to the compiled code and call it.
1246 for (ProfilingInfo* info : profiling_infos_) {
1247 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1248 if (ContainsPc(entry_point)) {
1249 info->SetSavedEntryPoint(entry_point);
Vladimir Marko2196c652017-11-30 16:16:07 +00001250 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001251 // class of the method. We may be concurrently running a GC which makes accessing
1252 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1253 // checked that the current entry point is JIT compiled code.
1254 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001255 }
1256 }
1257
1258 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Vladimir Marko2196c652017-11-30 16:16:07 +00001259
1260 // Change entry points of native methods back to the GenericJNI entrypoint.
1261 for (const auto& entry : jni_stubs_map_) {
1262 const JniStubData& data = entry.second;
1263 if (!data.IsCompiled()) {
1264 continue;
1265 }
1266 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1267 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1268 const OatQuickMethodHeader* method_header =
1269 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1270 for (ArtMethod* method : data.GetMethods()) {
1271 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1272 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1273 method->SetCounter(new_counter);
1274 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1275 }
1276 }
1277 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001278 }
1279 live_bitmap_.reset(nullptr);
1280 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001281 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001282 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001283 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001284}
1285
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001286void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001287 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001288 std::unordered_set<OatQuickMethodHeader*> method_headers;
1289 {
1290 MutexLock mu(self, lock_);
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001291 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -07001292 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001293 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1294 JniStubData* data = &it->second;
1295 if (!data->IsCompiled() || GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
1296 ++it;
1297 } else {
1298 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1299 it = jni_stubs_map_.erase(it);
1300 }
1301 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001302 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1303 const void* code_ptr = it->first;
1304 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1305 if (GetLiveBitmap()->Test(allocation)) {
1306 ++it;
1307 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +00001308 method_headers.insert(OatQuickMethodHeader::FromCodePointer(code_ptr));
Mingyao Yang063fc772016-08-02 11:02:54 -07001309 it = method_code_map_.erase(it);
1310 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001311 }
1312 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001313 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001314}
1315
1316void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001317 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001318 {
1319 MutexLock mu(self, lock_);
1320 if (collect_profiling_info) {
1321 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1322 // Also remove the saved entry point from the ProfilingInfo objects.
1323 for (ProfilingInfo* info : profiling_infos_) {
1324 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001325 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001326 info->GetMethod()->SetProfilingInfo(nullptr);
1327 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001328
1329 if (info->GetSavedEntryPoint() != nullptr) {
1330 info->SetSavedEntryPoint(nullptr);
1331 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001332 // give it a chance to be hot again.
1333 ClearMethodCounter(info->GetMethod(), /*was_warm*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001334 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001335 }
1336 } else if (kIsDebugBuild) {
1337 // Sanity check that the profiling infos do not have a dangling entry point.
1338 for (ProfilingInfo* info : profiling_infos_) {
1339 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001340 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001341 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001342
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001343 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1344 // an entry point is either:
1345 // - an osr compiled code, that will be removed if not in a thread call stack.
1346 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001347 for (const auto& entry : jni_stubs_map_) {
1348 const JniStubData& data = entry.second;
1349 const void* code_ptr = data.GetCode();
1350 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1351 for (ArtMethod* method : data.GetMethods()) {
1352 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1353 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1354 break;
1355 }
1356 }
1357 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001358 for (const auto& it : method_code_map_) {
1359 ArtMethod* method = it.second;
1360 const void* code_ptr = it.first;
1361 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1362 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1363 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1364 }
1365 }
1366
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001367 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001368 // on thread stacks).
1369 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001370 }
1371
1372 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001373 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001374
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001375 // At this point, mutator threads are still running, and entrypoints of methods can
1376 // change. We do know they cannot change to a code cache entry that is not marked,
1377 // therefore we can safely remove those entries.
1378 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001379
Nicolas Geoffray35122442016-03-02 12:05:30 +00001380 if (collect_profiling_info) {
1381 MutexLock mu(self, lock_);
1382 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001383 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001384 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001385 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001386 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1387 // that the compiled code would not get revived. As mutator threads run concurrently,
1388 // they may have revived the compiled code, and now we are in the situation where
1389 // a method has compiled code but no ProfilingInfo.
1390 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1391 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001392 if (ContainsPc(ptr) &&
1393 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001394 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001395 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001396 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001397 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001398 return true;
1399 }
1400 return false;
1401 });
1402 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001403 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001404 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001405}
1406
Nicolas Geoffray35122442016-03-02 12:05:30 +00001407bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001408 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001409 // Check that methods we have compiled do have a ProfilingInfo object. We would
1410 // have memory leaks of compiled code otherwise.
1411 for (const auto& it : method_code_map_) {
1412 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001413 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001414 const void* code_ptr = it.first;
1415 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1416 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1417 // If the code is not dead, then we have a problem. Note that this can even
1418 // happen just after a collection, as mutator threads are running in parallel
1419 // and could deoptimize an existing compiled code.
1420 return false;
1421 }
1422 }
1423 }
1424 return true;
1425}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001426
1427OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001428 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1429 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001430 // On Thumb-2, the pc is offset by one.
1431 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001432 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001433 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1434 return nullptr;
1435 }
1436
Vladimir Marko2196c652017-11-30 16:16:07 +00001437 if (!kIsDebugBuild) {
1438 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1439 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001440 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001441
Vladimir Marko2196c652017-11-30 16:16:07 +00001442 MutexLock mu(Thread::Current(), lock_);
1443 OatQuickMethodHeader* method_header = nullptr;
1444 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1445 if (method != nullptr && UNLIKELY(method->IsNative())) {
1446 auto it = jni_stubs_map_.find(JniStubKey(method));
1447 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1448 return nullptr;
1449 }
1450 const void* code_ptr = it->second.GetCode();
1451 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1452 if (!method_header->Contains(pc)) {
1453 return nullptr;
1454 }
1455 } else {
1456 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1457 if (it != method_code_map_.begin()) {
1458 --it;
1459 const void* code_ptr = it->first;
1460 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1461 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1462 found_method = it->second;
1463 }
1464 }
1465 if (method_header == nullptr && method == nullptr) {
1466 // Scan all compiled JNI stubs as well. This slow search is used only
1467 // for checks in debug build, for release builds the `method` is not null.
1468 for (auto&& entry : jni_stubs_map_) {
1469 const JniStubData& data = entry.second;
1470 if (data.IsCompiled() &&
1471 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1472 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1473 }
1474 }
1475 }
1476 if (method_header == nullptr) {
1477 return nullptr;
1478 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001479 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001480
1481 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001482 // When we are walking the stack to redefine classes and creating obsolete methods it is
1483 // possible that we might have updated the method_code_map by making this method obsolete in a
1484 // previous frame. Therefore we should just check that the non-obsolete version of this method
1485 // is the one we expect. We change to the non-obsolete versions in the error message since the
1486 // obsolete version of the method might not be fully initialized yet. This situation can only
1487 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
Andreas Gampe06c42a52017-07-26 14:17:14 -07001488 // method and it->second should be identical. (See openjdkjvmti/ti_redefine.cc for more
Alex Light1ebe4fe2017-01-30 14:57:11 -08001489 // information.)
Vladimir Marko2196c652017-11-30 16:16:07 +00001490 DCHECK_EQ(found_method->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
Alex Light1ebe4fe2017-01-30 14:57:11 -08001491 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
Vladimir Marko2196c652017-11-30 16:16:07 +00001492 << ArtMethod::PrettyMethod(found_method->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001493 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001494 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001495 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001496}
1497
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001498OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1499 MutexLock mu(Thread::Current(), lock_);
1500 auto it = osr_code_map_.find(method);
1501 if (it == osr_code_map_.end()) {
1502 return nullptr;
1503 }
1504 return OatQuickMethodHeader::FromCodePointer(it->second);
1505}
1506
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001507ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1508 ArtMethod* method,
1509 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001510 bool retry_allocation)
1511 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1512 NO_THREAD_SAFETY_ANALYSIS {
1513 ProfilingInfo* info = nullptr;
1514 if (!retry_allocation) {
1515 // If we are allocating for the interpreter, just try to lock, to avoid
1516 // lock contention with the JIT.
1517 if (lock_.ExclusiveTryLock(self)) {
1518 info = AddProfilingInfoInternal(self, method, entries);
1519 lock_.ExclusiveUnlock(self);
1520 }
1521 } else {
1522 {
1523 MutexLock mu(self, lock_);
1524 info = AddProfilingInfoInternal(self, method, entries);
1525 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001526
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001527 if (info == nullptr) {
1528 GarbageCollectCache(self);
1529 MutexLock mu(self, lock_);
1530 info = AddProfilingInfoInternal(self, method, entries);
1531 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001532 }
1533 return info;
1534}
1535
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001536ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001537 ArtMethod* method,
1538 const std::vector<uint32_t>& entries) {
1539 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001540 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001541 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001542
1543 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001544 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001545 if (info != nullptr) {
1546 return info;
1547 }
1548
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001549 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001550 if (data == nullptr) {
1551 return nullptr;
1552 }
1553 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001554
1555 // Make sure other threads see the data in the profiling info object before the
1556 // store in the ArtMethod's ProfilingInfo pointer.
1557 QuasiAtomic::ThreadFenceRelease();
1558
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001559 method->SetProfilingInfo(info);
1560 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001561 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001562 return info;
1563}
1564
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001565// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1566// is already held.
1567void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1568 if (code_mspace_ == mspace) {
1569 size_t result = code_end_;
1570 code_end_ += increment;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001571 return reinterpret_cast<void*>(result + code_map_->Begin());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001572 } else {
1573 DCHECK_EQ(data_mspace_, mspace);
1574 size_t result = data_end_;
1575 data_end_ += increment;
1576 return reinterpret_cast<void*>(result + data_map_->Begin());
1577 }
1578}
1579
Calin Juravle99629622016-04-19 16:33:46 +01001580void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001581 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001582 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001583 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001584 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001585 for (const ProfilingInfo* info : profiling_infos_) {
1586 ArtMethod* method = info->GetMethod();
1587 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001588 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1589 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001590 // Skip dex files which are not profiled.
1591 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001592 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001593 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001594
1595 // If the method didn't reach the compilation threshold don't save the inline caches.
1596 // They might be incomplete and cause unnecessary deoptimizations.
1597 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1598 if (method->GetCounter() < jit_compile_threshold) {
1599 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001600 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001601 continue;
1602 }
1603
Calin Juravle940eb0c2017-01-30 19:30:44 -08001604 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001605 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001606 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001607 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001608 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001609 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1610 mirror::Class* cls = cache.classes_[k].Read();
1611 if (cls == nullptr) {
1612 break;
1613 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001614
Calin Juravle13439f02017-02-21 01:17:21 -08001615 // Check if the receiver is in the boot class path or if it's in the
1616 // same class loader as the caller. If not, skip it, as there is not
1617 // much we can do during AOT.
1618 if (!cls->IsBootStrapClassLoaded() &&
1619 caller->GetClassLoader() != cls->GetClassLoader()) {
1620 is_missing_types = true;
1621 continue;
1622 }
1623
Calin Juravle4ca70a32017-02-21 16:22:24 -08001624 const DexFile* class_dex_file = nullptr;
1625 dex::TypeIndex type_index;
1626
1627 if (cls->GetDexCache() == nullptr) {
1628 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001629 // Make a best effort to find the type index in the method's dex file.
1630 // We could search all open dex files but that might turn expensive
1631 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001632 class_dex_file = dex_file;
1633 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1634 } else {
1635 class_dex_file = &(cls->GetDexFile());
1636 type_index = cls->GetDexTypeIndex();
1637 }
1638 if (!type_index.IsValid()) {
1639 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001640 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001641 continue;
1642 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001643 if (ContainsElement(dex_base_locations,
1644 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001645 // Only consider classes from the same apk (including multidex).
1646 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001647 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001648 } else {
1649 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001650 }
1651 }
1652 if (!profile_classes.empty()) {
1653 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001654 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001655 }
1656 }
1657 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001658 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001659 }
1660}
1661
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001662uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1663 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001664}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001665
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001666bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1667 MutexLock mu(Thread::Current(), lock_);
1668 return osr_code_map_.find(method) != osr_code_map_.end();
1669}
1670
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001671bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1672 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001673 return false;
1674 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001675
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001676 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001677 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1678 return false;
1679 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001680
Vladimir Marko2196c652017-11-30 16:16:07 +00001681 if (UNLIKELY(method->IsNative())) {
1682 JniStubKey key(method);
1683 auto it = jni_stubs_map_.find(key);
1684 bool new_compilation = false;
1685 if (it == jni_stubs_map_.end()) {
1686 // Create a new entry to mark the stub as being compiled.
1687 it = jni_stubs_map_.Put(key, JniStubData{});
1688 new_compilation = true;
1689 }
1690 JniStubData* data = &it->second;
1691 data->AddMethod(method);
1692 if (data->IsCompiled()) {
1693 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1694 const void* entrypoint = method_header->GetEntryPoint();
1695 // Update also entrypoints of other methods held by the JniStubData.
1696 // We could simply update the entrypoint of `method` but if the last JIT GC has
1697 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1698 // as well change them back as this stub shall not be collected anyway and this
1699 // can avoid a few expensive GenericJNI calls.
1700 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1701 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +00001702 // Call the dedicated method instead of the more generic UpdateMethodsCode, because
1703 // `m` might be in the process of being deleted.
1704 instrumentation->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
Vladimir Marko2196c652017-11-30 16:16:07 +00001705 }
1706 if (collection_in_progress_) {
1707 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1708 }
1709 }
1710 return new_compilation;
1711 } else {
1712 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1713 if (info == nullptr) {
1714 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1715 // Because the counter is not atomic, there are some rare cases where we may not hit the
1716 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
1717 ClearMethodCounter(method, /*was_warm*/ false);
1718 return false;
1719 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001720
Vladimir Marko2196c652017-11-30 16:16:07 +00001721 if (info->IsMethodBeingCompiled(osr)) {
1722 return false;
1723 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001724
Vladimir Marko2196c652017-11-30 16:16:07 +00001725 info->SetIsMethodBeingCompiled(true, osr);
1726 return true;
1727 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001728}
1729
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001730ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001731 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001732 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001733 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001734 if (!info->IncrementInlineUse()) {
1735 // Overflow of inlining uses, just bail.
1736 return nullptr;
1737 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001738 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001739 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001740}
1741
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001742void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001743 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001744 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001745 DCHECK(info != nullptr);
1746 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001747}
1748
Vladimir Marko2196c652017-11-30 16:16:07 +00001749void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
1750 DCHECK_EQ(Thread::Current(), self);
1751 MutexLock mu(self, lock_);
1752 if (UNLIKELY(method->IsNative())) {
1753 auto it = jni_stubs_map_.find(JniStubKey(method));
1754 DCHECK(it != jni_stubs_map_.end());
1755 JniStubData* data = &it->second;
1756 DCHECK(ContainsElement(data->GetMethods(), method));
1757 if (UNLIKELY(!data->IsCompiled())) {
1758 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1759 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
1760 } // else CommitCodeInternal() updated entrypoints of all methods in the JniStubData.
1761 } else {
1762 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1763 DCHECK(info->IsMethodBeingCompiled(osr));
1764 info->SetIsMethodBeingCompiled(false, osr);
1765 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001766}
1767
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001768size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1769 MutexLock mu(Thread::Current(), lock_);
1770 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1771}
1772
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001773void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1774 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001775 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07001776 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001777 if ((profiling_info != nullptr) &&
1778 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1779 // Prevent future uses of the compiled code.
1780 profiling_info->SetSavedEntryPoint(nullptr);
1781 }
1782
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001783 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001784 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001785 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001786 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1787 method, GetQuickToInterpreterBridge());
Mathieu Chartierf044c222017-05-31 15:27:54 -07001788 ClearMethodCounter(method, /*was_warm*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001789 } else {
1790 MutexLock mu(Thread::Current(), lock_);
1791 auto it = osr_code_map_.find(method);
1792 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1793 // Remove the OSR method, to avoid using it again.
1794 osr_code_map_.erase(it);
1795 }
1796 }
1797}
1798
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001799uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1800 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1801 uint8_t* result = reinterpret_cast<uint8_t*>(
1802 mspace_memalign(code_mspace_, alignment, code_size));
1803 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1804 // Ensure the header ends up at expected instruction alignment.
1805 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1806 used_memory_for_code_ += mspace_usable_size(result);
1807 return result;
1808}
1809
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001810void JitCodeCache::FreeCode(uint8_t* code) {
1811 used_memory_for_code_ -= mspace_usable_size(code);
1812 mspace_free(code_mspace_, code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001813}
1814
1815uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1816 void* result = mspace_malloc(data_mspace_, data_size);
1817 used_memory_for_data_ += mspace_usable_size(result);
1818 return reinterpret_cast<uint8_t*>(result);
1819}
1820
1821void JitCodeCache::FreeData(uint8_t* data) {
1822 used_memory_for_data_ -= mspace_usable_size(data);
1823 mspace_free(data_mspace_, data);
1824}
1825
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001826void JitCodeCache::Dump(std::ostream& os) {
1827 MutexLock mu(Thread::Current(), lock_);
David Srbeckyfb3de3d2018-01-29 16:11:49 +00001828 MutexLock mu2(Thread::Current(), *Locks::native_debug_interface_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001829 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1830 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
David Srbeckyc9e02082018-01-24 16:44:02 +00001831 << "Current JIT mini-debug-info size: " << PrettySize(GetJITCodeEntryMemUsage()) << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001832 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00001833 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001834 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1835 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1836 << "Total number of JIT compilations for on stack replacement: "
1837 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001838 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001839 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1840 histogram_code_memory_use_.PrintMemoryUse(os);
1841 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001842}
1843
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001844} // namespace jit
1845} // namespace art