blob: 32205138bdcf2fa6c3d30ddda232ddf0221418e1 [file] [log] [blame]
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001/*
2 * Copyright 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "jit_code_cache.h"
18
19#include <sstream>
20
Andreas Gampe5629d2d2017-05-15 16:28:13 -070021#include "arch/context.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070022#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070023#include "base/enums.h"
Calin Juravle66f55232015-12-08 15:09:10 +000024#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080025#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010026#include "base/time_utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070027#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000028#include "debugger_interface.h"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070029#include "dex_file_loader.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010030#include "entrypoints/runtime_asm_entrypoints.h"
31#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010032#include "gc/scoped_gc_critical_section.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000033#include "handle.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070034#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000035#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000036#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010037#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080038#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080039#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070040#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070041#include "object_callbacks.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000042#include "profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070043#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070044#include "stack.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000045#include "thread-current-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010046#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080047
48namespace art {
49namespace jit {
50
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010051static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
52static constexpr int kProtData = PROT_READ | PROT_WRITE;
53static constexpr int kProtCode = PROT_READ | PROT_EXEC;
54
Nicolas Geoffray933330a2016-03-16 14:20:06 +000055static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
56static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
57
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000058JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
59 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000060 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000061 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080062 ScopedTrace trace(__PRETTY_FUNCTION__);
Orion Hodsondbd05fe2017-08-10 11:41:35 +010063 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000064
David Sehrd1dbb742017-07-17 11:20:38 -070065 // Generating debug information is for using the Linux perf tool on
66 // host which does not work with ashmem.
Nicolas Geoffray520dadf2017-07-19 15:33:11 +010067 // Also, target linux does not support ashmem.
68 bool use_ashmem = !generate_debug_info && !kIsTargetLinux;
David Sehrd1dbb742017-07-17 11:20:38 -070069
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000070 // With 'perf', we want a 1-1 mapping between an address and a method.
71 bool garbage_collect_code = !generate_debug_info;
72
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000073 // We need to have 32 bit offsets from method headers in code cache which point to things
74 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
75 // Ensure we're below 1 GB to be safe.
76 if (max_capacity > 1 * GB) {
77 std::ostringstream oss;
78 oss << "Maxium code cache capacity is limited to 1 GB, "
79 << PrettySize(max_capacity) << " is too big";
80 *error_msg = oss.str();
81 return nullptr;
82 }
83
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080084 std::string error_str;
85 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +000086 // Map in low 4gb to simplify accessing root tables for x86_64.
87 // We could do PC-relative addressing to avoid this problem, but that
88 // would require reserving code and data area before submitting, which
89 // means more windows for the code memory to be RWX.
Andreas Gampee4deaf32017-06-09 15:27:15 -070090 std::unique_ptr<MemMap> data_map(MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +000091 "data-code-cache", nullptr,
92 max_capacity,
Andreas Gampee4deaf32017-06-09 15:27:15 -070093 kProtData,
Nicolas Geoffray132d8362016-11-16 09:19:42 +000094 /* low_4gb */ true,
95 /* reuse */ false,
96 &error_str,
Andreas Gampee4deaf32017-06-09 15:27:15 -070097 use_ashmem));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010098 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080099 std::ostringstream oss;
Andreas Gampee4deaf32017-06-09 15:27:15 -0700100 oss << "Failed to create read write cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800101 *error_msg = oss.str();
102 return nullptr;
103 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100104
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100105 // Align both capacities to page size, as that's the unit mspaces use.
106 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
107 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100108
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100109 // Data cache is 1 / 2 of the map.
110 // TODO: Make this variable?
111 size_t data_size = max_capacity / 2;
112 size_t code_size = max_capacity - data_size;
113 DCHECK_EQ(code_size + data_size, max_capacity);
114 uint8_t* divider = data_map->Begin() + data_size;
David Sehrd1dbb742017-07-17 11:20:38 -0700115
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100116 MemMap* code_map =
117 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
David Sehrd1dbb742017-07-17 11:20:38 -0700118 if (code_map == nullptr) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100119 std::ostringstream oss;
120 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
121 *error_msg = oss.str();
David Sehrd1dbb742017-07-17 11:20:38 -0700122 return nullptr;
123 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100124 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000125 data_size = initial_capacity / 2;
126 code_size = initial_capacity - data_size;
127 DCHECK_EQ(code_size + data_size, initial_capacity);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100128 return new JitCodeCache(
129 code_map, data_map.release(), code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800130}
131
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100132JitCodeCache::JitCodeCache(MemMap* code_map,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000133 MemMap* data_map,
134 size_t initial_code_capacity,
135 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000136 size_t max_capacity,
137 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100138 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000139 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100140 collection_in_progress_(false),
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100141 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000142 data_map_(data_map),
143 max_capacity_(max_capacity),
144 current_capacity_(initial_code_capacity + initial_data_capacity),
145 code_end_(initial_code_capacity),
146 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000147 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000148 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000149 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000150 used_memory_for_data_(0),
151 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000152 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000153 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000154 number_of_collections_(0),
155 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
156 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000157 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
158 is_weak_access_enabled_(true),
159 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100160
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000161 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100162 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000163 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100164
165 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
166 PLOG(FATAL) << "create_mspace_with_base failed";
167 }
168
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000169 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100170
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700171 CheckedCall(mprotect,
172 "mprotect jit code cache",
173 code_map_->Begin(),
174 code_map_->Size(),
175 kProtCode);
176 CheckedCall(mprotect,
177 "mprotect jit data cache",
178 data_map_->Begin(),
179 data_map_->Size(),
180 kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100181
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000182 VLOG(jit) << "Created jit code cache: initial data size="
183 << PrettySize(initial_data_capacity)
184 << ", initial code size="
185 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800186}
187
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000188JitCodeCache::~JitCodeCache() {}
189
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100190bool JitCodeCache::ContainsPc(const void* ptr) const {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100191 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800192}
193
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000194bool JitCodeCache::ContainsMethod(ArtMethod* method) {
195 MutexLock mu(Thread::Current(), lock_);
196 for (auto& it : method_code_map_) {
197 if (it.second == method) {
198 return true;
199 }
200 }
201 return false;
202}
203
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800204class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100205 public:
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100206 explicit ScopedCodeCacheWrite(MemMap* code_map, bool only_for_tlb_shootdown = false)
207 : ScopedTrace("ScopedCodeCacheWrite"),
208 code_map_(code_map),
209 only_for_tlb_shootdown_(only_for_tlb_shootdown) {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800210 ScopedTrace trace("mprotect all");
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700211 CheckedCall(mprotect,
212 "make code writable",
213 code_map_->Begin(),
214 only_for_tlb_shootdown_ ? kPageSize : code_map_->Size(),
215 kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800216 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100217 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800218 ScopedTrace trace("mprotect code");
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700219 CheckedCall(mprotect,
220 "make code protected",
221 code_map_->Begin(),
222 only_for_tlb_shootdown_ ? kPageSize : code_map_->Size(),
223 kProtCode);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100224 }
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700225
David Sehrd1dbb742017-07-17 11:20:38 -0700226 private:
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100227 MemMap* const code_map_;
228
229 // If we're using ScopedCacheWrite only for TLB shootdown, we limit the scope of mprotect to
230 // one page.
231 const bool only_for_tlb_shootdown_;
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100232
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100233 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
234};
235
236uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100237 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000238 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700239 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000240 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100241 size_t frame_size_in_bytes,
242 size_t core_spill_mask,
243 size_t fp_spill_mask,
244 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000245 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100246 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000247 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700248 Handle<mirror::ObjectArray<mirror::Object>> roots,
249 bool has_should_deoptimize_flag,
250 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100251 uint8_t* result = CommitCodeInternal(self,
252 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000253 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700254 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000255 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100256 frame_size_in_bytes,
257 core_spill_mask,
258 fp_spill_mask,
259 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000260 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100261 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000262 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700263 roots,
264 has_should_deoptimize_flag,
265 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100266 if (result == nullptr) {
267 // Retry.
268 GarbageCollectCache(self);
269 result = CommitCodeInternal(self,
270 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000271 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700272 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000273 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100274 frame_size_in_bytes,
275 core_spill_mask,
276 fp_spill_mask,
277 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000278 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100279 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000280 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700281 roots,
282 has_should_deoptimize_flag,
283 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100284 }
285 return result;
286}
287
288bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
289 bool in_collection = false;
290 while (collection_in_progress_) {
291 in_collection = true;
292 lock_cond_.Wait(self);
293 }
294 return in_collection;
295}
296
297static uintptr_t FromCodeToAllocation(const void* code) {
298 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
299 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
300}
301
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000302static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
303 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
304}
305
306static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
307 // The length of the table is stored just before the stack map (and therefore at the end of
308 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
309 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
310}
311
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800312static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
313 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
314 // pointer.
315 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
316}
317
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000318static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
319 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
320}
321
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000322static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
323 REQUIRES_SHARED(Locks::mutator_lock_) {
324 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800325 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000326 // Put all roots in `roots_data`.
327 for (uint32_t i = 0; i < length; ++i) {
328 ObjPtr<mirror::Object> object = roots->Get(i);
329 if (kIsDebugBuild) {
330 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000331 if (object->IsString()) {
332 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
333 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
334 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
335 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000336 }
337 gc_roots[i] = GcRoot<mirror::Object>(object);
338 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000339}
340
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100341static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000342 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
343 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
344 uint32_t roots = GetNumberOfRoots(data);
345 if (number_of_roots != nullptr) {
346 *number_of_roots = roots;
347 }
348 return data - ComputeRootTableSize(roots);
349}
350
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100351// Use a sentinel for marking entries in the JIT table that have been cleared.
352// This helps diagnosing in case the compiled code tries to wrongly access such
353// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700354static mirror::Class* const weak_sentinel =
355 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100356
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000357// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100358static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
359 IsMarkedVisitor* visitor,
360 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000361 REQUIRES_SHARED(Locks::mutator_lock_) {
362 // This does not need a read barrier because this is called by GC.
363 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100364 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000365 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
366 // Look at the classloader of the class to know if it has been unloaded.
367 // This does not need a read barrier because this is called by GC.
368 mirror::Object* class_loader =
369 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
370 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
371 // The class loader is live, update the entry if the class has moved.
372 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
373 // Note that new_object can be null for CMS and newly allocated objects.
374 if (new_cls != nullptr && new_cls != cls) {
375 *root_ptr = GcRoot<mirror::Class>(new_cls);
376 }
377 } else {
378 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100379 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000380 }
381 }
382}
383
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000384void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
385 MutexLock mu(Thread::Current(), lock_);
386 for (const auto& entry : method_code_map_) {
387 uint32_t number_of_roots = 0;
388 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
389 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
390 for (uint32_t i = 0; i < number_of_roots; ++i) {
391 // This does not need a read barrier because this is called by GC.
392 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100393 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000394 // entry got deleted in a previous sweep.
395 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
396 mirror::Object* new_object = visitor->IsMarked(object);
397 // We know the string is marked because it's a strongly-interned string that
398 // is always alive. The IsMarked implementation of the CMS collector returns
399 // null for newly allocated objects, but we know those haven't moved. Therefore,
400 // only update the entry if we get a different non-null string.
401 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
402 // out of the weak access/creation pause. b/32167580
403 if (new_object != nullptr && new_object != object) {
404 DCHECK(new_object->IsString());
405 roots[i] = GcRoot<mirror::Object>(new_object);
406 }
407 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100408 ProcessWeakClass(
409 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000410 }
411 }
412 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000413 // Walk over inline caches to clear entries containing unloaded classes.
414 for (ProfilingInfo* info : profiling_infos_) {
415 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
416 InlineCache* cache = &info->cache_[i];
417 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100418 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000419 }
420 }
421 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000422}
423
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100424void JitCodeCache::FreeCode(const void* code_ptr) {
425 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000426 // Notify native debugger that we are about to remove the code.
427 // It does nothing if we are not using native debugger.
428 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000429 FreeData(GetRootTable(code_ptr));
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100430 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100431}
432
Mingyao Yang063fc772016-08-02 11:02:54 -0700433void JitCodeCache::FreeAllMethodHeaders(
434 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
435 {
436 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700437 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
Mingyao Yang063fc772016-08-02 11:02:54 -0700438 ->RemoveDependentsWithMethodHeaders(method_headers);
439 }
440
441 // We need to remove entries in method_headers from CHA dependencies
442 // first since once we do FreeCode() below, the memory can be reused
443 // so it's possible for the same method_header to start representing
444 // different compile code.
445 MutexLock mu(Thread::Current(), lock_);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100446 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -0700447 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100448 FreeCode(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700449 }
450}
451
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100452void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800453 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700454 // We use a set to first collect all method_headers whose code need to be
455 // removed. We need to free the underlying code after we remove CHA dependencies
456 // for entries in this set. And it's more efficient to iterate through
457 // the CHA dependency map just once with an unordered_set.
458 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000459 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700460 MutexLock mu(self, lock_);
461 // We do not check if a code cache GC is in progress, as this method comes
462 // with the classlinker_classes_lock_ held, and suspending ourselves could
463 // lead to a deadlock.
464 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100465 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -0700466 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
467 if (alloc.ContainsUnsafe(it->second)) {
468 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
469 it = method_code_map_.erase(it);
470 } else {
471 ++it;
472 }
473 }
474 }
475 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
476 if (alloc.ContainsUnsafe(it->first)) {
477 // Note that the code has already been pushed to method_headers in the loop
478 // above and is going to be removed in FreeCode() below.
479 it = osr_code_map_.erase(it);
480 } else {
481 ++it;
482 }
483 }
484 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
485 ProfilingInfo* info = *it;
486 if (alloc.ContainsUnsafe(info->GetMethod())) {
487 info->GetMethod()->SetProfilingInfo(nullptr);
488 FreeData(reinterpret_cast<uint8_t*>(info));
489 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000490 } else {
491 ++it;
492 }
493 }
494 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700495 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100496}
497
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000498bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
499 return kUseReadBarrier
500 ? self->GetWeakRefAccessEnabled()
501 : is_weak_access_enabled_.LoadSequentiallyConsistent();
502}
503
504void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
505 if (IsWeakAccessEnabled(self)) {
506 return;
507 }
508 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000509 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000510 while (!IsWeakAccessEnabled(self)) {
511 inline_cache_cond_.Wait(self);
512 }
513}
514
515void JitCodeCache::BroadcastForInlineCacheAccess() {
516 Thread* self = Thread::Current();
517 MutexLock mu(self, lock_);
518 inline_cache_cond_.Broadcast(self);
519}
520
521void JitCodeCache::AllowInlineCacheAccess() {
522 DCHECK(!kUseReadBarrier);
523 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
524 BroadcastForInlineCacheAccess();
525}
526
527void JitCodeCache::DisallowInlineCacheAccess() {
528 DCHECK(!kUseReadBarrier);
529 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
530}
531
532void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
533 Handle<mirror::ObjectArray<mirror::Class>> array) {
534 WaitUntilInlineCacheAccessible(Thread::Current());
535 // Note that we don't need to lock `lock_` here, the compiler calling
536 // this method has already ensured the inline cache will not be deleted.
537 for (size_t in_cache = 0, in_array = 0;
538 in_cache < InlineCache::kIndividualCacheSize;
539 ++in_cache) {
540 mirror::Class* object = ic.classes_[in_cache].Read();
541 if (object != nullptr) {
542 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000543 }
544 }
545}
546
Mathieu Chartierf044c222017-05-31 15:27:54 -0700547static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
548 if (was_warm) {
Orion Hodsoncfcc9cf2017-09-29 15:07:27 +0100549 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700550 }
551 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
552 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100553 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
554 // the warmup threshold is 1.
555 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
556 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700557}
558
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100559uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
560 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000561 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700562 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000563 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100564 size_t frame_size_in_bytes,
565 size_t core_spill_mask,
566 size_t fp_spill_mask,
567 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000568 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100569 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000570 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700571 Handle<mirror::ObjectArray<mirror::Object>> roots,
572 bool has_should_deoptimize_flag,
573 const ArenaSet<ArtMethod*>&
574 cha_single_implementation_list) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000575 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100576 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
577 // Ensure the header ends up at expected instruction alignment.
578 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
579 size_t total_size = header_size + code_size;
580
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100581 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100582 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000583 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100584 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000585 ScopedThreadSuspension sts(self, kSuspended);
586 MutexLock mu(self, lock_);
587 WaitForPotentialCollectionToComplete(self);
588 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100589 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000590 memory = AllocateCode(total_size);
591 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000592 return nullptr;
593 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100594 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000595
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100596 std::copy(code, code + code_size, code_ptr);
597 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
598 new (method_header) OatQuickMethodHeader(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000599 code_ptr - stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700600 code_ptr - method_info,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000601 frame_size_in_bytes,
602 core_spill_mask,
603 fp_spill_mask,
604 code_size);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100605 // Flush caches before we remove write permission because some ARMv8 Qualcomm kernels may
606 // trigger a segfault if a page fault occurs when requesting a cache maintenance operation.
607 // This is a kernel bug that we need to work around until affected devices (e.g. Nexus 5X and
608 // 6P) stop being supported or their kernels are fixed.
609 //
610 // For reference, this behavior is caused by this commit:
611 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
612 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
613 reinterpret_cast<char*>(code_ptr + code_size));
Mingyao Yang063fc772016-08-02 11:02:54 -0700614 DCHECK(!Runtime::Current()->IsAotCompiler());
615 if (has_should_deoptimize_flag) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100616 method_header->SetHasShouldDeoptimizeFlag();
Mingyao Yang063fc772016-08-02 11:02:54 -0700617 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100618 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100619
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000620 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100621 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000622 // We need to update the entry point in the runnable state for the instrumentation.
623 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700624 // Need cha_lock_ for checking all single-implementation flags and register
625 // dependencies.
626 MutexLock cha_mu(self, *Locks::cha_lock_);
627 bool single_impl_still_valid = true;
628 for (ArtMethod* single_impl : cha_single_implementation_list) {
629 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700630 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
631 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700632 single_impl_still_valid = false;
Mathieu Chartierf044c222017-05-31 15:27:54 -0700633 ClearMethodCounter(method, /*was_warm*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700634 break;
635 }
636 }
637
638 // Discard the code if any single-implementation assumptions are now invalid.
639 if (!single_impl_still_valid) {
640 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
641 return nullptr;
642 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000643 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800644 << "Should not be using cha on debuggable apps/runs!";
645
Mingyao Yang063fc772016-08-02 11:02:54 -0700646 for (ArtMethod* single_impl : cha_single_implementation_list) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700647 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()->AddDependency(
Mingyao Yang063fc772016-08-02 11:02:54 -0700648 single_impl, method, method_header);
649 }
650
651 // The following needs to be guarded by cha_lock_ also. Otherwise it's
652 // possible that the compiled code is considered invalidated by some class linking,
653 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000654 MutexLock mu(self, lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000655 // Fill the root table before updating the entry point.
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000656 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100657 DCHECK_LE(roots_data, stack_map);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000658 FillRootTable(roots_data, roots);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100659 {
660 // Flush data cache, as compiled code references literals in it.
661 // We also need a TLB shootdown to act as memory barrier across cores.
662 ScopedCodeCacheWrite ccw(code_map_.get(), /* only_for_tlb_shootdown */ true);
663 FlushDataCache(reinterpret_cast<char*>(roots_data),
664 reinterpret_cast<char*>(roots_data + data_size));
665 }
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100666 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000667 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000668 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000669 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100670 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000671 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
672 method, method_header->GetEntryPoint());
673 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000674 if (collection_in_progress_) {
675 // We need to update the live bitmap if there is a GC to ensure it sees this new
676 // code.
677 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
678 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000679 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000680 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100681 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700682 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000683 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
684 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
685 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700686 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
687 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000688 histogram_code_memory_use_.AddValue(code_size);
689 if (code_size > kCodeSizeLogThreshold) {
690 LOG(INFO) << "JIT allocated "
691 << PrettySize(code_size)
692 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700693 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000694 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000695 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100696
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100697 return reinterpret_cast<uint8_t*>(method_header);
698}
699
700size_t JitCodeCache::CodeCacheSize() {
701 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000702 return CodeCacheSizeLocked();
703}
704
Orion Hodsoneced6922017-06-01 10:54:28 +0100705bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
706 MutexLock mu(Thread::Current(), lock_);
707 if (method->IsNative()) {
708 return false;
709 }
710
711 bool in_cache = false;
712 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100713 ScopedCodeCacheWrite ccw(code_map_.get());
Orion Hodsoneced6922017-06-01 10:54:28 +0100714 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
715 if (code_iter->second == method) {
716 if (release_memory) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100717 FreeCode(code_iter->first);
Orion Hodsoneced6922017-06-01 10:54:28 +0100718 }
719 code_iter = method_code_map_.erase(code_iter);
720 in_cache = true;
721 continue;
722 }
723 ++code_iter;
724 }
725 }
726
727 bool osr = false;
728 auto code_map = osr_code_map_.find(method);
729 if (code_map != osr_code_map_.end()) {
730 osr_code_map_.erase(code_map);
731 osr = true;
732 }
733
734 if (!in_cache) {
735 return false;
736 }
737
738 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
739 if (info != nullptr) {
740 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
741 DCHECK(profile != profiling_infos_.end());
742 profiling_infos_.erase(profile);
743 }
744 method->SetProfilingInfo(nullptr);
745 method->ClearCounter();
746 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
747 method, GetQuickToInterpreterBridge());
748 VLOG(jit)
749 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
750 << ArtMethod::PrettyMethod(method) << "@" << method
751 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
752 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
753 return true;
754}
755
Alex Lightdba61482016-12-21 08:20:29 -0800756// This notifies the code cache that the given method has been redefined and that it should remove
757// any cached information it has on the method. All threads must be suspended before calling this
758// method. The compiled code for the method (if there is any) must not be in any threads call stack.
759void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
760 MutexLock mu(Thread::Current(), lock_);
761 if (method->IsNative()) {
762 return;
763 }
764 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
765 if (info != nullptr) {
766 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
767 DCHECK(profile != profiling_infos_.end());
768 profiling_infos_.erase(profile);
769 }
770 method->SetProfilingInfo(nullptr);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100771 ScopedCodeCacheWrite ccw(code_map_.get());
Andreas Gampe39e67382017-05-15 19:26:38 -0700772 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
Alex Lightdba61482016-12-21 08:20:29 -0800773 if (code_iter->second == method) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100774 FreeCode(code_iter->first);
Andreas Gampe39e67382017-05-15 19:26:38 -0700775 code_iter = method_code_map_.erase(code_iter);
776 continue;
Alex Lightdba61482016-12-21 08:20:29 -0800777 }
Andreas Gampe39e67382017-05-15 19:26:38 -0700778 ++code_iter;
Alex Lightdba61482016-12-21 08:20:29 -0800779 }
780 auto code_map = osr_code_map_.find(method);
781 if (code_map != osr_code_map_.end()) {
782 osr_code_map_.erase(code_map);
783 }
784}
785
786// This invalidates old_method. Once this function returns one can no longer use old_method to
787// execute code unless it is fixed up. This fixup will happen later in the process of installing a
788// class redefinition.
789// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
790// shouldn't be used since it is no longer logically in the jit code cache.
791// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
792void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000793 // Native methods have no profiling info and need no special handling from the JIT code cache.
794 if (old_method->IsNative()) {
795 return;
796 }
Alex Lightdba61482016-12-21 08:20:29 -0800797 MutexLock mu(Thread::Current(), lock_);
798 // Update ProfilingInfo to the new one and remove it from the old_method.
799 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
800 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
801 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
802 old_method->SetProfilingInfo(nullptr);
803 // Since the JIT should be paused and all threads suspended by the time this is called these
804 // checks should always pass.
805 DCHECK(!info->IsInUseByCompiler());
806 new_method->SetProfilingInfo(info);
807 info->method_ = new_method;
808 }
809 // Update method_code_map_ to point to the new method.
810 for (auto& it : method_code_map_) {
811 if (it.second == old_method) {
812 it.second = new_method;
813 }
814 }
815 // Update osr_code_map_ to point to the new method.
816 auto code_map = osr_code_map_.find(old_method);
817 if (code_map != osr_code_map_.end()) {
818 osr_code_map_.Put(new_method, code_map->second);
819 osr_code_map_.erase(old_method);
820 }
821}
822
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000823size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000824 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100825}
826
827size_t JitCodeCache::DataCacheSize() {
828 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000829 return DataCacheSizeLocked();
830}
831
832size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000833 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800834}
835
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000836void JitCodeCache::ClearData(Thread* self,
837 uint8_t* stack_map_data,
838 uint8_t* roots_data) {
839 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000840 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000841 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000842}
843
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000844size_t JitCodeCache::ReserveData(Thread* self,
845 size_t stack_map_size,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700846 size_t method_info_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000847 size_t number_of_roots,
848 ArtMethod* method,
849 uint8_t** stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700850 uint8_t** method_info_data,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000851 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000852 size_t table_size = ComputeRootTableSize(number_of_roots);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700853 size_t size = RoundUp(stack_map_size + method_info_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100854 uint8_t* result = nullptr;
855
856 {
857 ScopedThreadSuspension sts(self, kSuspended);
858 MutexLock mu(self, lock_);
859 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000860 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100861 }
862
863 if (result == nullptr) {
864 // Retry.
865 GarbageCollectCache(self);
866 ScopedThreadSuspension sts(self, kSuspended);
867 MutexLock mu(self, lock_);
868 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000869 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100870 }
871
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000872 MutexLock mu(self, lock_);
873 histogram_stack_map_memory_use_.AddValue(size);
874 if (size > kStackMapSizeLogThreshold) {
875 LOG(INFO) << "JIT allocated "
876 << PrettySize(size)
877 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700878 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800879 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000880 if (result != nullptr) {
881 *roots_data = result;
882 *stack_map_data = result + table_size;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700883 *method_info_data = *stack_map_data + stack_map_size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000884 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000885 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000886 } else {
887 *roots_data = nullptr;
888 *stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700889 *method_info_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000890 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000891 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800892}
893
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100894class MarkCodeVisitor FINAL : public StackVisitor {
895 public:
896 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
897 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
898 code_cache_(code_cache_in),
899 bitmap_(code_cache_->GetLiveBitmap()) {}
900
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700901 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100902 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
903 if (method_header == nullptr) {
904 return true;
905 }
906 const void* code = method_header->GetCode();
907 if (code_cache_->ContainsPc(code)) {
908 // Use the atomic set version, as multiple threads are executing this code.
909 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
910 }
911 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800912 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100913
914 private:
915 JitCodeCache* const code_cache_;
916 CodeCacheBitmap* const bitmap_;
917};
918
919class MarkCodeClosure FINAL : public Closure {
920 public:
921 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
922 : code_cache_(code_cache), barrier_(barrier) {}
923
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700924 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800925 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100926 DCHECK(thread == Thread::Current() || thread->IsSuspended());
927 MarkCodeVisitor visitor(thread, code_cache_);
928 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000929 if (kIsDebugBuild) {
930 // The stack walking code queries the side instrumentation stack if it
931 // sees an instrumentation exit pc, so the JIT code of methods in that stack
932 // must have been seen. We sanity check this below.
933 for (const instrumentation::InstrumentationStackFrame& frame
934 : *thread->GetInstrumentationStack()) {
935 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
936 // its stack frame, it is not the method owning return_pc_. We just pass null to
937 // LookupMethodHeader: the method is only checked against in debug builds.
938 OatQuickMethodHeader* method_header =
939 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
940 if (method_header != nullptr) {
941 const void* code = method_header->GetCode();
942 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
943 }
944 }
945 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700946 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800947 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100948
949 private:
950 JitCodeCache* const code_cache_;
951 Barrier* const barrier_;
952};
953
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000954void JitCodeCache::NotifyCollectionDone(Thread* self) {
955 collection_in_progress_ = false;
956 lock_cond_.Broadcast(self);
957}
958
959void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
960 size_t per_space_footprint = new_footprint / 2;
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100961 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000962 DCHECK_EQ(per_space_footprint * 2, new_footprint);
963 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
964 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100965 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000966 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
967 }
968}
969
970bool JitCodeCache::IncreaseCodeCacheCapacity() {
971 if (current_capacity_ == max_capacity_) {
972 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100973 }
974
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000975 // Double the capacity if we're below 1MB, or increase it by 1MB if
976 // we're above.
977 if (current_capacity_ < 1 * MB) {
978 current_capacity_ *= 2;
979 } else {
980 current_capacity_ += 1 * MB;
981 }
982 if (current_capacity_ > max_capacity_) {
983 current_capacity_ = max_capacity_;
984 }
985
Nicolas Geoffray646d6382017-08-09 10:50:00 +0100986 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000987
988 SetFootprintLimit(current_capacity_);
989
990 return true;
991}
992
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000993void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
994 Barrier barrier(0);
995 size_t threads_running_checkpoint = 0;
996 MarkCodeClosure closure(this, &barrier);
997 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
998 // Now that we have run our checkpoint, move to a suspended state and wait
999 // for other threads to run the checkpoint.
1000 ScopedThreadSuspension sts(self, kSuspended);
1001 if (threads_running_checkpoint != 0) {
1002 barrier.Increment(self, threads_running_checkpoint);
1003 }
1004}
1005
Nicolas Geoffray35122442016-03-02 12:05:30 +00001006bool JitCodeCache::ShouldDoFullCollection() {
1007 if (current_capacity_ == max_capacity_) {
1008 // Always do a full collection when the code cache is full.
1009 return true;
1010 } else if (current_capacity_ < kReservedCapacity) {
1011 // Always do partial collection when the code cache size is below the reserved
1012 // capacity.
1013 return false;
1014 } else if (last_collection_increased_code_cache_) {
1015 // This time do a full collection.
1016 return true;
1017 } else {
1018 // This time do a partial collection.
1019 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001020 }
1021}
1022
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001023void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001024 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001025 if (!garbage_collect_code_) {
1026 MutexLock mu(self, lock_);
1027 IncreaseCodeCacheCapacity();
1028 return;
1029 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001030
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001031 // Wait for an existing collection, or let everyone know we are starting one.
1032 {
1033 ScopedThreadSuspension sts(self, kSuspended);
1034 MutexLock mu(self, lock_);
1035 if (WaitForPotentialCollectionToComplete(self)) {
1036 return;
1037 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001038 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001039 live_bitmap_.reset(CodeCacheBitmap::Create(
1040 "code-cache-bitmap",
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001041 reinterpret_cast<uintptr_t>(code_map_->Begin()),
1042 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001043 collection_in_progress_ = true;
1044 }
1045 }
1046
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001047 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001048 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001049 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001050
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001051 bool do_full_collection = false;
1052 {
1053 MutexLock mu(self, lock_);
1054 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001055 }
1056
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001057 VLOG(jit) << "Do "
1058 << (do_full_collection ? "full" : "partial")
1059 << " code cache collection, code="
1060 << PrettySize(CodeCacheSize())
1061 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001062
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001063 DoCollection(self, /* collect_profiling_info */ do_full_collection);
1064
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001065 VLOG(jit) << "After code cache collection, code="
1066 << PrettySize(CodeCacheSize())
1067 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001068
1069 {
1070 MutexLock mu(self, lock_);
1071
1072 // Increase the code cache only when we do partial collections.
1073 // TODO: base this strategy on how full the code cache is?
1074 if (do_full_collection) {
1075 last_collection_increased_code_cache_ = false;
1076 } else {
1077 last_collection_increased_code_cache_ = true;
1078 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001079 }
1080
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001081 bool next_collection_will_be_full = ShouldDoFullCollection();
1082
1083 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001084 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001085 // Save the entry point of methods we have compiled, and update the entry
1086 // point of those methods to the interpreter. If the method is invoked, the
1087 // interpreter will update its entry point to the compiled code and call it.
1088 for (ProfilingInfo* info : profiling_infos_) {
1089 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1090 if (ContainsPc(entry_point)) {
1091 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001092 // Don't call Instrumentation::UpdateMethods, as it can check the declaring
1093 // class of the method. We may be concurrently running a GC which makes accessing
1094 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1095 // checked that the current entry point is JIT compiled code.
1096 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001097 }
1098 }
1099
1100 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
1101 }
1102 live_bitmap_.reset(nullptr);
1103 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001104 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001105 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001106 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001107}
1108
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001109void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001110 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001111 std::unordered_set<OatQuickMethodHeader*> method_headers;
1112 {
1113 MutexLock mu(self, lock_);
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001114 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -07001115 // Iterate over all compiled code and remove entries that are not marked.
1116 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1117 const void* code_ptr = it->first;
1118 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1119 if (GetLiveBitmap()->Test(allocation)) {
1120 ++it;
1121 } else {
1122 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
1123 it = method_code_map_.erase(it);
1124 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001125 }
1126 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001127 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001128}
1129
1130void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001131 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001132 {
1133 MutexLock mu(self, lock_);
1134 if (collect_profiling_info) {
1135 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1136 // Also remove the saved entry point from the ProfilingInfo objects.
1137 for (ProfilingInfo* info : profiling_infos_) {
1138 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001139 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001140 info->GetMethod()->SetProfilingInfo(nullptr);
1141 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001142
1143 if (info->GetSavedEntryPoint() != nullptr) {
1144 info->SetSavedEntryPoint(nullptr);
1145 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001146 // give it a chance to be hot again.
1147 ClearMethodCounter(info->GetMethod(), /*was_warm*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001148 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001149 }
1150 } else if (kIsDebugBuild) {
1151 // Sanity check that the profiling infos do not have a dangling entry point.
1152 for (ProfilingInfo* info : profiling_infos_) {
1153 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001154 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001155 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001156
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001157 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1158 // an entry point is either:
1159 // - an osr compiled code, that will be removed if not in a thread call stack.
1160 // - discarded compiled code, that will be removed if not in a thread call stack.
1161 for (const auto& it : method_code_map_) {
1162 ArtMethod* method = it.second;
1163 const void* code_ptr = it.first;
1164 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1165 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1166 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1167 }
1168 }
1169
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001170 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001171 // on thread stacks).
1172 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001173 }
1174
1175 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001176 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001177
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001178 // At this point, mutator threads are still running, and entrypoints of methods can
1179 // change. We do know they cannot change to a code cache entry that is not marked,
1180 // therefore we can safely remove those entries.
1181 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001182
Nicolas Geoffray35122442016-03-02 12:05:30 +00001183 if (collect_profiling_info) {
1184 MutexLock mu(self, lock_);
1185 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001186 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001187 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001188 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001189 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1190 // that the compiled code would not get revived. As mutator threads run concurrently,
1191 // they may have revived the compiled code, and now we are in the situation where
1192 // a method has compiled code but no ProfilingInfo.
1193 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1194 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001195 if (ContainsPc(ptr) &&
1196 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001197 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001198 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001199 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001200 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001201 return true;
1202 }
1203 return false;
1204 });
1205 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001206 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001207 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001208}
1209
Nicolas Geoffray35122442016-03-02 12:05:30 +00001210bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001211 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001212 // Check that methods we have compiled do have a ProfilingInfo object. We would
1213 // have memory leaks of compiled code otherwise.
1214 for (const auto& it : method_code_map_) {
1215 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001216 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001217 const void* code_ptr = it.first;
1218 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1219 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1220 // If the code is not dead, then we have a problem. Note that this can even
1221 // happen just after a collection, as mutator threads are running in parallel
1222 // and could deoptimize an existing compiled code.
1223 return false;
1224 }
1225 }
1226 }
1227 return true;
1228}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001229
1230OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001231 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1232 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001233 // On Thumb-2, the pc is offset by one.
1234 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001235 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001236 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1237 return nullptr;
1238 }
1239
1240 MutexLock mu(Thread::Current(), lock_);
1241 if (method_code_map_.empty()) {
1242 return nullptr;
1243 }
1244 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1245 --it;
1246
1247 const void* code_ptr = it->first;
1248 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1249 if (!method_header->Contains(pc)) {
1250 return nullptr;
1251 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001252 if (kIsDebugBuild && method != nullptr) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001253 // When we are walking the stack to redefine classes and creating obsolete methods it is
1254 // possible that we might have updated the method_code_map by making this method obsolete in a
1255 // previous frame. Therefore we should just check that the non-obsolete version of this method
1256 // is the one we expect. We change to the non-obsolete versions in the error message since the
1257 // obsolete version of the method might not be fully initialized yet. This situation can only
1258 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
Andreas Gampe06c42a52017-07-26 14:17:14 -07001259 // method and it->second should be identical. (See openjdkjvmti/ti_redefine.cc for more
Alex Light1ebe4fe2017-01-30 14:57:11 -08001260 // information.)
1261 DCHECK_EQ(it->second->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
1262 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
1263 << ArtMethod::PrettyMethod(it->second->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001264 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001265 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001266 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001267}
1268
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001269OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1270 MutexLock mu(Thread::Current(), lock_);
1271 auto it = osr_code_map_.find(method);
1272 if (it == osr_code_map_.end()) {
1273 return nullptr;
1274 }
1275 return OatQuickMethodHeader::FromCodePointer(it->second);
1276}
1277
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001278ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1279 ArtMethod* method,
1280 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001281 bool retry_allocation)
1282 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1283 NO_THREAD_SAFETY_ANALYSIS {
1284 ProfilingInfo* info = nullptr;
1285 if (!retry_allocation) {
1286 // If we are allocating for the interpreter, just try to lock, to avoid
1287 // lock contention with the JIT.
1288 if (lock_.ExclusiveTryLock(self)) {
1289 info = AddProfilingInfoInternal(self, method, entries);
1290 lock_.ExclusiveUnlock(self);
1291 }
1292 } else {
1293 {
1294 MutexLock mu(self, lock_);
1295 info = AddProfilingInfoInternal(self, method, entries);
1296 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001297
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001298 if (info == nullptr) {
1299 GarbageCollectCache(self);
1300 MutexLock mu(self, lock_);
1301 info = AddProfilingInfoInternal(self, method, entries);
1302 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001303 }
1304 return info;
1305}
1306
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001307ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001308 ArtMethod* method,
1309 const std::vector<uint32_t>& entries) {
1310 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001311 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001312 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001313
1314 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001315 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001316 if (info != nullptr) {
1317 return info;
1318 }
1319
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001320 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001321 if (data == nullptr) {
1322 return nullptr;
1323 }
1324 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001325
1326 // Make sure other threads see the data in the profiling info object before the
1327 // store in the ArtMethod's ProfilingInfo pointer.
1328 QuasiAtomic::ThreadFenceRelease();
1329
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001330 method->SetProfilingInfo(info);
1331 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001332 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001333 return info;
1334}
1335
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001336// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1337// is already held.
1338void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1339 if (code_mspace_ == mspace) {
1340 size_t result = code_end_;
1341 code_end_ += increment;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001342 return reinterpret_cast<void*>(result + code_map_->Begin());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001343 } else {
1344 DCHECK_EQ(data_mspace_, mspace);
1345 size_t result = data_end_;
1346 data_end_ += increment;
1347 return reinterpret_cast<void*>(result + data_map_->Begin());
1348 }
1349}
1350
Calin Juravle99629622016-04-19 16:33:46 +01001351void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001352 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001353 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001354 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001355 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001356 for (const ProfilingInfo* info : profiling_infos_) {
1357 ArtMethod* method = info->GetMethod();
1358 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001359 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1360 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001361 // Skip dex files which are not profiled.
1362 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001363 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001364 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001365
1366 // If the method didn't reach the compilation threshold don't save the inline caches.
1367 // They might be incomplete and cause unnecessary deoptimizations.
1368 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1369 if (method->GetCounter() < jit_compile_threshold) {
1370 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001371 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001372 continue;
1373 }
1374
Calin Juravle940eb0c2017-01-30 19:30:44 -08001375 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001376 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001377 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001378 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001379 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001380 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1381 mirror::Class* cls = cache.classes_[k].Read();
1382 if (cls == nullptr) {
1383 break;
1384 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001385
Calin Juravle13439f02017-02-21 01:17:21 -08001386 // Check if the receiver is in the boot class path or if it's in the
1387 // same class loader as the caller. If not, skip it, as there is not
1388 // much we can do during AOT.
1389 if (!cls->IsBootStrapClassLoaded() &&
1390 caller->GetClassLoader() != cls->GetClassLoader()) {
1391 is_missing_types = true;
1392 continue;
1393 }
1394
Calin Juravle4ca70a32017-02-21 16:22:24 -08001395 const DexFile* class_dex_file = nullptr;
1396 dex::TypeIndex type_index;
1397
1398 if (cls->GetDexCache() == nullptr) {
1399 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001400 // Make a best effort to find the type index in the method's dex file.
1401 // We could search all open dex files but that might turn expensive
1402 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001403 class_dex_file = dex_file;
1404 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1405 } else {
1406 class_dex_file = &(cls->GetDexFile());
1407 type_index = cls->GetDexTypeIndex();
1408 }
1409 if (!type_index.IsValid()) {
1410 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001411 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001412 continue;
1413 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001414 if (ContainsElement(dex_base_locations,
1415 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001416 // Only consider classes from the same apk (including multidex).
1417 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001418 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001419 } else {
1420 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001421 }
1422 }
1423 if (!profile_classes.empty()) {
1424 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001425 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001426 }
1427 }
1428 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001429 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001430 }
1431}
1432
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001433uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1434 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001435}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001436
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001437bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1438 MutexLock mu(Thread::Current(), lock_);
1439 return osr_code_map_.find(method) != osr_code_map_.end();
1440}
1441
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001442bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1443 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001444 return false;
1445 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001446
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001447 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001448 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1449 return false;
1450 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001451
Andreas Gampe542451c2016-07-26 09:02:02 -07001452 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001453 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001454 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Jeff Hao00286db2017-05-30 16:53:07 -07001455 // Because the counter is not atomic, there are some rare cases where we may not hit the
1456 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
Mathieu Chartierf044c222017-05-31 15:27:54 -07001457 ClearMethodCounter(method, /*was_warm*/ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001458 return false;
1459 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001460
buzbee454b3b62016-04-07 14:42:47 -07001461 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001462 return false;
1463 }
1464
buzbee454b3b62016-04-07 14:42:47 -07001465 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001466 return true;
1467}
1468
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001469ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001470 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001471 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001472 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001473 if (!info->IncrementInlineUse()) {
1474 // Overflow of inlining uses, just bail.
1475 return nullptr;
1476 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001477 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001478 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001479}
1480
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001481void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001482 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001483 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001484 DCHECK(info != nullptr);
1485 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001486}
1487
buzbee454b3b62016-04-07 14:42:47 -07001488void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001489 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001490 DCHECK(info->IsMethodBeingCompiled(osr));
1491 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001492}
1493
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001494size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1495 MutexLock mu(Thread::Current(), lock_);
1496 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1497}
1498
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001499void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1500 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001501 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001502 if ((profiling_info != nullptr) &&
1503 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1504 // Prevent future uses of the compiled code.
1505 profiling_info->SetSavedEntryPoint(nullptr);
1506 }
1507
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001508 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001509 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001510 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001511 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1512 method, GetQuickToInterpreterBridge());
Mathieu Chartierf044c222017-05-31 15:27:54 -07001513 ClearMethodCounter(method, /*was_warm*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001514 } else {
1515 MutexLock mu(Thread::Current(), lock_);
1516 auto it = osr_code_map_.find(method);
1517 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1518 // Remove the OSR method, to avoid using it again.
1519 osr_code_map_.erase(it);
1520 }
1521 }
1522}
1523
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001524uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1525 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1526 uint8_t* result = reinterpret_cast<uint8_t*>(
1527 mspace_memalign(code_mspace_, alignment, code_size));
1528 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1529 // Ensure the header ends up at expected instruction alignment.
1530 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1531 used_memory_for_code_ += mspace_usable_size(result);
1532 return result;
1533}
1534
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001535void JitCodeCache::FreeCode(uint8_t* code) {
1536 used_memory_for_code_ -= mspace_usable_size(code);
1537 mspace_free(code_mspace_, code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001538}
1539
1540uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1541 void* result = mspace_malloc(data_mspace_, data_size);
1542 used_memory_for_data_ += mspace_usable_size(result);
1543 return reinterpret_cast<uint8_t*>(result);
1544}
1545
1546void JitCodeCache::FreeData(uint8_t* data) {
1547 used_memory_for_data_ -= mspace_usable_size(data);
1548 mspace_free(data_mspace_, data);
1549}
1550
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001551void JitCodeCache::Dump(std::ostream& os) {
1552 MutexLock mu(Thread::Current(), lock_);
1553 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1554 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1555 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1556 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1557 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1558 << "Total number of JIT compilations for on stack replacement: "
1559 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001560 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001561 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1562 histogram_code_memory_use_.PrintMemoryUse(os);
1563 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001564}
1565
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001566} // namespace jit
1567} // namespace art