blob: b92affa26eb983d5e23d895757d3df2fe448d99e [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 Gampef0f3c592018-06-26 13:28:00 -070024#include "base/histogram-inl.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080025#include "base/logging.h" // For VLOG.
David Sehr79e26072018-04-06 17:58:50 -070026#include "base/mem_map.h"
David Sehrc431b9d2018-03-02 12:01:51 -080027#include "base/quasi_atomic.h"
Calin Juravle66f55232015-12-08 15:09:10 +000028#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080029#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010030#include "base/time_utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070031#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000032#include "debugger_interface.h"
David Sehr9e734c72018-01-04 17:56:19 -080033#include "dex/dex_file_loader.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070034#include "dex/method_reference.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010035#include "entrypoints/runtime_asm_entrypoints.h"
36#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010037#include "gc/scoped_gc_critical_section.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000038#include "handle.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070039#include "instrumentation.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070040#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000041#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000042#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010043#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080044#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070045#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070046#include "object_callbacks.h"
David Sehr82d046e2018-04-23 08:14:19 -070047#include "profile/profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070048#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070049#include "stack.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000050#include "thread-current-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010051#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080052
53namespace art {
54namespace jit {
55
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010056static constexpr int kProtData = PROT_READ | PROT_WRITE;
57static constexpr int kProtCode = PROT_READ | PROT_EXEC;
58
Nicolas Geoffray933330a2016-03-16 14:20:06 +000059static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
60static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
61
Vladimir Marko2196c652017-11-30 16:16:07 +000062class JitCodeCache::JniStubKey {
63 public:
64 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
65 : shorty_(method->GetShorty()),
66 is_static_(method->IsStatic()),
67 is_fast_native_(method->IsFastNative()),
68 is_critical_native_(method->IsCriticalNative()),
69 is_synchronized_(method->IsSynchronized()) {
70 DCHECK(!(is_fast_native_ && is_critical_native_));
71 }
72
73 bool operator<(const JniStubKey& rhs) const {
74 if (is_static_ != rhs.is_static_) {
75 return rhs.is_static_;
76 }
77 if (is_synchronized_ != rhs.is_synchronized_) {
78 return rhs.is_synchronized_;
79 }
80 if (is_fast_native_ != rhs.is_fast_native_) {
81 return rhs.is_fast_native_;
82 }
83 if (is_critical_native_ != rhs.is_critical_native_) {
84 return rhs.is_critical_native_;
85 }
86 return strcmp(shorty_, rhs.shorty_) < 0;
87 }
88
89 // Update the shorty to point to another method's shorty. Call this function when removing
90 // the method that references the old shorty from JniCodeData and not removing the entire
91 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
92 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
93 const char* shorty = method->GetShorty();
94 DCHECK_STREQ(shorty_, shorty);
95 shorty_ = shorty;
96 }
97
98 private:
99 // The shorty points to a DexFile data and may need to change
100 // to point to the same shorty in a different DexFile.
101 mutable const char* shorty_;
102
103 const bool is_static_;
104 const bool is_fast_native_;
105 const bool is_critical_native_;
106 const bool is_synchronized_;
107};
108
109class JitCodeCache::JniStubData {
110 public:
111 JniStubData() : code_(nullptr), methods_() {}
112
113 void SetCode(const void* code) {
114 DCHECK(code != nullptr);
115 code_ = code;
116 }
117
118 const void* GetCode() const {
119 return code_;
120 }
121
122 bool IsCompiled() const {
123 return GetCode() != nullptr;
124 }
125
126 void AddMethod(ArtMethod* method) {
127 if (!ContainsElement(methods_, method)) {
128 methods_.push_back(method);
129 }
130 }
131
132 const std::vector<ArtMethod*>& GetMethods() const {
133 return methods_;
134 }
135
136 void RemoveMethodsIn(const LinearAlloc& alloc) {
137 auto kept_end = std::remove_if(
138 methods_.begin(),
139 methods_.end(),
140 [&alloc](ArtMethod* method) { return alloc.ContainsUnsafe(method); });
141 methods_.erase(kept_end, methods_.end());
142 }
143
144 bool RemoveMethod(ArtMethod* method) {
145 auto it = std::find(methods_.begin(), methods_.end(), method);
146 if (it != methods_.end()) {
147 methods_.erase(it);
148 return true;
149 } else {
150 return false;
151 }
152 }
153
154 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
155 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
156 }
157
158 private:
159 const void* code_;
160 std::vector<ArtMethod*> methods_;
161};
162
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000163JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
164 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000165 bool generate_debug_info,
Calin Juravle016fcbe22018-05-03 19:47:35 -0700166 bool used_only_for_profile_data,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000167 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800168 ScopedTrace trace(__PRETTY_FUNCTION__);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100169 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000170
David Sehrd1dbb742017-07-17 11:20:38 -0700171 // Generating debug information is for using the Linux perf tool on
172 // host which does not work with ashmem.
Steve Austin882ed6b2018-06-08 11:40:38 -0700173 // Also, targets linux and fuchsia do not support ashmem.
174 bool use_ashmem = !generate_debug_info && !kIsTargetLinux && !kIsTargetFuchsia;
David Sehrd1dbb742017-07-17 11:20:38 -0700175
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000176 // With 'perf', we want a 1-1 mapping between an address and a method.
Alex Light2d441b12018-06-08 15:33:21 -0700177 // We aren't able to keep method pointers live during the instrumentation method entry trampoline
178 // so we will just disable jit-gc if we are doing that.
179 bool garbage_collect_code = !generate_debug_info &&
180 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled();
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000181
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000182 // We need to have 32 bit offsets from method headers in code cache which point to things
183 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
184 // Ensure we're below 1 GB to be safe.
185 if (max_capacity > 1 * GB) {
186 std::ostringstream oss;
187 oss << "Maxium code cache capacity is limited to 1 GB, "
188 << PrettySize(max_capacity) << " is too big";
189 *error_msg = oss.str();
190 return nullptr;
191 }
192
Calin Juravle016fcbe22018-05-03 19:47:35 -0700193 // Decide how we should map the code and data sections.
194 // If we use the code cache just for profiling we do not need to map the code section as
195 // executable.
196 // NOTE 1: this is yet another workaround to bypass strict SElinux policies in order to be able
197 // to profile system server.
198 // NOTE 2: We could just not create the code section at all but we will need to
199 // special case too many cases.
200 int memmap_flags_prot_code = used_only_for_profile_data ? (kProtCode & ~PROT_EXEC) : kProtCode;
201
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800202 std::string error_str;
203 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000204 // Map in low 4gb to simplify accessing root tables for x86_64.
205 // We could do PC-relative addressing to avoid this problem, but that
206 // would require reserving code and data area before submitting, which
207 // means more windows for the code memory to be RWX.
Andreas Gampee4deaf32017-06-09 15:27:15 -0700208 std::unique_ptr<MemMap> data_map(MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000209 "data-code-cache", nullptr,
210 max_capacity,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700211 kProtData,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000212 /* low_4gb */ true,
213 /* reuse */ false,
214 &error_str,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700215 use_ashmem));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100216 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800217 std::ostringstream oss;
Andreas Gampee4deaf32017-06-09 15:27:15 -0700218 oss << "Failed to create read write cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800219 *error_msg = oss.str();
220 return nullptr;
221 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100222
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100223 // Align both capacities to page size, as that's the unit mspaces use.
224 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
225 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100226
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100227 // Data cache is 1 / 2 of the map.
228 // TODO: Make this variable?
229 size_t data_size = max_capacity / 2;
230 size_t code_size = max_capacity - data_size;
231 DCHECK_EQ(code_size + data_size, max_capacity);
232 uint8_t* divider = data_map->Begin() + data_size;
David Sehrd1dbb742017-07-17 11:20:38 -0700233
Calin Juravle016fcbe22018-05-03 19:47:35 -0700234 MemMap* code_map = data_map->RemapAtEnd(
235 divider,
236 "jit-code-cache",
237 memmap_flags_prot_code | PROT_WRITE,
238 &error_str, use_ashmem);
David Sehrd1dbb742017-07-17 11:20:38 -0700239 if (code_map == nullptr) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100240 std::ostringstream oss;
241 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
242 *error_msg = oss.str();
David Sehrd1dbb742017-07-17 11:20:38 -0700243 return nullptr;
244 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100245 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000246 data_size = initial_capacity / 2;
247 code_size = initial_capacity - data_size;
248 DCHECK_EQ(code_size + data_size, initial_capacity);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100249 return new JitCodeCache(
Calin Juravle016fcbe22018-05-03 19:47:35 -0700250 code_map,
251 data_map.release(),
252 code_size,
253 data_size,
254 max_capacity,
255 garbage_collect_code,
256 memmap_flags_prot_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800257}
258
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100259JitCodeCache::JitCodeCache(MemMap* code_map,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000260 MemMap* data_map,
261 size_t initial_code_capacity,
262 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000263 size_t max_capacity,
Calin Juravle016fcbe22018-05-03 19:47:35 -0700264 bool garbage_collect_code,
265 int memmap_flags_prot_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100266 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000267 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100268 collection_in_progress_(false),
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100269 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000270 data_map_(data_map),
271 max_capacity_(max_capacity),
272 current_capacity_(initial_code_capacity + initial_data_capacity),
273 code_end_(initial_code_capacity),
274 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000275 last_collection_increased_code_cache_(false),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000276 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000277 used_memory_for_data_(0),
278 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000279 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000280 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000281 number_of_collections_(0),
282 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
283 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000284 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
285 is_weak_access_enabled_(true),
Calin Juravle016fcbe22018-05-03 19:47:35 -0700286 inline_cache_cond_("Jit inline cache condition variable", lock_),
287 memmap_flags_prot_code_(memmap_flags_prot_code) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100288
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000289 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100290 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000291 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100292
293 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
294 PLOG(FATAL) << "create_mspace_with_base failed";
295 }
296
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000297 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100298
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700299 CheckedCall(mprotect,
300 "mprotect jit code cache",
301 code_map_->Begin(),
302 code_map_->Size(),
Calin Juravle016fcbe22018-05-03 19:47:35 -0700303 memmap_flags_prot_code_);
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700304 CheckedCall(mprotect,
305 "mprotect jit data cache",
306 data_map_->Begin(),
307 data_map_->Size(),
308 kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100309
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000310 VLOG(jit) << "Created jit code cache: initial data size="
311 << PrettySize(initial_data_capacity)
312 << ", initial code size="
313 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800314}
315
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000316JitCodeCache::~JitCodeCache() {}
317
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100318bool JitCodeCache::ContainsPc(const void* ptr) const {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100319 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800320}
321
Alex Light2d441b12018-06-08 15:33:21 -0700322bool JitCodeCache::WillExecuteJitCode(ArtMethod* method) {
323 ScopedObjectAccess soa(art::Thread::Current());
324 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
325 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
326 return true;
327 } else if (method->GetEntryPointFromQuickCompiledCode() == GetQuickInstrumentationEntryPoint()) {
328 return FindCompiledCodeForInstrumentation(method) != nullptr;
329 }
330 return false;
331}
332
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000333bool JitCodeCache::ContainsMethod(ArtMethod* method) {
334 MutexLock mu(Thread::Current(), lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000335 if (UNLIKELY(method->IsNative())) {
336 auto it = jni_stubs_map_.find(JniStubKey(method));
337 if (it != jni_stubs_map_.end() &&
338 it->second.IsCompiled() &&
339 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000340 return true;
341 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000342 } else {
343 for (const auto& it : method_code_map_) {
344 if (it.second == method) {
345 return true;
346 }
347 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000348 }
349 return false;
350}
351
Vladimir Marko2196c652017-11-30 16:16:07 +0000352const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
353 DCHECK(method->IsNative());
354 MutexLock mu(Thread::Current(), lock_);
355 auto it = jni_stubs_map_.find(JniStubKey(method));
356 if (it != jni_stubs_map_.end()) {
357 JniStubData& data = it->second;
358 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
359 return data.GetCode();
360 }
361 }
362 return nullptr;
363}
364
Alex Light2d441b12018-06-08 15:33:21 -0700365const void* JitCodeCache::FindCompiledCodeForInstrumentation(ArtMethod* method) {
Alex Light839f53a2018-07-10 15:46:14 -0700366 // If jit-gc is still on we use the SavedEntryPoint field for doing that and so cannot use it to
367 // find the instrumentation entrypoint.
368 if (LIKELY(GetGarbageCollectCode())) {
Alex Light2d441b12018-06-08 15:33:21 -0700369 return nullptr;
370 }
371 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
372 if (info == nullptr) {
373 return nullptr;
374 }
375 // When GC is disabled for trampoline tracing we will use SavedEntrypoint to hold the actual
376 // jit-compiled version of the method. If jit-gc is disabled for other reasons this will just be
377 // nullptr.
378 return info->GetSavedEntryPoint();
379}
380
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800381class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100382 public:
Calin Juravle016fcbe22018-05-03 19:47:35 -0700383 explicit ScopedCodeCacheWrite(const JitCodeCache* const code_cache)
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100384 : ScopedTrace("ScopedCodeCacheWrite"),
Calin Juravle016fcbe22018-05-03 19:47:35 -0700385 code_cache_(code_cache) {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800386 ScopedTrace trace("mprotect all");
Calin Juravle016fcbe22018-05-03 19:47:35 -0700387 CheckedCall(
388 mprotect,
389 "make code writable",
390 code_cache_->code_map_->Begin(),
391 code_cache_->code_map_->Size(),
392 code_cache_->memmap_flags_prot_code_ | PROT_WRITE);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800393 }
Calin Juravle016fcbe22018-05-03 19:47:35 -0700394
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100395 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800396 ScopedTrace trace("mprotect code");
Calin Juravle016fcbe22018-05-03 19:47:35 -0700397 CheckedCall(
398 mprotect,
399 "make code protected",
400 code_cache_->code_map_->Begin(),
401 code_cache_->code_map_->Size(),
402 code_cache_->memmap_flags_prot_code_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100403 }
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700404
David Sehrd1dbb742017-07-17 11:20:38 -0700405 private:
Calin Juravle016fcbe22018-05-03 19:47:35 -0700406 const JitCodeCache* const code_cache_;
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100407
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100408 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
409};
410
411uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100412 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000413 uint8_t* stack_map,
414 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100415 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000416 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100417 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000418 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700419 Handle<mirror::ObjectArray<mirror::Object>> roots,
420 bool has_should_deoptimize_flag,
421 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100422 uint8_t* result = CommitCodeInternal(self,
423 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000424 stack_map,
425 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100426 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000427 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100428 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000429 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700430 roots,
431 has_should_deoptimize_flag,
432 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100433 if (result == nullptr) {
434 // Retry.
435 GarbageCollectCache(self);
436 result = CommitCodeInternal(self,
437 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000438 stack_map,
439 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100440 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000441 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100442 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000443 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700444 roots,
445 has_should_deoptimize_flag,
446 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100447 }
448 return result;
449}
450
451bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
452 bool in_collection = false;
453 while (collection_in_progress_) {
454 in_collection = true;
455 lock_cond_.Wait(self);
456 }
457 return in_collection;
458}
459
460static uintptr_t FromCodeToAllocation(const void* code) {
461 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
462 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
463}
464
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000465static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
466 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
467}
468
469static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
470 // The length of the table is stored just before the stack map (and therefore at the end of
471 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
472 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
473}
474
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800475static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
476 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
477 // pointer.
478 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
479}
480
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000481static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
482 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
483}
484
Alex Light3e36a9c2018-06-19 09:45:05 -0700485static void DCheckRootsAreValid(Handle<mirror::ObjectArray<mirror::Object>> roots)
486 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
487 if (!kIsDebugBuild) {
488 return;
489 }
490 const uint32_t length = roots->GetLength();
491 // Put all roots in `roots_data`.
492 for (uint32_t i = 0; i < length; ++i) {
493 ObjPtr<mirror::Object> object = roots->Get(i);
494 // Ensure the string is strongly interned. b/32995596
495 if (object->IsString()) {
496 ObjPtr<mirror::String> str = ObjPtr<mirror::String>::DownCast(object);
497 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
498 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
499 }
500 }
501}
502
503void JitCodeCache::FillRootTable(uint8_t* roots_data,
504 Handle<mirror::ObjectArray<mirror::Object>> roots) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000505 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800506 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000507 // Put all roots in `roots_data`.
508 for (uint32_t i = 0; i < length; ++i) {
509 ObjPtr<mirror::Object> object = roots->Get(i);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000510 gc_roots[i] = GcRoot<mirror::Object>(object);
511 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000512}
513
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100514static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000515 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
516 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
517 uint32_t roots = GetNumberOfRoots(data);
518 if (number_of_roots != nullptr) {
519 *number_of_roots = roots;
520 }
521 return data - ComputeRootTableSize(roots);
522}
523
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100524// Use a sentinel for marking entries in the JIT table that have been cleared.
525// This helps diagnosing in case the compiled code tries to wrongly access such
526// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700527static mirror::Class* const weak_sentinel =
528 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100529
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000530// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100531static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
532 IsMarkedVisitor* visitor,
533 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000534 REQUIRES_SHARED(Locks::mutator_lock_) {
535 // This does not need a read barrier because this is called by GC.
536 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100537 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000538 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
539 // Look at the classloader of the class to know if it has been unloaded.
540 // This does not need a read barrier because this is called by GC.
541 mirror::Object* class_loader =
542 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
543 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
544 // The class loader is live, update the entry if the class has moved.
545 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
546 // Note that new_object can be null for CMS and newly allocated objects.
547 if (new_cls != nullptr && new_cls != cls) {
548 *root_ptr = GcRoot<mirror::Class>(new_cls);
549 }
550 } else {
551 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100552 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000553 }
554 }
555}
556
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000557void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
558 MutexLock mu(Thread::Current(), lock_);
559 for (const auto& entry : method_code_map_) {
560 uint32_t number_of_roots = 0;
561 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
562 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
563 for (uint32_t i = 0; i < number_of_roots; ++i) {
564 // This does not need a read barrier because this is called by GC.
565 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100566 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000567 // entry got deleted in a previous sweep.
568 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
569 mirror::Object* new_object = visitor->IsMarked(object);
570 // We know the string is marked because it's a strongly-interned string that
571 // is always alive. The IsMarked implementation of the CMS collector returns
572 // null for newly allocated objects, but we know those haven't moved. Therefore,
573 // only update the entry if we get a different non-null string.
574 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
575 // out of the weak access/creation pause. b/32167580
576 if (new_object != nullptr && new_object != object) {
577 DCHECK(new_object->IsString());
578 roots[i] = GcRoot<mirror::Object>(new_object);
579 }
580 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100581 ProcessWeakClass(
582 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000583 }
584 }
585 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000586 // Walk over inline caches to clear entries containing unloaded classes.
587 for (ProfilingInfo* info : profiling_infos_) {
588 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
589 InlineCache* cache = &info->cache_[i];
590 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100591 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000592 }
593 }
594 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000595}
596
Orion Hodson607624f2018-05-11 10:10:46 +0100597void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100598 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000599 // Notify native debugger that we are about to remove the code.
600 // It does nothing if we are not using native debugger.
David Srbeckyfb3de3d2018-01-29 16:11:49 +0000601 MutexLock mu(Thread::Current(), *Locks::native_debug_interface_lock_);
David Srbecky440a9b32018-02-15 17:47:29 +0000602 RemoveNativeDebugInfoForJit(code_ptr);
Vladimir Marko2196c652017-11-30 16:16:07 +0000603 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
604 FreeData(GetRootTable(code_ptr));
605 } // else this is a JNI stub without any data.
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100606 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100607}
608
Mingyao Yang063fc772016-08-02 11:02:54 -0700609void JitCodeCache::FreeAllMethodHeaders(
610 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
611 {
612 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700613 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
Mingyao Yang063fc772016-08-02 11:02:54 -0700614 ->RemoveDependentsWithMethodHeaders(method_headers);
615 }
616
617 // We need to remove entries in method_headers from CHA dependencies
618 // first since once we do FreeCode() below, the memory can be reused
619 // so it's possible for the same method_header to start representing
620 // different compile code.
621 MutexLock mu(Thread::Current(), lock_);
Calin Juravle016fcbe22018-05-03 19:47:35 -0700622 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700623 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodson607624f2018-05-11 10:10:46 +0100624 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700625 }
626}
627
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100628void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800629 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700630 // We use a set to first collect all method_headers whose code need to be
631 // removed. We need to free the underlying code after we remove CHA dependencies
632 // for entries in this set. And it's more efficient to iterate through
633 // the CHA dependency map just once with an unordered_set.
634 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000635 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700636 MutexLock mu(self, lock_);
637 // We do not check if a code cache GC is in progress, as this method comes
638 // with the classlinker_classes_lock_ held, and suspending ourselves could
639 // lead to a deadlock.
640 {
Calin Juravle016fcbe22018-05-03 19:47:35 -0700641 ScopedCodeCacheWrite scc(this);
Vladimir Marko2196c652017-11-30 16:16:07 +0000642 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
643 it->second.RemoveMethodsIn(alloc);
644 if (it->second.GetMethods().empty()) {
645 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
646 it = jni_stubs_map_.erase(it);
647 } else {
648 it->first.UpdateShorty(it->second.GetMethods().front());
649 ++it;
650 }
651 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700652 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
653 if (alloc.ContainsUnsafe(it->second)) {
654 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
655 it = method_code_map_.erase(it);
656 } else {
657 ++it;
658 }
659 }
660 }
661 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
662 if (alloc.ContainsUnsafe(it->first)) {
663 // Note that the code has already been pushed to method_headers in the loop
664 // above and is going to be removed in FreeCode() below.
665 it = osr_code_map_.erase(it);
666 } else {
667 ++it;
668 }
669 }
670 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
671 ProfilingInfo* info = *it;
672 if (alloc.ContainsUnsafe(info->GetMethod())) {
673 info->GetMethod()->SetProfilingInfo(nullptr);
674 FreeData(reinterpret_cast<uint8_t*>(info));
675 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000676 } else {
677 ++it;
678 }
679 }
680 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700681 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100682}
683
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000684bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
685 return kUseReadBarrier
686 ? self->GetWeakRefAccessEnabled()
Orion Hodson88591fe2018-03-06 13:35:43 +0000687 : is_weak_access_enabled_.load(std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000688}
689
690void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
691 if (IsWeakAccessEnabled(self)) {
692 return;
693 }
694 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000695 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000696 while (!IsWeakAccessEnabled(self)) {
697 inline_cache_cond_.Wait(self);
698 }
699}
700
701void JitCodeCache::BroadcastForInlineCacheAccess() {
702 Thread* self = Thread::Current();
703 MutexLock mu(self, lock_);
704 inline_cache_cond_.Broadcast(self);
705}
706
707void JitCodeCache::AllowInlineCacheAccess() {
708 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000709 is_weak_access_enabled_.store(true, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000710 BroadcastForInlineCacheAccess();
711}
712
713void JitCodeCache::DisallowInlineCacheAccess() {
714 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000715 is_weak_access_enabled_.store(false, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000716}
717
718void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
719 Handle<mirror::ObjectArray<mirror::Class>> array) {
720 WaitUntilInlineCacheAccessible(Thread::Current());
721 // Note that we don't need to lock `lock_` here, the compiler calling
722 // this method has already ensured the inline cache will not be deleted.
723 for (size_t in_cache = 0, in_array = 0;
724 in_cache < InlineCache::kIndividualCacheSize;
725 ++in_cache) {
726 mirror::Class* object = ic.classes_[in_cache].Read();
727 if (object != nullptr) {
728 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000729 }
730 }
731}
732
Mathieu Chartierf044c222017-05-31 15:27:54 -0700733static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
734 if (was_warm) {
Vladimir Markoc945e0d2018-07-18 17:26:45 +0100735 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700736 }
737 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
738 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100739 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
740 // the warmup threshold is 1.
741 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
742 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700743}
744
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100745uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
746 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000747 uint8_t* stack_map,
748 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100749 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000750 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100751 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000752 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700753 Handle<mirror::ObjectArray<mirror::Object>> roots,
754 bool has_should_deoptimize_flag,
755 const ArenaSet<ArtMethod*>&
756 cha_single_implementation_list) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000757 DCHECK(!method->IsNative() || !osr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100758 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
759 // Ensure the header ends up at expected instruction alignment.
760 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
761 size_t total_size = header_size + code_size;
762
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100763 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100764 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000765 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100766 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000767 ScopedThreadSuspension sts(self, kSuspended);
768 MutexLock mu(self, lock_);
769 WaitForPotentialCollectionToComplete(self);
770 {
Calin Juravle016fcbe22018-05-03 19:47:35 -0700771 ScopedCodeCacheWrite scc(this);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000772 memory = AllocateCode(total_size);
773 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000774 return nullptr;
775 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100776 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000777
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100778 std::copy(code, code + code_size, code_ptr);
779 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
780 new (method_header) OatQuickMethodHeader(
Vladimir Marko2196c652017-11-30 16:16:07 +0000781 (stack_map != nullptr) ? code_ptr - stack_map : 0u,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000782 code_size);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100783 // Flush caches before we remove write permission because some ARMv8 Qualcomm kernels may
784 // trigger a segfault if a page fault occurs when requesting a cache maintenance operation.
785 // This is a kernel bug that we need to work around until affected devices (e.g. Nexus 5X and
786 // 6P) stop being supported or their kernels are fixed.
787 //
788 // For reference, this behavior is caused by this commit:
789 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
790 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
791 reinterpret_cast<char*>(code_ptr + code_size));
Mingyao Yang063fc772016-08-02 11:02:54 -0700792 DCHECK(!Runtime::Current()->IsAotCompiler());
793 if (has_should_deoptimize_flag) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100794 method_header->SetHasShouldDeoptimizeFlag();
Mingyao Yang063fc772016-08-02 11:02:54 -0700795 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100796 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100797
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000798 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100799 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000800 // We need to update the entry point in the runnable state for the instrumentation.
801 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700802 // Need cha_lock_ for checking all single-implementation flags and register
803 // dependencies.
804 MutexLock cha_mu(self, *Locks::cha_lock_);
805 bool single_impl_still_valid = true;
806 for (ArtMethod* single_impl : cha_single_implementation_list) {
807 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700808 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
809 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700810 single_impl_still_valid = false;
Mathieu Chartierf044c222017-05-31 15:27:54 -0700811 ClearMethodCounter(method, /*was_warm*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700812 break;
813 }
814 }
815
816 // Discard the code if any single-implementation assumptions are now invalid.
817 if (!single_impl_still_valid) {
818 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
819 return nullptr;
820 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000821 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800822 << "Should not be using cha on debuggable apps/runs!";
823
Mingyao Yang063fc772016-08-02 11:02:54 -0700824 for (ArtMethod* single_impl : cha_single_implementation_list) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700825 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()->AddDependency(
Mingyao Yang063fc772016-08-02 11:02:54 -0700826 single_impl, method, method_header);
827 }
828
Alex Light3e36a9c2018-06-19 09:45:05 -0700829 if (!method->IsNative()) {
830 // We need to do this before grabbing the lock_ because it needs to be able to see the string
831 // InternTable. Native methods do not have roots.
832 DCheckRootsAreValid(roots);
833 }
834
Mingyao Yang063fc772016-08-02 11:02:54 -0700835 // The following needs to be guarded by cha_lock_ also. Otherwise it's
836 // possible that the compiled code is considered invalidated by some class linking,
837 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000838 MutexLock mu(self, lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000839 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000840 auto it = jni_stubs_map_.find(JniStubKey(method));
841 DCHECK(it != jni_stubs_map_.end())
842 << "Entry inserted in NotifyCompilationOf() should be alive.";
843 JniStubData* data = &it->second;
844 DCHECK(ContainsElement(data->GetMethods(), method))
845 << "Entry inserted in NotifyCompilationOf() should contain this method.";
846 data->SetCode(code_ptr);
847 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
848 for (ArtMethod* m : data->GetMethods()) {
849 instrum->UpdateMethodsCode(m, method_header->GetEntryPoint());
850 }
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100851 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +0000852 // Fill the root table before updating the entry point.
853 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
854 DCHECK_LE(roots_data, stack_map);
855 FillRootTable(roots_data, roots);
856 {
857 // Flush data cache, as compiled code references literals in it.
Vladimir Marko2196c652017-11-30 16:16:07 +0000858 FlushDataCache(reinterpret_cast<char*>(roots_data),
859 reinterpret_cast<char*>(roots_data + data_size));
860 }
861 method_code_map_.Put(code_ptr, method);
862 if (osr) {
863 number_of_osr_compilations_++;
864 osr_code_map_.Put(method, code_ptr);
865 } else {
866 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
867 method, method_header->GetEntryPoint());
868 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000869 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000870 if (collection_in_progress_) {
871 // We need to update the live bitmap if there is a GC to ensure it sees this new
872 // code.
873 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
874 }
875 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100876 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700877 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000878 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
879 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
880 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700881 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
882 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000883 histogram_code_memory_use_.AddValue(code_size);
884 if (code_size > kCodeSizeLogThreshold) {
885 LOG(INFO) << "JIT allocated "
886 << PrettySize(code_size)
887 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700888 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000889 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000890 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100891
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100892 return reinterpret_cast<uint8_t*>(method_header);
893}
894
895size_t JitCodeCache::CodeCacheSize() {
896 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000897 return CodeCacheSizeLocked();
898}
899
Orion Hodsoneced6922017-06-01 10:54:28 +0100900bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000901 // This function is used only for testing and only with non-native methods.
902 CHECK(!method->IsNative());
903
Orion Hodsoneced6922017-06-01 10:54:28 +0100904 MutexLock mu(Thread::Current(), lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +0100905
Vladimir Marko2196c652017-11-30 16:16:07 +0000906 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
907 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +0100908
909 if (!in_cache) {
910 return false;
911 }
912
Orion Hodsoneced6922017-06-01 10:54:28 +0100913 method->ClearCounter();
914 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
915 method, GetQuickToInterpreterBridge());
916 VLOG(jit)
917 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
918 << ArtMethod::PrettyMethod(method) << "@" << method
919 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
920 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
921 return true;
922}
923
Vladimir Marko2196c652017-11-30 16:16:07 +0000924bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
925 if (LIKELY(!method->IsNative())) {
926 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
927 if (info != nullptr) {
928 RemoveElement(profiling_infos_, info);
929 }
930 method->SetProfilingInfo(nullptr);
931 }
932
933 bool in_cache = false;
Calin Juravle016fcbe22018-05-03 19:47:35 -0700934 ScopedCodeCacheWrite ccw(this);
Vladimir Marko2196c652017-11-30 16:16:07 +0000935 if (UNLIKELY(method->IsNative())) {
936 auto it = jni_stubs_map_.find(JniStubKey(method));
937 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
938 in_cache = true;
939 if (it->second.GetMethods().empty()) {
940 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100941 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +0000942 }
943 jni_stubs_map_.erase(it);
944 } else {
945 it->first.UpdateShorty(it->second.GetMethods().front());
946 }
947 }
948 } else {
949 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
950 if (it->second == method) {
951 in_cache = true;
952 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100953 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +0000954 }
955 it = method_code_map_.erase(it);
956 } else {
957 ++it;
958 }
959 }
960
961 auto osr_it = osr_code_map_.find(method);
962 if (osr_it != osr_code_map_.end()) {
963 osr_code_map_.erase(osr_it);
964 }
965 }
966
967 return in_cache;
968}
969
Alex Lightdba61482016-12-21 08:20:29 -0800970// This notifies the code cache that the given method has been redefined and that it should remove
971// any cached information it has on the method. All threads must be suspended before calling this
972// method. The compiled code for the method (if there is any) must not be in any threads call stack.
973void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
974 MutexLock mu(Thread::Current(), lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000975 RemoveMethodLocked(method, /* release_memory */ true);
Alex Lightdba61482016-12-21 08:20:29 -0800976}
977
978// This invalidates old_method. Once this function returns one can no longer use old_method to
979// execute code unless it is fixed up. This fixup will happen later in the process of installing a
980// class redefinition.
981// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
982// shouldn't be used since it is no longer logically in the jit code cache.
983// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
984void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000985 MutexLock mu(Thread::Current(), lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +0000986 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000987 // Update methods in jni_stubs_map_.
988 for (auto& entry : jni_stubs_map_) {
989 JniStubData& data = entry.second;
990 data.MoveObsoleteMethod(old_method, new_method);
991 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000992 return;
993 }
Alex Lightdba61482016-12-21 08:20:29 -0800994 // Update ProfilingInfo to the new one and remove it from the old_method.
995 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
996 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
997 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
998 old_method->SetProfilingInfo(nullptr);
999 // Since the JIT should be paused and all threads suspended by the time this is called these
1000 // checks should always pass.
1001 DCHECK(!info->IsInUseByCompiler());
1002 new_method->SetProfilingInfo(info);
Alex Light2d441b12018-06-08 15:33:21 -07001003 // Get rid of the old saved entrypoint if it is there.
1004 info->SetSavedEntryPoint(nullptr);
Alex Lightdba61482016-12-21 08:20:29 -08001005 info->method_ = new_method;
1006 }
1007 // Update method_code_map_ to point to the new method.
1008 for (auto& it : method_code_map_) {
1009 if (it.second == old_method) {
1010 it.second = new_method;
1011 }
1012 }
1013 // Update osr_code_map_ to point to the new method.
1014 auto code_map = osr_code_map_.find(old_method);
1015 if (code_map != osr_code_map_.end()) {
1016 osr_code_map_.Put(new_method, code_map->second);
1017 osr_code_map_.erase(old_method);
1018 }
1019}
1020
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001021size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001022 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001023}
1024
1025size_t JitCodeCache::DataCacheSize() {
1026 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001027 return DataCacheSizeLocked();
1028}
1029
1030size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001031 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001032}
1033
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001034void JitCodeCache::ClearData(Thread* self,
1035 uint8_t* stack_map_data,
1036 uint8_t* roots_data) {
1037 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001038 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001039 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001040}
1041
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001042size_t JitCodeCache::ReserveData(Thread* self,
1043 size_t stack_map_size,
1044 size_t number_of_roots,
1045 ArtMethod* method,
1046 uint8_t** stack_map_data,
1047 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001048 size_t table_size = ComputeRootTableSize(number_of_roots);
David Srbecky8cd54542018-07-15 23:58:44 +01001049 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001050 uint8_t* result = nullptr;
1051
1052 {
1053 ScopedThreadSuspension sts(self, kSuspended);
1054 MutexLock mu(self, lock_);
1055 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001056 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001057 }
1058
1059 if (result == nullptr) {
1060 // Retry.
1061 GarbageCollectCache(self);
1062 ScopedThreadSuspension sts(self, kSuspended);
1063 MutexLock mu(self, lock_);
1064 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001065 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001066 }
1067
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001068 MutexLock mu(self, lock_);
1069 histogram_stack_map_memory_use_.AddValue(size);
1070 if (size > kStackMapSizeLogThreshold) {
1071 LOG(INFO) << "JIT allocated "
1072 << PrettySize(size)
1073 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001074 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001075 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001076 if (result != nullptr) {
1077 *roots_data = result;
1078 *stack_map_data = result + table_size;
1079 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001080 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001081 } else {
1082 *roots_data = nullptr;
1083 *stack_map_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001084 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001085 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001086}
1087
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001088class MarkCodeVisitor FINAL : public StackVisitor {
1089 public:
1090 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
1091 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
1092 code_cache_(code_cache_in),
1093 bitmap_(code_cache_->GetLiveBitmap()) {}
1094
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001095 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001096 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
1097 if (method_header == nullptr) {
1098 return true;
1099 }
1100 const void* code = method_header->GetCode();
1101 if (code_cache_->ContainsPc(code)) {
1102 // Use the atomic set version, as multiple threads are executing this code.
1103 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1104 }
1105 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001106 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001107
1108 private:
1109 JitCodeCache* const code_cache_;
1110 CodeCacheBitmap* const bitmap_;
1111};
1112
1113class MarkCodeClosure FINAL : public Closure {
1114 public:
1115 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
1116 : code_cache_(code_cache), barrier_(barrier) {}
1117
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001118 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001119 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001120 DCHECK(thread == Thread::Current() || thread->IsSuspended());
1121 MarkCodeVisitor visitor(thread, code_cache_);
1122 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001123 if (kIsDebugBuild) {
1124 // The stack walking code queries the side instrumentation stack if it
1125 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1126 // must have been seen. We sanity check this below.
1127 for (const instrumentation::InstrumentationStackFrame& frame
1128 : *thread->GetInstrumentationStack()) {
1129 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1130 // its stack frame, it is not the method owning return_pc_. We just pass null to
1131 // LookupMethodHeader: the method is only checked against in debug builds.
1132 OatQuickMethodHeader* method_header =
Vladimir Marko2196c652017-11-30 16:16:07 +00001133 code_cache_->LookupMethodHeader(frame.return_pc_, /* method */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001134 if (method_header != nullptr) {
1135 const void* code = method_header->GetCode();
1136 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
1137 }
1138 }
1139 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001140 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001141 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001142
1143 private:
1144 JitCodeCache* const code_cache_;
1145 Barrier* const barrier_;
1146};
1147
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001148void JitCodeCache::NotifyCollectionDone(Thread* self) {
1149 collection_in_progress_ = false;
1150 lock_cond_.Broadcast(self);
1151}
1152
1153void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
1154 size_t per_space_footprint = new_footprint / 2;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001155 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001156 DCHECK_EQ(per_space_footprint * 2, new_footprint);
1157 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
1158 {
Calin Juravle016fcbe22018-05-03 19:47:35 -07001159 ScopedCodeCacheWrite scc(this);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001160 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
1161 }
1162}
1163
1164bool JitCodeCache::IncreaseCodeCacheCapacity() {
1165 if (current_capacity_ == max_capacity_) {
1166 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001167 }
1168
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001169 // Double the capacity if we're below 1MB, or increase it by 1MB if
1170 // we're above.
1171 if (current_capacity_ < 1 * MB) {
1172 current_capacity_ *= 2;
1173 } else {
1174 current_capacity_ += 1 * MB;
1175 }
1176 if (current_capacity_ > max_capacity_) {
1177 current_capacity_ = max_capacity_;
1178 }
1179
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001180 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001181
1182 SetFootprintLimit(current_capacity_);
1183
1184 return true;
1185}
1186
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001187void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1188 Barrier barrier(0);
1189 size_t threads_running_checkpoint = 0;
1190 MarkCodeClosure closure(this, &barrier);
1191 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1192 // Now that we have run our checkpoint, move to a suspended state and wait
1193 // for other threads to run the checkpoint.
1194 ScopedThreadSuspension sts(self, kSuspended);
1195 if (threads_running_checkpoint != 0) {
1196 barrier.Increment(self, threads_running_checkpoint);
1197 }
1198}
1199
Nicolas Geoffray35122442016-03-02 12:05:30 +00001200bool JitCodeCache::ShouldDoFullCollection() {
1201 if (current_capacity_ == max_capacity_) {
1202 // Always do a full collection when the code cache is full.
1203 return true;
1204 } else if (current_capacity_ < kReservedCapacity) {
1205 // Always do partial collection when the code cache size is below the reserved
1206 // capacity.
1207 return false;
1208 } else if (last_collection_increased_code_cache_) {
1209 // This time do a full collection.
1210 return true;
1211 } else {
1212 // This time do a partial collection.
1213 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001214 }
1215}
1216
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001217void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001218 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001219 if (!garbage_collect_code_) {
1220 MutexLock mu(self, lock_);
1221 IncreaseCodeCacheCapacity();
1222 return;
1223 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001224
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001225 // Wait for an existing collection, or let everyone know we are starting one.
1226 {
1227 ScopedThreadSuspension sts(self, kSuspended);
1228 MutexLock mu(self, lock_);
1229 if (WaitForPotentialCollectionToComplete(self)) {
1230 return;
1231 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001232 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001233 live_bitmap_.reset(CodeCacheBitmap::Create(
1234 "code-cache-bitmap",
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001235 reinterpret_cast<uintptr_t>(code_map_->Begin()),
1236 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001237 collection_in_progress_ = true;
1238 }
1239 }
1240
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001241 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001242 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001243 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001244
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001245 bool do_full_collection = false;
1246 {
1247 MutexLock mu(self, lock_);
1248 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001249 }
1250
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001251 VLOG(jit) << "Do "
1252 << (do_full_collection ? "full" : "partial")
1253 << " code cache collection, code="
1254 << PrettySize(CodeCacheSize())
1255 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001256
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001257 DoCollection(self, /* collect_profiling_info */ do_full_collection);
1258
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001259 VLOG(jit) << "After code cache collection, code="
1260 << PrettySize(CodeCacheSize())
1261 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001262
1263 {
1264 MutexLock mu(self, lock_);
1265
1266 // Increase the code cache only when we do partial collections.
1267 // TODO: base this strategy on how full the code cache is?
1268 if (do_full_collection) {
1269 last_collection_increased_code_cache_ = false;
1270 } else {
1271 last_collection_increased_code_cache_ = true;
1272 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001273 }
1274
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001275 bool next_collection_will_be_full = ShouldDoFullCollection();
1276
1277 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001278 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001279 // Save the entry point of methods we have compiled, and update the entry
1280 // point of those methods to the interpreter. If the method is invoked, the
1281 // interpreter will update its entry point to the compiled code and call it.
1282 for (ProfilingInfo* info : profiling_infos_) {
1283 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1284 if (ContainsPc(entry_point)) {
1285 info->SetSavedEntryPoint(entry_point);
Vladimir Marko2196c652017-11-30 16:16:07 +00001286 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001287 // class of the method. We may be concurrently running a GC which makes accessing
1288 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1289 // checked that the current entry point is JIT compiled code.
1290 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001291 }
1292 }
1293
1294 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Vladimir Marko2196c652017-11-30 16:16:07 +00001295
1296 // Change entry points of native methods back to the GenericJNI entrypoint.
1297 for (const auto& entry : jni_stubs_map_) {
1298 const JniStubData& data = entry.second;
1299 if (!data.IsCompiled()) {
1300 continue;
1301 }
1302 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1303 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1304 const OatQuickMethodHeader* method_header =
1305 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1306 for (ArtMethod* method : data.GetMethods()) {
1307 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1308 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1309 method->SetCounter(new_counter);
1310 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1311 }
1312 }
1313 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001314 }
1315 live_bitmap_.reset(nullptr);
1316 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001317 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001318 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001319 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001320}
1321
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001322void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001323 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001324 std::unordered_set<OatQuickMethodHeader*> method_headers;
1325 {
1326 MutexLock mu(self, lock_);
Calin Juravle016fcbe22018-05-03 19:47:35 -07001327 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -07001328 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001329 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1330 JniStubData* data = &it->second;
1331 if (!data->IsCompiled() || GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
1332 ++it;
1333 } else {
1334 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1335 it = jni_stubs_map_.erase(it);
1336 }
1337 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001338 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1339 const void* code_ptr = it->first;
1340 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1341 if (GetLiveBitmap()->Test(allocation)) {
1342 ++it;
1343 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001344 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1345 method_headers.insert(header);
Mingyao Yang063fc772016-08-02 11:02:54 -07001346 it = method_code_map_.erase(it);
1347 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001348 }
1349 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001350 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001351}
1352
1353void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001354 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001355 {
1356 MutexLock mu(self, lock_);
1357 if (collect_profiling_info) {
1358 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1359 // Also remove the saved entry point from the ProfilingInfo objects.
1360 for (ProfilingInfo* info : profiling_infos_) {
1361 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001362 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001363 info->GetMethod()->SetProfilingInfo(nullptr);
1364 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001365
1366 if (info->GetSavedEntryPoint() != nullptr) {
1367 info->SetSavedEntryPoint(nullptr);
1368 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001369 // give it a chance to be hot again.
1370 ClearMethodCounter(info->GetMethod(), /*was_warm*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001371 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001372 }
1373 } else if (kIsDebugBuild) {
1374 // Sanity check that the profiling infos do not have a dangling entry point.
1375 for (ProfilingInfo* info : profiling_infos_) {
1376 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001377 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001378 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001379
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001380 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1381 // an entry point is either:
1382 // - an osr compiled code, that will be removed if not in a thread call stack.
1383 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001384 for (const auto& entry : jni_stubs_map_) {
1385 const JniStubData& data = entry.second;
1386 const void* code_ptr = data.GetCode();
1387 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1388 for (ArtMethod* method : data.GetMethods()) {
1389 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1390 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1391 break;
1392 }
1393 }
1394 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001395 for (const auto& it : method_code_map_) {
1396 ArtMethod* method = it.second;
1397 const void* code_ptr = it.first;
1398 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1399 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1400 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1401 }
1402 }
1403
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001404 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001405 // on thread stacks).
1406 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001407 }
1408
1409 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001410 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001411
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001412 // At this point, mutator threads are still running, and entrypoints of methods can
1413 // change. We do know they cannot change to a code cache entry that is not marked,
1414 // therefore we can safely remove those entries.
1415 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001416
Nicolas Geoffray35122442016-03-02 12:05:30 +00001417 if (collect_profiling_info) {
1418 MutexLock mu(self, lock_);
1419 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001420 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001421 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001422 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001423 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1424 // that the compiled code would not get revived. As mutator threads run concurrently,
1425 // they may have revived the compiled code, and now we are in the situation where
1426 // a method has compiled code but no ProfilingInfo.
1427 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1428 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001429 if (ContainsPc(ptr) &&
1430 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001431 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001432 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001433 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001434 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001435 return true;
1436 }
1437 return false;
1438 });
1439 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001440 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001441 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001442}
1443
Nicolas Geoffray35122442016-03-02 12:05:30 +00001444bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001445 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001446 // Check that methods we have compiled do have a ProfilingInfo object. We would
1447 // have memory leaks of compiled code otherwise.
1448 for (const auto& it : method_code_map_) {
1449 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001450 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001451 const void* code_ptr = it.first;
1452 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1453 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1454 // If the code is not dead, then we have a problem. Note that this can even
1455 // happen just after a collection, as mutator threads are running in parallel
1456 // and could deoptimize an existing compiled code.
1457 return false;
1458 }
1459 }
1460 }
1461 return true;
1462}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001463
1464OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001465 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1466 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001467 // On Thumb-2, the pc is offset by one.
1468 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001469 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001470 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1471 return nullptr;
1472 }
1473
Vladimir Marko2196c652017-11-30 16:16:07 +00001474 if (!kIsDebugBuild) {
1475 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1476 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001477 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001478
Vladimir Marko2196c652017-11-30 16:16:07 +00001479 MutexLock mu(Thread::Current(), lock_);
1480 OatQuickMethodHeader* method_header = nullptr;
1481 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1482 if (method != nullptr && UNLIKELY(method->IsNative())) {
1483 auto it = jni_stubs_map_.find(JniStubKey(method));
1484 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1485 return nullptr;
1486 }
1487 const void* code_ptr = it->second.GetCode();
1488 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1489 if (!method_header->Contains(pc)) {
1490 return nullptr;
1491 }
1492 } else {
1493 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1494 if (it != method_code_map_.begin()) {
1495 --it;
1496 const void* code_ptr = it->first;
1497 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1498 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1499 found_method = it->second;
1500 }
1501 }
1502 if (method_header == nullptr && method == nullptr) {
1503 // Scan all compiled JNI stubs as well. This slow search is used only
1504 // for checks in debug build, for release builds the `method` is not null.
1505 for (auto&& entry : jni_stubs_map_) {
1506 const JniStubData& data = entry.second;
1507 if (data.IsCompiled() &&
1508 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1509 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1510 }
1511 }
1512 }
1513 if (method_header == nullptr) {
1514 return nullptr;
1515 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001516 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001517
1518 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001519 // When we are walking the stack to redefine classes and creating obsolete methods it is
1520 // possible that we might have updated the method_code_map by making this method obsolete in a
1521 // previous frame. Therefore we should just check that the non-obsolete version of this method
1522 // is the one we expect. We change to the non-obsolete versions in the error message since the
1523 // obsolete version of the method might not be fully initialized yet. This situation can only
1524 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
Andreas Gampe06c42a52017-07-26 14:17:14 -07001525 // method and it->second should be identical. (See openjdkjvmti/ti_redefine.cc for more
Alex Light1ebe4fe2017-01-30 14:57:11 -08001526 // information.)
Vladimir Marko2196c652017-11-30 16:16:07 +00001527 DCHECK_EQ(found_method->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
Alex Light1ebe4fe2017-01-30 14:57:11 -08001528 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
Vladimir Marko2196c652017-11-30 16:16:07 +00001529 << ArtMethod::PrettyMethod(found_method->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001530 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001531 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001532 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001533}
1534
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001535OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1536 MutexLock mu(Thread::Current(), lock_);
1537 auto it = osr_code_map_.find(method);
1538 if (it == osr_code_map_.end()) {
1539 return nullptr;
1540 }
1541 return OatQuickMethodHeader::FromCodePointer(it->second);
1542}
1543
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001544ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1545 ArtMethod* method,
1546 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001547 bool retry_allocation)
1548 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1549 NO_THREAD_SAFETY_ANALYSIS {
1550 ProfilingInfo* info = nullptr;
1551 if (!retry_allocation) {
1552 // If we are allocating for the interpreter, just try to lock, to avoid
1553 // lock contention with the JIT.
1554 if (lock_.ExclusiveTryLock(self)) {
1555 info = AddProfilingInfoInternal(self, method, entries);
1556 lock_.ExclusiveUnlock(self);
1557 }
1558 } else {
1559 {
1560 MutexLock mu(self, lock_);
1561 info = AddProfilingInfoInternal(self, method, entries);
1562 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001563
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001564 if (info == nullptr) {
1565 GarbageCollectCache(self);
1566 MutexLock mu(self, lock_);
1567 info = AddProfilingInfoInternal(self, method, entries);
1568 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001569 }
1570 return info;
1571}
1572
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001573ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001574 ArtMethod* method,
1575 const std::vector<uint32_t>& entries) {
1576 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001577 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001578 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001579
1580 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001581 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001582 if (info != nullptr) {
1583 return info;
1584 }
1585
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001586 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001587 if (data == nullptr) {
1588 return nullptr;
1589 }
1590 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001591
1592 // Make sure other threads see the data in the profiling info object before the
1593 // store in the ArtMethod's ProfilingInfo pointer.
Orion Hodson27b96762018-03-13 16:06:57 +00001594 std::atomic_thread_fence(std::memory_order_release);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001595
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001596 method->SetProfilingInfo(info);
1597 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001598 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001599 return info;
1600}
1601
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001602// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1603// is already held.
1604void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1605 if (code_mspace_ == mspace) {
1606 size_t result = code_end_;
1607 code_end_ += increment;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001608 return reinterpret_cast<void*>(result + code_map_->Begin());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001609 } else {
1610 DCHECK_EQ(data_mspace_, mspace);
1611 size_t result = data_end_;
1612 data_end_ += increment;
1613 return reinterpret_cast<void*>(result + data_map_->Begin());
1614 }
1615}
1616
Calin Juravle99629622016-04-19 16:33:46 +01001617void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001618 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001619 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001620 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001621 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001622 for (const ProfilingInfo* info : profiling_infos_) {
1623 ArtMethod* method = info->GetMethod();
1624 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001625 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1626 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001627 // Skip dex files which are not profiled.
1628 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001629 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001630 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001631
1632 // If the method didn't reach the compilation threshold don't save the inline caches.
1633 // They might be incomplete and cause unnecessary deoptimizations.
1634 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1635 if (method->GetCounter() < jit_compile_threshold) {
1636 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001637 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001638 continue;
1639 }
1640
Calin Juravle940eb0c2017-01-30 19:30:44 -08001641 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001642 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001643 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001644 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001645 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001646 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1647 mirror::Class* cls = cache.classes_[k].Read();
1648 if (cls == nullptr) {
1649 break;
1650 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001651
Calin Juravle13439f02017-02-21 01:17:21 -08001652 // Check if the receiver is in the boot class path or if it's in the
1653 // same class loader as the caller. If not, skip it, as there is not
1654 // much we can do during AOT.
1655 if (!cls->IsBootStrapClassLoaded() &&
1656 caller->GetClassLoader() != cls->GetClassLoader()) {
1657 is_missing_types = true;
1658 continue;
1659 }
1660
Calin Juravle4ca70a32017-02-21 16:22:24 -08001661 const DexFile* class_dex_file = nullptr;
1662 dex::TypeIndex type_index;
1663
1664 if (cls->GetDexCache() == nullptr) {
1665 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001666 // Make a best effort to find the type index in the method's dex file.
1667 // We could search all open dex files but that might turn expensive
1668 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001669 class_dex_file = dex_file;
1670 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1671 } else {
1672 class_dex_file = &(cls->GetDexFile());
1673 type_index = cls->GetDexTypeIndex();
1674 }
1675 if (!type_index.IsValid()) {
1676 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001677 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001678 continue;
1679 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001680 if (ContainsElement(dex_base_locations,
1681 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001682 // Only consider classes from the same apk (including multidex).
1683 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001684 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001685 } else {
1686 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001687 }
1688 }
1689 if (!profile_classes.empty()) {
1690 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001691 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001692 }
1693 }
1694 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001695 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001696 }
1697}
1698
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001699bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1700 MutexLock mu(Thread::Current(), lock_);
1701 return osr_code_map_.find(method) != osr_code_map_.end();
1702}
1703
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001704bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1705 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001706 return false;
1707 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001708
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001709 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001710 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1711 return false;
1712 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001713
Vladimir Marko2196c652017-11-30 16:16:07 +00001714 if (UNLIKELY(method->IsNative())) {
1715 JniStubKey key(method);
1716 auto it = jni_stubs_map_.find(key);
1717 bool new_compilation = false;
1718 if (it == jni_stubs_map_.end()) {
1719 // Create a new entry to mark the stub as being compiled.
1720 it = jni_stubs_map_.Put(key, JniStubData{});
1721 new_compilation = true;
1722 }
1723 JniStubData* data = &it->second;
1724 data->AddMethod(method);
1725 if (data->IsCompiled()) {
1726 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1727 const void* entrypoint = method_header->GetEntryPoint();
1728 // Update also entrypoints of other methods held by the JniStubData.
1729 // We could simply update the entrypoint of `method` but if the last JIT GC has
1730 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1731 // as well change them back as this stub shall not be collected anyway and this
1732 // can avoid a few expensive GenericJNI calls.
1733 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1734 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +00001735 // Call the dedicated method instead of the more generic UpdateMethodsCode, because
1736 // `m` might be in the process of being deleted.
1737 instrumentation->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
Vladimir Marko2196c652017-11-30 16:16:07 +00001738 }
1739 if (collection_in_progress_) {
1740 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1741 }
1742 }
1743 return new_compilation;
1744 } else {
1745 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1746 if (info == nullptr) {
1747 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1748 // Because the counter is not atomic, there are some rare cases where we may not hit the
1749 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
1750 ClearMethodCounter(method, /*was_warm*/ false);
1751 return false;
1752 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001753
Vladimir Marko2196c652017-11-30 16:16:07 +00001754 if (info->IsMethodBeingCompiled(osr)) {
1755 return false;
1756 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001757
Vladimir Marko2196c652017-11-30 16:16:07 +00001758 info->SetIsMethodBeingCompiled(true, osr);
1759 return true;
1760 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001761}
1762
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001763ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001764 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001765 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001766 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001767 if (!info->IncrementInlineUse()) {
1768 // Overflow of inlining uses, just bail.
1769 return nullptr;
1770 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001771 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001772 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001773}
1774
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001775void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001776 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001777 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001778 DCHECK(info != nullptr);
1779 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001780}
1781
Vladimir Marko2196c652017-11-30 16:16:07 +00001782void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
1783 DCHECK_EQ(Thread::Current(), self);
1784 MutexLock mu(self, lock_);
1785 if (UNLIKELY(method->IsNative())) {
1786 auto it = jni_stubs_map_.find(JniStubKey(method));
1787 DCHECK(it != jni_stubs_map_.end());
1788 JniStubData* data = &it->second;
1789 DCHECK(ContainsElement(data->GetMethods(), method));
1790 if (UNLIKELY(!data->IsCompiled())) {
1791 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1792 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
1793 } // else CommitCodeInternal() updated entrypoints of all methods in the JniStubData.
1794 } else {
1795 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1796 DCHECK(info->IsMethodBeingCompiled(osr));
1797 info->SetIsMethodBeingCompiled(false, osr);
1798 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001799}
1800
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001801size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1802 MutexLock mu(Thread::Current(), lock_);
1803 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1804}
1805
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001806void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1807 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001808 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07001809 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Alex Light2d441b12018-06-08 15:33:21 -07001810 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001811 if ((profiling_info != nullptr) &&
1812 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
Alex Light2d441b12018-06-08 15:33:21 -07001813 // When instrumentation is set, the actual entrypoint is the one in the profiling info.
1814 method_entrypoint = profiling_info->GetSavedEntryPoint();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001815 // Prevent future uses of the compiled code.
1816 profiling_info->SetSavedEntryPoint(nullptr);
1817 }
1818
Alex Light2d441b12018-06-08 15:33:21 -07001819 // Clear the method counter if we are running jitted code since we might want to jit this again in
1820 // the future.
1821 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001822 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001823 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001824 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1825 method, GetQuickToInterpreterBridge());
Mathieu Chartierf044c222017-05-31 15:27:54 -07001826 ClearMethodCounter(method, /*was_warm*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001827 } else {
1828 MutexLock mu(Thread::Current(), lock_);
1829 auto it = osr_code_map_.find(method);
1830 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1831 // Remove the OSR method, to avoid using it again.
1832 osr_code_map_.erase(it);
1833 }
1834 }
1835}
1836
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001837uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1838 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1839 uint8_t* result = reinterpret_cast<uint8_t*>(
1840 mspace_memalign(code_mspace_, alignment, code_size));
1841 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1842 // Ensure the header ends up at expected instruction alignment.
1843 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1844 used_memory_for_code_ += mspace_usable_size(result);
1845 return result;
1846}
1847
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001848void JitCodeCache::FreeCode(uint8_t* code) {
1849 used_memory_for_code_ -= mspace_usable_size(code);
1850 mspace_free(code_mspace_, code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001851}
1852
1853uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1854 void* result = mspace_malloc(data_mspace_, data_size);
1855 used_memory_for_data_ += mspace_usable_size(result);
1856 return reinterpret_cast<uint8_t*>(result);
1857}
1858
1859void JitCodeCache::FreeData(uint8_t* data) {
1860 used_memory_for_data_ -= mspace_usable_size(data);
1861 mspace_free(data_mspace_, data);
1862}
1863
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001864void JitCodeCache::Dump(std::ostream& os) {
1865 MutexLock mu(Thread::Current(), lock_);
David Srbeckyfb3de3d2018-01-29 16:11:49 +00001866 MutexLock mu2(Thread::Current(), *Locks::native_debug_interface_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001867 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1868 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
David Srbecky440a9b32018-02-15 17:47:29 +00001869 << "Current JIT mini-debug-info size: " << PrettySize(GetJitNativeDebugInfoMemUsage()) << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001870 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00001871 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001872 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1873 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1874 << "Total number of JIT compilations for on stack replacement: "
1875 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001876 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001877 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1878 histogram_code_memory_use_.PrintMemoryUse(os);
1879 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001880}
1881
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001882} // namespace jit
1883} // namespace art