blob: cd386c06fa48562333aaa5d7bfa7bdfda7a4424b [file] [log] [blame]
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001/*
2 * Copyright 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "jit_code_cache.h"
18
19#include <sstream>
20
Andreas Gampe5629d2d2017-05-15 16:28:13 -070021#include "arch/context.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070022#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070023#include "base/enums.h"
Calin Juravle66f55232015-12-08 15:09:10 +000024#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080025#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010026#include "base/time_utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070027#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000028#include "debugger_interface.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010029#include "entrypoints/runtime_asm_entrypoints.h"
30#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010031#include "gc/scoped_gc_critical_section.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070032#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000033#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000034#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010035#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080036#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080037#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070038#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070039#include "object_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070040#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070041#include "stack.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010042#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080043
44namespace art {
45namespace jit {
46
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010047static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
48static constexpr int kProtData = PROT_READ | PROT_WRITE;
49static constexpr int kProtCode = PROT_READ | PROT_EXEC;
50
Nicolas Geoffray933330a2016-03-16 14:20:06 +000051static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
52static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
53
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010054#define CHECKED_MPROTECT(memory, size, prot) \
55 do { \
56 int rc = mprotect(memory, size, prot); \
57 if (UNLIKELY(rc != 0)) { \
58 errno = rc; \
59 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
60 } \
61 } while (false) \
62
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000063JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
64 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000065 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000066 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080067 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000068 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000069
70 // Generating debug information is mostly for using the 'perf' tool, which does
71 // not work with ashmem.
72 bool use_ashmem = !generate_debug_info;
73 // With 'perf', we want a 1-1 mapping between an address and a method.
74 bool garbage_collect_code = !generate_debug_info;
75
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000076 // We need to have 32 bit offsets from method headers in code cache which point to things
77 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
78 // Ensure we're below 1 GB to be safe.
79 if (max_capacity > 1 * GB) {
80 std::ostringstream oss;
81 oss << "Maxium code cache capacity is limited to 1 GB, "
82 << PrettySize(max_capacity) << " is too big";
83 *error_msg = oss.str();
84 return nullptr;
85 }
86
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080087 std::string error_str;
88 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +000089 // Map in low 4gb to simplify accessing root tables for x86_64.
90 // We could do PC-relative addressing to avoid this problem, but that
91 // would require reserving code and data area before submitting, which
92 // means more windows for the code memory to be RWX.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010093 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +000094 "data-code-cache", nullptr,
95 max_capacity,
96 kProtAll,
97 /* low_4gb */ true,
98 /* reuse */ false,
99 &error_str,
100 use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100101 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800102 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000103 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800104 *error_msg = oss.str();
105 return nullptr;
106 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100107
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000108 // Align both capacities to page size, as that's the unit mspaces use.
109 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
110 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
111
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +0000112 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100113 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000114 size_t data_size = max_capacity / 2;
115 size_t code_size = max_capacity - data_size;
116 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100117 uint8_t* divider = data_map->Begin() + data_size;
118
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000119 MemMap* code_map =
120 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100121 if (code_map == nullptr) {
122 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000123 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100124 *error_msg = oss.str();
125 return nullptr;
126 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100127 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000128 data_size = initial_capacity / 2;
129 code_size = initial_capacity - data_size;
130 DCHECK_EQ(code_size + data_size, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000131 return new JitCodeCache(
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000132 code_map, data_map, code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800133}
134
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000135JitCodeCache::JitCodeCache(MemMap* code_map,
136 MemMap* data_map,
137 size_t initial_code_capacity,
138 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000139 size_t max_capacity,
140 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100141 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000142 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100143 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100144 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000145 data_map_(data_map),
146 max_capacity_(max_capacity),
147 current_capacity_(initial_code_capacity + initial_data_capacity),
148 code_end_(initial_code_capacity),
149 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000150 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000151 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000152 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000153 used_memory_for_data_(0),
154 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000155 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000156 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000157 number_of_collections_(0),
158 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
159 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000160 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
161 is_weak_access_enabled_(true),
162 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100163
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000164 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000165 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
166 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100167
168 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
169 PLOG(FATAL) << "create_mspace_with_base failed";
170 }
171
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000172 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100173
174 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
175 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100176
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000177 VLOG(jit) << "Created jit code cache: initial data size="
178 << PrettySize(initial_data_capacity)
179 << ", initial code size="
180 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800181}
182
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100183bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100184 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800185}
186
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000187bool JitCodeCache::ContainsMethod(ArtMethod* method) {
188 MutexLock mu(Thread::Current(), lock_);
189 for (auto& it : method_code_map_) {
190 if (it.second == method) {
191 return true;
192 }
193 }
194 return false;
195}
196
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800197class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100198 public:
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100199 explicit ScopedCodeCacheWrite(MemMap* code_map, bool only_for_tlb_shootdown = false)
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800200 : ScopedTrace("ScopedCodeCacheWrite"),
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100201 code_map_(code_map),
202 only_for_tlb_shootdown_(only_for_tlb_shootdown) {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800203 ScopedTrace trace("mprotect all");
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100204 CHECKED_MPROTECT(
205 code_map_->Begin(), only_for_tlb_shootdown_ ? kPageSize : code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800206 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100207 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800208 ScopedTrace trace("mprotect code");
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100209 CHECKED_MPROTECT(
210 code_map_->Begin(), only_for_tlb_shootdown_ ? kPageSize : code_map_->Size(), kProtCode);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100211 }
212 private:
213 MemMap* const code_map_;
214
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100215 // If we're using ScopedCacheWrite only for TLB shootdown, we limit the scope of mprotect to
216 // one page.
217 const bool only_for_tlb_shootdown_;
218
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100219 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
220};
221
222uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100223 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000224 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700225 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000226 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100227 size_t frame_size_in_bytes,
228 size_t core_spill_mask,
229 size_t fp_spill_mask,
230 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000231 size_t code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000232 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000233 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700234 Handle<mirror::ObjectArray<mirror::Object>> roots,
235 bool has_should_deoptimize_flag,
236 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100237 uint8_t* result = CommitCodeInternal(self,
238 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000239 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700240 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000241 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100242 frame_size_in_bytes,
243 core_spill_mask,
244 fp_spill_mask,
245 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000246 code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000247 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000248 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700249 roots,
250 has_should_deoptimize_flag,
251 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100252 if (result == nullptr) {
253 // Retry.
254 GarbageCollectCache(self);
255 result = CommitCodeInternal(self,
256 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000257 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700258 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000259 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100260 frame_size_in_bytes,
261 core_spill_mask,
262 fp_spill_mask,
263 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000264 code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000265 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000266 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700267 roots,
268 has_should_deoptimize_flag,
269 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100270 }
271 return result;
272}
273
274bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
275 bool in_collection = false;
276 while (collection_in_progress_) {
277 in_collection = true;
278 lock_cond_.Wait(self);
279 }
280 return in_collection;
281}
282
283static uintptr_t FromCodeToAllocation(const void* code) {
284 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
285 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
286}
287
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000288static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
289 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
290}
291
292static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
293 // The length of the table is stored just before the stack map (and therefore at the end of
294 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
295 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
296}
297
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800298static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
299 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
300 // pointer.
301 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
302}
303
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000304static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
305 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
306}
307
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000308static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
309 REQUIRES_SHARED(Locks::mutator_lock_) {
310 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800311 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000312 // Put all roots in `roots_data`.
313 for (uint32_t i = 0; i < length; ++i) {
314 ObjPtr<mirror::Object> object = roots->Get(i);
315 if (kIsDebugBuild) {
316 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000317 if (object->IsString()) {
318 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
319 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
320 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
321 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000322 }
323 gc_roots[i] = GcRoot<mirror::Object>(object);
324 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000325}
326
327static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
328 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
329 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
330 uint32_t roots = GetNumberOfRoots(data);
331 if (number_of_roots != nullptr) {
332 *number_of_roots = roots;
333 }
334 return data - ComputeRootTableSize(roots);
335}
336
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100337// Use a sentinel for marking entries in the JIT table that have been cleared.
338// This helps diagnosing in case the compiled code tries to wrongly access such
339// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700340static mirror::Class* const weak_sentinel =
341 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100342
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000343// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100344static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
345 IsMarkedVisitor* visitor,
346 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000347 REQUIRES_SHARED(Locks::mutator_lock_) {
348 // This does not need a read barrier because this is called by GC.
349 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100350 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000351 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
352 // Look at the classloader of the class to know if it has been unloaded.
353 // This does not need a read barrier because this is called by GC.
354 mirror::Object* class_loader =
355 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
356 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
357 // The class loader is live, update the entry if the class has moved.
358 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
359 // Note that new_object can be null for CMS and newly allocated objects.
360 if (new_cls != nullptr && new_cls != cls) {
361 *root_ptr = GcRoot<mirror::Class>(new_cls);
362 }
363 } else {
364 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100365 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000366 }
367 }
368}
369
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000370void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
371 MutexLock mu(Thread::Current(), lock_);
372 for (const auto& entry : method_code_map_) {
373 uint32_t number_of_roots = 0;
374 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
375 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
376 for (uint32_t i = 0; i < number_of_roots; ++i) {
377 // This does not need a read barrier because this is called by GC.
378 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100379 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000380 // entry got deleted in a previous sweep.
381 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
382 mirror::Object* new_object = visitor->IsMarked(object);
383 // We know the string is marked because it's a strongly-interned string that
384 // is always alive. The IsMarked implementation of the CMS collector returns
385 // null for newly allocated objects, but we know those haven't moved. Therefore,
386 // only update the entry if we get a different non-null string.
387 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
388 // out of the weak access/creation pause. b/32167580
389 if (new_object != nullptr && new_object != object) {
390 DCHECK(new_object->IsString());
391 roots[i] = GcRoot<mirror::Object>(new_object);
392 }
393 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100394 ProcessWeakClass(
395 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000396 }
397 }
398 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000399 // Walk over inline caches to clear entries containing unloaded classes.
400 for (ProfilingInfo* info : profiling_infos_) {
401 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
402 InlineCache* cache = &info->cache_[i];
403 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100404 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000405 }
406 }
407 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000408}
409
Mingyao Yang063fc772016-08-02 11:02:54 -0700410void JitCodeCache::FreeCode(const void* code_ptr) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100411 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000412 // Notify native debugger that we are about to remove the code.
413 // It does nothing if we are not using native debugger.
414 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000415 FreeData(GetRootTable(code_ptr));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000416 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100417}
418
Mingyao Yang063fc772016-08-02 11:02:54 -0700419void JitCodeCache::FreeAllMethodHeaders(
420 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
421 {
422 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
423 Runtime::Current()->GetClassHierarchyAnalysis()
424 ->RemoveDependentsWithMethodHeaders(method_headers);
425 }
426
427 // We need to remove entries in method_headers from CHA dependencies
428 // first since once we do FreeCode() below, the memory can be reused
429 // so it's possible for the same method_header to start representing
430 // different compile code.
431 MutexLock mu(Thread::Current(), lock_);
432 ScopedCodeCacheWrite scc(code_map_.get());
433 for (const OatQuickMethodHeader* method_header : method_headers) {
434 FreeCode(method_header->GetCode());
435 }
436}
437
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100438void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800439 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700440 // We use a set to first collect all method_headers whose code need to be
441 // removed. We need to free the underlying code after we remove CHA dependencies
442 // for entries in this set. And it's more efficient to iterate through
443 // the CHA dependency map just once with an unordered_set.
444 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000445 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700446 MutexLock mu(self, lock_);
447 // We do not check if a code cache GC is in progress, as this method comes
448 // with the classlinker_classes_lock_ held, and suspending ourselves could
449 // lead to a deadlock.
450 {
451 ScopedCodeCacheWrite scc(code_map_.get());
452 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
453 if (alloc.ContainsUnsafe(it->second)) {
454 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
455 it = method_code_map_.erase(it);
456 } else {
457 ++it;
458 }
459 }
460 }
461 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
462 if (alloc.ContainsUnsafe(it->first)) {
463 // Note that the code has already been pushed to method_headers in the loop
464 // above and is going to be removed in FreeCode() below.
465 it = osr_code_map_.erase(it);
466 } else {
467 ++it;
468 }
469 }
470 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
471 ProfilingInfo* info = *it;
472 if (alloc.ContainsUnsafe(info->GetMethod())) {
473 info->GetMethod()->SetProfilingInfo(nullptr);
474 FreeData(reinterpret_cast<uint8_t*>(info));
475 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000476 } else {
477 ++it;
478 }
479 }
480 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700481 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100482}
483
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000484bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
485 return kUseReadBarrier
486 ? self->GetWeakRefAccessEnabled()
487 : is_weak_access_enabled_.LoadSequentiallyConsistent();
488}
489
490void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
491 if (IsWeakAccessEnabled(self)) {
492 return;
493 }
494 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000495 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000496 while (!IsWeakAccessEnabled(self)) {
497 inline_cache_cond_.Wait(self);
498 }
499}
500
501void JitCodeCache::BroadcastForInlineCacheAccess() {
502 Thread* self = Thread::Current();
503 MutexLock mu(self, lock_);
504 inline_cache_cond_.Broadcast(self);
505}
506
507void JitCodeCache::AllowInlineCacheAccess() {
508 DCHECK(!kUseReadBarrier);
509 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
510 BroadcastForInlineCacheAccess();
511}
512
513void JitCodeCache::DisallowInlineCacheAccess() {
514 DCHECK(!kUseReadBarrier);
515 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
516}
517
518void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
519 Handle<mirror::ObjectArray<mirror::Class>> array) {
520 WaitUntilInlineCacheAccessible(Thread::Current());
521 // Note that we don't need to lock `lock_` here, the compiler calling
522 // this method has already ensured the inline cache will not be deleted.
523 for (size_t in_cache = 0, in_array = 0;
524 in_cache < InlineCache::kIndividualCacheSize;
525 ++in_cache) {
526 mirror::Class* object = ic.classes_[in_cache].Read();
527 if (object != nullptr) {
528 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000529 }
530 }
531}
532
Mathieu Chartierf044c222017-05-31 15:27:54 -0700533static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
534 if (was_warm) {
535 method->AddAccessFlags(kAccPreviouslyWarm);
536 }
537 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
538 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100539 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
540 // the warmup threshold is 1.
541 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
542 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700543}
544
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100545uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
546 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000547 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700548 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000549 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100550 size_t frame_size_in_bytes,
551 size_t core_spill_mask,
552 size_t fp_spill_mask,
553 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000554 size_t code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000555 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000556 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700557 Handle<mirror::ObjectArray<mirror::Object>> roots,
558 bool has_should_deoptimize_flag,
559 const ArenaSet<ArtMethod*>&
560 cha_single_implementation_list) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000561 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100562 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
563 // Ensure the header ends up at expected instruction alignment.
564 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
565 size_t total_size = header_size + code_size;
566
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100567 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100568 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000569 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100570 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000571 ScopedThreadSuspension sts(self, kSuspended);
572 MutexLock mu(self, lock_);
573 WaitForPotentialCollectionToComplete(self);
574 {
575 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000576 memory = AllocateCode(total_size);
577 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000578 return nullptr;
579 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000580 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000581
582 std::copy(code, code + code_size, code_ptr);
583 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
584 new (method_header) OatQuickMethodHeader(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000585 code_ptr - stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700586 code_ptr - method_info,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000587 frame_size_in_bytes,
588 core_spill_mask,
589 fp_spill_mask,
590 code_size);
Kevin Brodskyb93ce182016-12-15 14:23:09 +0000591 // Flush caches before we remove write permission because some ARMv8 Qualcomm kernels may
592 // trigger a segfault if a page fault occurs when requesting a cache maintenance operation.
593 // This is a kernel bug that we need to work around until affected devices (e.g. Nexus 5X and
594 // 6P) stop being supported or their kernels are fixed.
Artem Udovichenkob18a6692016-11-17 10:51:58 +0300595 //
Kevin Brodskyb93ce182016-12-15 14:23:09 +0000596 // For reference, this behavior is caused by this commit:
597 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
Artem Udovichenkob18a6692016-11-17 10:51:58 +0300598 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
599 reinterpret_cast<char*>(code_ptr + code_size));
Mingyao Yang063fc772016-08-02 11:02:54 -0700600 DCHECK(!Runtime::Current()->IsAotCompiler());
601 if (has_should_deoptimize_flag) {
602 method_header->SetHasShouldDeoptimizeFlag();
603 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100604 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100605
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000606 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100607 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000608 // We need to update the entry point in the runnable state for the instrumentation.
609 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700610 // Need cha_lock_ for checking all single-implementation flags and register
611 // dependencies.
612 MutexLock cha_mu(self, *Locks::cha_lock_);
613 bool single_impl_still_valid = true;
614 for (ArtMethod* single_impl : cha_single_implementation_list) {
615 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700616 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
617 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700618 single_impl_still_valid = false;
Mathieu Chartierf044c222017-05-31 15:27:54 -0700619 ClearMethodCounter(method, /*was_warm*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700620 break;
621 }
622 }
623
624 // Discard the code if any single-implementation assumptions are now invalid.
625 if (!single_impl_still_valid) {
626 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
627 return nullptr;
628 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000629 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800630 << "Should not be using cha on debuggable apps/runs!";
631
Mingyao Yang063fc772016-08-02 11:02:54 -0700632 for (ArtMethod* single_impl : cha_single_implementation_list) {
633 Runtime::Current()->GetClassHierarchyAnalysis()->AddDependency(
634 single_impl, method, method_header);
635 }
636
637 // The following needs to be guarded by cha_lock_ also. Otherwise it's
638 // possible that the compiled code is considered invalidated by some class linking,
639 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000640 MutexLock mu(self, lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000641 // Fill the root table before updating the entry point.
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000642 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100643 DCHECK_LE(roots_data, stack_map);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000644 FillRootTable(roots_data, roots);
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100645 {
646 // Flush data cache, as compiled code references literals in it.
647 // We also need a TLB shootdown to act as memory barrier across cores.
648 ScopedCodeCacheWrite ccw(code_map_.get(), /* only_for_tlb_shootdown */ true);
649 FlushDataCache(reinterpret_cast<char*>(roots_data),
650 reinterpret_cast<char*>(roots_data + data_size));
651 }
652 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000653 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000654 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000655 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100656 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000657 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
658 method, method_header->GetEntryPoint());
659 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000660 if (collection_in_progress_) {
661 // We need to update the live bitmap if there is a GC to ensure it sees this new
662 // code.
663 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
664 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000665 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000666 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100667 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700668 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000669 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
670 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
671 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700672 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
673 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000674 histogram_code_memory_use_.AddValue(code_size);
675 if (code_size > kCodeSizeLogThreshold) {
676 LOG(INFO) << "JIT allocated "
677 << PrettySize(code_size)
678 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700679 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000680 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000681 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100682
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100683 return reinterpret_cast<uint8_t*>(method_header);
684}
685
686size_t JitCodeCache::CodeCacheSize() {
687 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000688 return CodeCacheSizeLocked();
689}
690
Orion Hodsoneced6922017-06-01 10:54:28 +0100691bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
692 MutexLock mu(Thread::Current(), lock_);
693 if (method->IsNative()) {
694 return false;
695 }
696
697 bool in_cache = false;
698 {
699 ScopedCodeCacheWrite ccw(code_map_.get());
700 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
701 if (code_iter->second == method) {
702 if (release_memory) {
703 FreeCode(code_iter->first);
704 }
705 code_iter = method_code_map_.erase(code_iter);
706 in_cache = true;
707 continue;
708 }
709 ++code_iter;
710 }
711 }
712
713 bool osr = false;
714 auto code_map = osr_code_map_.find(method);
715 if (code_map != osr_code_map_.end()) {
716 osr_code_map_.erase(code_map);
717 osr = true;
718 }
719
720 if (!in_cache) {
721 return false;
722 }
723
724 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
725 if (info != nullptr) {
726 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
727 DCHECK(profile != profiling_infos_.end());
728 profiling_infos_.erase(profile);
729 }
730 method->SetProfilingInfo(nullptr);
731 method->ClearCounter();
732 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
733 method, GetQuickToInterpreterBridge());
734 VLOG(jit)
735 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
736 << ArtMethod::PrettyMethod(method) << "@" << method
737 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
738 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
739 return true;
740}
741
Alex Lightdba61482016-12-21 08:20:29 -0800742// This notifies the code cache that the given method has been redefined and that it should remove
743// any cached information it has on the method. All threads must be suspended before calling this
744// method. The compiled code for the method (if there is any) must not be in any threads call stack.
745void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
746 MutexLock mu(Thread::Current(), lock_);
747 if (method->IsNative()) {
748 return;
749 }
750 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
751 if (info != nullptr) {
752 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
753 DCHECK(profile != profiling_infos_.end());
754 profiling_infos_.erase(profile);
755 }
756 method->SetProfilingInfo(nullptr);
757 ScopedCodeCacheWrite ccw(code_map_.get());
Andreas Gampe39e67382017-05-15 19:26:38 -0700758 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
Alex Lightdba61482016-12-21 08:20:29 -0800759 if (code_iter->second == method) {
760 FreeCode(code_iter->first);
Andreas Gampe39e67382017-05-15 19:26:38 -0700761 code_iter = method_code_map_.erase(code_iter);
762 continue;
Alex Lightdba61482016-12-21 08:20:29 -0800763 }
Andreas Gampe39e67382017-05-15 19:26:38 -0700764 ++code_iter;
Alex Lightdba61482016-12-21 08:20:29 -0800765 }
766 auto code_map = osr_code_map_.find(method);
767 if (code_map != osr_code_map_.end()) {
768 osr_code_map_.erase(code_map);
769 }
770}
771
772// This invalidates old_method. Once this function returns one can no longer use old_method to
773// execute code unless it is fixed up. This fixup will happen later in the process of installing a
774// class redefinition.
775// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
776// shouldn't be used since it is no longer logically in the jit code cache.
777// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
778void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000779 // Native methods have no profiling info and need no special handling from the JIT code cache.
780 if (old_method->IsNative()) {
781 return;
782 }
Alex Lightdba61482016-12-21 08:20:29 -0800783 MutexLock mu(Thread::Current(), lock_);
784 // Update ProfilingInfo to the new one and remove it from the old_method.
785 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
786 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
787 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
788 old_method->SetProfilingInfo(nullptr);
789 // Since the JIT should be paused and all threads suspended by the time this is called these
790 // checks should always pass.
791 DCHECK(!info->IsInUseByCompiler());
792 new_method->SetProfilingInfo(info);
793 info->method_ = new_method;
794 }
795 // Update method_code_map_ to point to the new method.
796 for (auto& it : method_code_map_) {
797 if (it.second == old_method) {
798 it.second = new_method;
799 }
800 }
801 // Update osr_code_map_ to point to the new method.
802 auto code_map = osr_code_map_.find(old_method);
803 if (code_map != osr_code_map_.end()) {
804 osr_code_map_.Put(new_method, code_map->second);
805 osr_code_map_.erase(old_method);
806 }
807}
808
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000809size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000810 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100811}
812
813size_t JitCodeCache::DataCacheSize() {
814 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000815 return DataCacheSizeLocked();
816}
817
818size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000819 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800820}
821
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000822void JitCodeCache::ClearData(Thread* self,
823 uint8_t* stack_map_data,
824 uint8_t* roots_data) {
825 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000826 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000827 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000828}
829
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000830size_t JitCodeCache::ReserveData(Thread* self,
831 size_t stack_map_size,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700832 size_t method_info_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000833 size_t number_of_roots,
834 ArtMethod* method,
835 uint8_t** stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700836 uint8_t** method_info_data,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000837 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000838 size_t table_size = ComputeRootTableSize(number_of_roots);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700839 size_t size = RoundUp(stack_map_size + method_info_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100840 uint8_t* result = nullptr;
841
842 {
843 ScopedThreadSuspension sts(self, kSuspended);
844 MutexLock mu(self, lock_);
845 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000846 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100847 }
848
849 if (result == nullptr) {
850 // Retry.
851 GarbageCollectCache(self);
852 ScopedThreadSuspension sts(self, kSuspended);
853 MutexLock mu(self, lock_);
854 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000855 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100856 }
857
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000858 MutexLock mu(self, lock_);
859 histogram_stack_map_memory_use_.AddValue(size);
860 if (size > kStackMapSizeLogThreshold) {
861 LOG(INFO) << "JIT allocated "
862 << PrettySize(size)
863 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700864 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800865 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000866 if (result != nullptr) {
867 *roots_data = result;
868 *stack_map_data = result + table_size;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700869 *method_info_data = *stack_map_data + stack_map_size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000870 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000871 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000872 } else {
873 *roots_data = nullptr;
874 *stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700875 *method_info_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000876 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000877 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800878}
879
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100880class MarkCodeVisitor FINAL : public StackVisitor {
881 public:
882 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
883 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
884 code_cache_(code_cache_in),
885 bitmap_(code_cache_->GetLiveBitmap()) {}
886
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700887 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100888 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
889 if (method_header == nullptr) {
890 return true;
891 }
892 const void* code = method_header->GetCode();
893 if (code_cache_->ContainsPc(code)) {
894 // Use the atomic set version, as multiple threads are executing this code.
895 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
896 }
897 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800898 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100899
900 private:
901 JitCodeCache* const code_cache_;
902 CodeCacheBitmap* const bitmap_;
903};
904
905class MarkCodeClosure FINAL : public Closure {
906 public:
907 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
908 : code_cache_(code_cache), barrier_(barrier) {}
909
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700910 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800911 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100912 DCHECK(thread == Thread::Current() || thread->IsSuspended());
913 MarkCodeVisitor visitor(thread, code_cache_);
914 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000915 if (kIsDebugBuild) {
916 // The stack walking code queries the side instrumentation stack if it
917 // sees an instrumentation exit pc, so the JIT code of methods in that stack
918 // must have been seen. We sanity check this below.
919 for (const instrumentation::InstrumentationStackFrame& frame
920 : *thread->GetInstrumentationStack()) {
921 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
922 // its stack frame, it is not the method owning return_pc_. We just pass null to
923 // LookupMethodHeader: the method is only checked against in debug builds.
924 OatQuickMethodHeader* method_header =
925 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
926 if (method_header != nullptr) {
927 const void* code = method_header->GetCode();
928 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
929 }
930 }
931 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700932 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800933 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100934
935 private:
936 JitCodeCache* const code_cache_;
937 Barrier* const barrier_;
938};
939
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000940void JitCodeCache::NotifyCollectionDone(Thread* self) {
941 collection_in_progress_ = false;
942 lock_cond_.Broadcast(self);
943}
944
945void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
946 size_t per_space_footprint = new_footprint / 2;
947 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
948 DCHECK_EQ(per_space_footprint * 2, new_footprint);
949 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
950 {
951 ScopedCodeCacheWrite scc(code_map_.get());
952 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
953 }
954}
955
956bool JitCodeCache::IncreaseCodeCacheCapacity() {
957 if (current_capacity_ == max_capacity_) {
958 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100959 }
960
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000961 // Double the capacity if we're below 1MB, or increase it by 1MB if
962 // we're above.
963 if (current_capacity_ < 1 * MB) {
964 current_capacity_ *= 2;
965 } else {
966 current_capacity_ += 1 * MB;
967 }
968 if (current_capacity_ > max_capacity_) {
969 current_capacity_ = max_capacity_;
970 }
971
972 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
973 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
974 }
975
976 SetFootprintLimit(current_capacity_);
977
978 return true;
979}
980
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000981void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
982 Barrier barrier(0);
983 size_t threads_running_checkpoint = 0;
984 MarkCodeClosure closure(this, &barrier);
985 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
986 // Now that we have run our checkpoint, move to a suspended state and wait
987 // for other threads to run the checkpoint.
988 ScopedThreadSuspension sts(self, kSuspended);
989 if (threads_running_checkpoint != 0) {
990 barrier.Increment(self, threads_running_checkpoint);
991 }
992}
993
Nicolas Geoffray35122442016-03-02 12:05:30 +0000994bool JitCodeCache::ShouldDoFullCollection() {
995 if (current_capacity_ == max_capacity_) {
996 // Always do a full collection when the code cache is full.
997 return true;
998 } else if (current_capacity_ < kReservedCapacity) {
999 // Always do partial collection when the code cache size is below the reserved
1000 // capacity.
1001 return false;
1002 } else if (last_collection_increased_code_cache_) {
1003 // This time do a full collection.
1004 return true;
1005 } else {
1006 // This time do a partial collection.
1007 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001008 }
1009}
1010
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001011void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001012 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001013 if (!garbage_collect_code_) {
1014 MutexLock mu(self, lock_);
1015 IncreaseCodeCacheCapacity();
1016 return;
1017 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001018
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001019 // Wait for an existing collection, or let everyone know we are starting one.
1020 {
1021 ScopedThreadSuspension sts(self, kSuspended);
1022 MutexLock mu(self, lock_);
1023 if (WaitForPotentialCollectionToComplete(self)) {
1024 return;
1025 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001026 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001027 live_bitmap_.reset(CodeCacheBitmap::Create(
1028 "code-cache-bitmap",
1029 reinterpret_cast<uintptr_t>(code_map_->Begin()),
1030 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001031 collection_in_progress_ = true;
1032 }
1033 }
1034
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001035 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001036 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001037 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001038
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001039 bool do_full_collection = false;
1040 {
1041 MutexLock mu(self, lock_);
1042 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001043 }
1044
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001045 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
1046 LOG(INFO) << "Do "
1047 << (do_full_collection ? "full" : "partial")
1048 << " code cache collection, code="
1049 << PrettySize(CodeCacheSize())
1050 << ", data=" << PrettySize(DataCacheSize());
1051 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001052
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001053 DoCollection(self, /* collect_profiling_info */ do_full_collection);
1054
1055 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
1056 LOG(INFO) << "After code cache collection, code="
1057 << PrettySize(CodeCacheSize())
1058 << ", data=" << PrettySize(DataCacheSize());
1059 }
1060
1061 {
1062 MutexLock mu(self, lock_);
1063
1064 // Increase the code cache only when we do partial collections.
1065 // TODO: base this strategy on how full the code cache is?
1066 if (do_full_collection) {
1067 last_collection_increased_code_cache_ = false;
1068 } else {
1069 last_collection_increased_code_cache_ = true;
1070 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001071 }
1072
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001073 bool next_collection_will_be_full = ShouldDoFullCollection();
1074
1075 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001076 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001077 // Save the entry point of methods we have compiled, and update the entry
1078 // point of those methods to the interpreter. If the method is invoked, the
1079 // interpreter will update its entry point to the compiled code and call it.
1080 for (ProfilingInfo* info : profiling_infos_) {
1081 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1082 if (ContainsPc(entry_point)) {
1083 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001084 // Don't call Instrumentation::UpdateMethods, as it can check the declaring
1085 // class of the method. We may be concurrently running a GC which makes accessing
1086 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1087 // checked that the current entry point is JIT compiled code.
1088 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001089 }
1090 }
1091
1092 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
1093 }
1094 live_bitmap_.reset(nullptr);
1095 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001096 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001097 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001098 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001099}
1100
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001101void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001102 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001103 std::unordered_set<OatQuickMethodHeader*> method_headers;
1104 {
1105 MutexLock mu(self, lock_);
1106 ScopedCodeCacheWrite scc(code_map_.get());
1107 // Iterate over all compiled code and remove entries that are not marked.
1108 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1109 const void* code_ptr = it->first;
1110 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1111 if (GetLiveBitmap()->Test(allocation)) {
1112 ++it;
1113 } else {
1114 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
1115 it = method_code_map_.erase(it);
1116 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001117 }
1118 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001119 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001120}
1121
1122void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001123 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001124 {
1125 MutexLock mu(self, lock_);
1126 if (collect_profiling_info) {
1127 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1128 // Also remove the saved entry point from the ProfilingInfo objects.
1129 for (ProfilingInfo* info : profiling_infos_) {
1130 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001131 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001132 info->GetMethod()->SetProfilingInfo(nullptr);
1133 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001134
1135 if (info->GetSavedEntryPoint() != nullptr) {
1136 info->SetSavedEntryPoint(nullptr);
1137 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001138 // give it a chance to be hot again.
1139 ClearMethodCounter(info->GetMethod(), /*was_warm*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001140 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001141 }
1142 } else if (kIsDebugBuild) {
1143 // Sanity check that the profiling infos do not have a dangling entry point.
1144 for (ProfilingInfo* info : profiling_infos_) {
1145 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001146 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001147 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001148
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001149 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1150 // an entry point is either:
1151 // - an osr compiled code, that will be removed if not in a thread call stack.
1152 // - discarded compiled code, that will be removed if not in a thread call stack.
1153 for (const auto& it : method_code_map_) {
1154 ArtMethod* method = it.second;
1155 const void* code_ptr = it.first;
1156 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1157 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1158 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1159 }
1160 }
1161
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001162 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001163 // on thread stacks).
1164 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001165 }
1166
1167 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001168 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001169
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001170 // At this point, mutator threads are still running, and entrypoints of methods can
1171 // change. We do know they cannot change to a code cache entry that is not marked,
1172 // therefore we can safely remove those entries.
1173 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001174
Nicolas Geoffray35122442016-03-02 12:05:30 +00001175 if (collect_profiling_info) {
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +01001176 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001177 MutexLock mu(self, lock_);
1178 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001179 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001180 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001181 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001182 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1183 // that the compiled code would not get revived. As mutator threads run concurrently,
1184 // they may have revived the compiled code, and now we are in the situation where
1185 // a method has compiled code but no ProfilingInfo.
1186 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1187 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001188 if (ContainsPc(ptr) &&
1189 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001190 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001191 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001192 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001193 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001194 return true;
1195 }
1196 return false;
1197 });
1198 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001199 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001200 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001201}
1202
Nicolas Geoffray35122442016-03-02 12:05:30 +00001203bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001204 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001205 // Check that methods we have compiled do have a ProfilingInfo object. We would
1206 // have memory leaks of compiled code otherwise.
1207 for (const auto& it : method_code_map_) {
1208 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001209 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001210 const void* code_ptr = it.first;
1211 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1212 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1213 // If the code is not dead, then we have a problem. Note that this can even
1214 // happen just after a collection, as mutator threads are running in parallel
1215 // and could deoptimize an existing compiled code.
1216 return false;
1217 }
1218 }
1219 }
1220 return true;
1221}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001222
1223OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
1224 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
1225 if (kRuntimeISA == kArm) {
1226 // On Thumb-2, the pc is offset by one.
1227 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001228 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001229 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1230 return nullptr;
1231 }
1232
1233 MutexLock mu(Thread::Current(), lock_);
1234 if (method_code_map_.empty()) {
1235 return nullptr;
1236 }
1237 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1238 --it;
1239
1240 const void* code_ptr = it->first;
1241 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1242 if (!method_header->Contains(pc)) {
1243 return nullptr;
1244 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001245 if (kIsDebugBuild && method != nullptr) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001246 // When we are walking the stack to redefine classes and creating obsolete methods it is
1247 // possible that we might have updated the method_code_map by making this method obsolete in a
1248 // previous frame. Therefore we should just check that the non-obsolete version of this method
1249 // is the one we expect. We change to the non-obsolete versions in the error message since the
1250 // obsolete version of the method might not be fully initialized yet. This situation can only
1251 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
1252 // method and it->second should be identical. (See runtime/openjdkjvmti/ti_redefine.cc for more
1253 // information.)
1254 DCHECK_EQ(it->second->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
1255 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
1256 << ArtMethod::PrettyMethod(it->second->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001257 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001258 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001259 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001260}
1261
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001262OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1263 MutexLock mu(Thread::Current(), lock_);
1264 auto it = osr_code_map_.find(method);
1265 if (it == osr_code_map_.end()) {
1266 return nullptr;
1267 }
1268 return OatQuickMethodHeader::FromCodePointer(it->second);
1269}
1270
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001271ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1272 ArtMethod* method,
1273 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001274 bool retry_allocation)
1275 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1276 NO_THREAD_SAFETY_ANALYSIS {
1277 ProfilingInfo* info = nullptr;
1278 if (!retry_allocation) {
1279 // If we are allocating for the interpreter, just try to lock, to avoid
1280 // lock contention with the JIT.
1281 if (lock_.ExclusiveTryLock(self)) {
1282 info = AddProfilingInfoInternal(self, method, entries);
1283 lock_.ExclusiveUnlock(self);
1284 }
1285 } else {
1286 {
1287 MutexLock mu(self, lock_);
1288 info = AddProfilingInfoInternal(self, method, entries);
1289 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001290
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001291 if (info == nullptr) {
1292 GarbageCollectCache(self);
1293 MutexLock mu(self, lock_);
1294 info = AddProfilingInfoInternal(self, method, entries);
1295 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001296 }
1297 return info;
1298}
1299
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001300ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001301 ArtMethod* method,
1302 const std::vector<uint32_t>& entries) {
1303 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001304 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001305 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001306
1307 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001308 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001309 if (info != nullptr) {
1310 return info;
1311 }
1312
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001313 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001314 if (data == nullptr) {
1315 return nullptr;
1316 }
1317 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001318
1319 // Make sure other threads see the data in the profiling info object before the
1320 // store in the ArtMethod's ProfilingInfo pointer.
1321 QuasiAtomic::ThreadFenceRelease();
1322
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001323 method->SetProfilingInfo(info);
1324 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001325 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001326 return info;
1327}
1328
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001329// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1330// is already held.
1331void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1332 if (code_mspace_ == mspace) {
1333 size_t result = code_end_;
1334 code_end_ += increment;
1335 return reinterpret_cast<void*>(result + code_map_->Begin());
1336 } else {
1337 DCHECK_EQ(data_mspace_, mspace);
1338 size_t result = data_end_;
1339 data_end_ += increment;
1340 return reinterpret_cast<void*>(result + data_map_->Begin());
1341 }
1342}
1343
Calin Juravle99629622016-04-19 16:33:46 +01001344void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001345 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001346 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001347 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001348 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001349 for (const ProfilingInfo* info : profiling_infos_) {
1350 ArtMethod* method = info->GetMethod();
1351 const DexFile* dex_file = method->GetDexFile();
Calin Juravle940eb0c2017-01-30 19:30:44 -08001352 if (!ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
1353 // Skip dex files which are not profiled.
1354 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001355 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001356 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001357
1358 // If the method didn't reach the compilation threshold don't save the inline caches.
1359 // They might be incomplete and cause unnecessary deoptimizations.
1360 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1361 if (method->GetCounter() < jit_compile_threshold) {
1362 methods.emplace_back(/*ProfileMethodInfo*/
1363 dex_file, method->GetDexMethodIndex(), inline_caches);
1364 continue;
1365 }
1366
Calin Juravle940eb0c2017-01-30 19:30:44 -08001367 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001368 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001369 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001370 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001371 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001372 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1373 mirror::Class* cls = cache.classes_[k].Read();
1374 if (cls == nullptr) {
1375 break;
1376 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001377
Calin Juravle13439f02017-02-21 01:17:21 -08001378 // Check if the receiver is in the boot class path or if it's in the
1379 // same class loader as the caller. If not, skip it, as there is not
1380 // much we can do during AOT.
1381 if (!cls->IsBootStrapClassLoaded() &&
1382 caller->GetClassLoader() != cls->GetClassLoader()) {
1383 is_missing_types = true;
1384 continue;
1385 }
1386
Calin Juravle4ca70a32017-02-21 16:22:24 -08001387 const DexFile* class_dex_file = nullptr;
1388 dex::TypeIndex type_index;
1389
1390 if (cls->GetDexCache() == nullptr) {
1391 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001392 // Make a best effort to find the type index in the method's dex file.
1393 // We could search all open dex files but that might turn expensive
1394 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001395 class_dex_file = dex_file;
1396 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1397 } else {
1398 class_dex_file = &(cls->GetDexFile());
1399 type_index = cls->GetDexTypeIndex();
1400 }
1401 if (!type_index.IsValid()) {
1402 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001403 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001404 continue;
1405 }
1406 if (ContainsElement(dex_base_locations, class_dex_file->GetBaseLocation())) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001407 // Only consider classes from the same apk (including multidex).
1408 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001409 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001410 } else {
1411 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001412 }
1413 }
1414 if (!profile_classes.empty()) {
1415 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001416 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001417 }
1418 }
1419 methods.emplace_back(/*ProfileMethodInfo*/
1420 dex_file, method->GetDexMethodIndex(), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001421 }
1422}
1423
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001424uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1425 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001426}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001427
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001428bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1429 MutexLock mu(Thread::Current(), lock_);
1430 return osr_code_map_.find(method) != osr_code_map_.end();
1431}
1432
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001433bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1434 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001435 return false;
1436 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001437
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001438 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001439 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1440 return false;
1441 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001442
Andreas Gampe542451c2016-07-26 09:02:02 -07001443 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001444 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001445 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Jeff Hao00286db2017-05-30 16:53:07 -07001446 // Because the counter is not atomic, there are some rare cases where we may not hit the
1447 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
Mathieu Chartierf044c222017-05-31 15:27:54 -07001448 ClearMethodCounter(method, /*was_warm*/ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001449 return false;
1450 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001451
buzbee454b3b62016-04-07 14:42:47 -07001452 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001453 return false;
1454 }
1455
buzbee454b3b62016-04-07 14:42:47 -07001456 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001457 return true;
1458}
1459
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001460ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001461 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001462 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001463 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001464 if (!info->IncrementInlineUse()) {
1465 // Overflow of inlining uses, just bail.
1466 return nullptr;
1467 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001468 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001469 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001470}
1471
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001472void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001473 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001474 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001475 DCHECK(info != nullptr);
1476 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001477}
1478
buzbee454b3b62016-04-07 14:42:47 -07001479void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001480 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001481 DCHECK(info->IsMethodBeingCompiled(osr));
1482 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001483}
1484
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001485size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1486 MutexLock mu(Thread::Current(), lock_);
1487 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1488}
1489
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001490void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1491 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001492 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001493 if ((profiling_info != nullptr) &&
1494 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1495 // Prevent future uses of the compiled code.
1496 profiling_info->SetSavedEntryPoint(nullptr);
1497 }
1498
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001499 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001500 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001501 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001502 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1503 method, GetQuickToInterpreterBridge());
Mathieu Chartierf044c222017-05-31 15:27:54 -07001504 ClearMethodCounter(method, /*was_warm*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001505 } else {
1506 MutexLock mu(Thread::Current(), lock_);
1507 auto it = osr_code_map_.find(method);
1508 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1509 // Remove the OSR method, to avoid using it again.
1510 osr_code_map_.erase(it);
1511 }
1512 }
1513}
1514
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001515uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1516 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1517 uint8_t* result = reinterpret_cast<uint8_t*>(
1518 mspace_memalign(code_mspace_, alignment, code_size));
1519 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1520 // Ensure the header ends up at expected instruction alignment.
1521 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1522 used_memory_for_code_ += mspace_usable_size(result);
1523 return result;
1524}
1525
1526void JitCodeCache::FreeCode(uint8_t* code) {
1527 used_memory_for_code_ -= mspace_usable_size(code);
1528 mspace_free(code_mspace_, code);
1529}
1530
1531uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1532 void* result = mspace_malloc(data_mspace_, data_size);
1533 used_memory_for_data_ += mspace_usable_size(result);
1534 return reinterpret_cast<uint8_t*>(result);
1535}
1536
1537void JitCodeCache::FreeData(uint8_t* data) {
1538 used_memory_for_data_ -= mspace_usable_size(data);
1539 mspace_free(data_mspace_, data);
1540}
1541
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001542void JitCodeCache::Dump(std::ostream& os) {
1543 MutexLock mu(Thread::Current(), lock_);
1544 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1545 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1546 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1547 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1548 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1549 << "Total number of JIT compilations for on stack replacement: "
1550 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001551 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001552 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1553 histogram_code_memory_use_.PrintMemoryUse(os);
1554 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001555}
1556
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001557} // namespace jit
1558} // namespace art