blob: e122c6da201de5dc48d06e39217185ef99183e85 [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 Geoffray0a3be162015-11-18 11:15:22 +000054JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
55 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000056 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000057 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080058 ScopedTrace trace(__PRETTY_FUNCTION__);
Orion Hodsondbd05fe2017-08-10 11:41:35 +010059 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000060
David Sehrd1dbb742017-07-17 11:20:38 -070061 // Generating debug information is for using the Linux perf tool on
62 // host which does not work with ashmem.
Nicolas Geoffray520dadf2017-07-19 15:33:11 +010063 // Also, target linux does not support ashmem.
64 bool use_ashmem = !generate_debug_info && !kIsTargetLinux;
David Sehrd1dbb742017-07-17 11:20:38 -070065
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000066 // With 'perf', we want a 1-1 mapping between an address and a method.
67 bool garbage_collect_code = !generate_debug_info;
68
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000069 // We need to have 32 bit offsets from method headers in code cache which point to things
70 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
71 // Ensure we're below 1 GB to be safe.
72 if (max_capacity > 1 * GB) {
73 std::ostringstream oss;
74 oss << "Maxium code cache capacity is limited to 1 GB, "
75 << PrettySize(max_capacity) << " is too big";
76 *error_msg = oss.str();
77 return nullptr;
78 }
79
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080080 std::string error_str;
81 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +000082 // Map in low 4gb to simplify accessing root tables for x86_64.
83 // We could do PC-relative addressing to avoid this problem, but that
84 // would require reserving code and data area before submitting, which
85 // means more windows for the code memory to be RWX.
Andreas Gampee4deaf32017-06-09 15:27:15 -070086 std::unique_ptr<MemMap> data_map(MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +000087 "data-code-cache", nullptr,
88 max_capacity,
Andreas Gampee4deaf32017-06-09 15:27:15 -070089 kProtData,
Nicolas Geoffray132d8362016-11-16 09:19:42 +000090 /* low_4gb */ true,
91 /* reuse */ false,
92 &error_str,
Andreas Gampee4deaf32017-06-09 15:27:15 -070093 use_ashmem));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010094 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080095 std::ostringstream oss;
Andreas Gampee4deaf32017-06-09 15:27:15 -070096 oss << "Failed to create read write cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080097 *error_msg = oss.str();
98 return nullptr;
99 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100100
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100101 // Align both capacities to page size, as that's the unit mspaces use.
102 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
103 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100104
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100105 // Data cache is 1 / 2 of the map.
106 // TODO: Make this variable?
107 size_t data_size = max_capacity / 2;
108 size_t code_size = max_capacity - data_size;
109 DCHECK_EQ(code_size + data_size, max_capacity);
110 uint8_t* divider = data_map->Begin() + data_size;
David Sehrd1dbb742017-07-17 11:20:38 -0700111
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100112 MemMap* code_map =
113 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
David Sehrd1dbb742017-07-17 11:20:38 -0700114 if (code_map == nullptr) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100115 std::ostringstream oss;
116 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
117 *error_msg = oss.str();
David Sehrd1dbb742017-07-17 11:20:38 -0700118 return nullptr;
119 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100120 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000121 data_size = initial_capacity / 2;
122 code_size = initial_capacity - data_size;
123 DCHECK_EQ(code_size + data_size, initial_capacity);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100124 return new JitCodeCache(
125 code_map, data_map.release(), code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800126}
127
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100128JitCodeCache::JitCodeCache(MemMap* code_map,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000129 MemMap* data_map,
130 size_t initial_code_capacity,
131 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000132 size_t max_capacity,
133 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100134 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000135 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100136 collection_in_progress_(false),
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100137 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000138 data_map_(data_map),
139 max_capacity_(max_capacity),
140 current_capacity_(initial_code_capacity + initial_data_capacity),
141 code_end_(initial_code_capacity),
142 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000143 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000144 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000145 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000146 used_memory_for_data_(0),
147 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000148 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000149 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000150 number_of_collections_(0),
151 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
152 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000153 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
154 is_weak_access_enabled_(true),
155 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100156
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000157 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100158 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000159 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100160
161 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
162 PLOG(FATAL) << "create_mspace_with_base failed";
163 }
164
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000165 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100166
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700167 CheckedCall(mprotect,
168 "mprotect jit code cache",
169 code_map_->Begin(),
170 code_map_->Size(),
171 kProtCode);
172 CheckedCall(mprotect,
173 "mprotect jit data cache",
174 data_map_->Begin(),
175 data_map_->Size(),
176 kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100177
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000178 VLOG(jit) << "Created jit code cache: initial data size="
179 << PrettySize(initial_data_capacity)
180 << ", initial code size="
181 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800182}
183
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100184bool JitCodeCache::ContainsPc(const void* ptr) const {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100185 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800186}
187
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000188bool JitCodeCache::ContainsMethod(ArtMethod* method) {
189 MutexLock mu(Thread::Current(), lock_);
190 for (auto& it : method_code_map_) {
191 if (it.second == method) {
192 return true;
193 }
194 }
195 return false;
196}
197
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800198class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100199 public:
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100200 explicit ScopedCodeCacheWrite(MemMap* code_map, bool only_for_tlb_shootdown = false)
201 : ScopedTrace("ScopedCodeCacheWrite"),
202 code_map_(code_map),
203 only_for_tlb_shootdown_(only_for_tlb_shootdown) {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800204 ScopedTrace trace("mprotect all");
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700205 CheckedCall(mprotect,
206 "make code writable",
207 code_map_->Begin(),
208 only_for_tlb_shootdown_ ? kPageSize : code_map_->Size(),
209 kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800210 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100211 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800212 ScopedTrace trace("mprotect code");
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700213 CheckedCall(mprotect,
214 "make code protected",
215 code_map_->Begin(),
216 only_for_tlb_shootdown_ ? kPageSize : code_map_->Size(),
217 kProtCode);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100218 }
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700219
David Sehrd1dbb742017-07-17 11:20:38 -0700220 private:
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100221 MemMap* const code_map_;
222
223 // If we're using ScopedCacheWrite only for TLB shootdown, we limit the scope of mprotect to
224 // one page.
225 const bool only_for_tlb_shootdown_;
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100226
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100227 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
228};
229
230uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100231 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000232 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700233 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000234 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100235 size_t frame_size_in_bytes,
236 size_t core_spill_mask,
237 size_t fp_spill_mask,
238 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000239 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100240 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000241 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700242 Handle<mirror::ObjectArray<mirror::Object>> roots,
243 bool has_should_deoptimize_flag,
244 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100245 uint8_t* result = CommitCodeInternal(self,
246 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000247 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700248 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000249 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100250 frame_size_in_bytes,
251 core_spill_mask,
252 fp_spill_mask,
253 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000254 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100255 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000256 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700257 roots,
258 has_should_deoptimize_flag,
259 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100260 if (result == nullptr) {
261 // Retry.
262 GarbageCollectCache(self);
263 result = CommitCodeInternal(self,
264 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000265 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700266 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000267 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100268 frame_size_in_bytes,
269 core_spill_mask,
270 fp_spill_mask,
271 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000272 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100273 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000274 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700275 roots,
276 has_should_deoptimize_flag,
277 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100278 }
279 return result;
280}
281
282bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
283 bool in_collection = false;
284 while (collection_in_progress_) {
285 in_collection = true;
286 lock_cond_.Wait(self);
287 }
288 return in_collection;
289}
290
291static uintptr_t FromCodeToAllocation(const void* code) {
292 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
293 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
294}
295
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000296static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
297 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
298}
299
300static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
301 // The length of the table is stored just before the stack map (and therefore at the end of
302 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
303 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
304}
305
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800306static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
307 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
308 // pointer.
309 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
310}
311
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000312static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
313 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
314}
315
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000316static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
317 REQUIRES_SHARED(Locks::mutator_lock_) {
318 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800319 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000320 // Put all roots in `roots_data`.
321 for (uint32_t i = 0; i < length; ++i) {
322 ObjPtr<mirror::Object> object = roots->Get(i);
323 if (kIsDebugBuild) {
324 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000325 if (object->IsString()) {
326 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
327 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
328 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
329 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000330 }
331 gc_roots[i] = GcRoot<mirror::Object>(object);
332 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000333}
334
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100335static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000336 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
337 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
338 uint32_t roots = GetNumberOfRoots(data);
339 if (number_of_roots != nullptr) {
340 *number_of_roots = roots;
341 }
342 return data - ComputeRootTableSize(roots);
343}
344
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100345// Use a sentinel for marking entries in the JIT table that have been cleared.
346// This helps diagnosing in case the compiled code tries to wrongly access such
347// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700348static mirror::Class* const weak_sentinel =
349 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100350
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000351// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100352static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
353 IsMarkedVisitor* visitor,
354 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000355 REQUIRES_SHARED(Locks::mutator_lock_) {
356 // This does not need a read barrier because this is called by GC.
357 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100358 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000359 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
360 // Look at the classloader of the class to know if it has been unloaded.
361 // This does not need a read barrier because this is called by GC.
362 mirror::Object* class_loader =
363 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
364 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
365 // The class loader is live, update the entry if the class has moved.
366 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
367 // Note that new_object can be null for CMS and newly allocated objects.
368 if (new_cls != nullptr && new_cls != cls) {
369 *root_ptr = GcRoot<mirror::Class>(new_cls);
370 }
371 } else {
372 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100373 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000374 }
375 }
376}
377
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000378void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
379 MutexLock mu(Thread::Current(), lock_);
380 for (const auto& entry : method_code_map_) {
381 uint32_t number_of_roots = 0;
382 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
383 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
384 for (uint32_t i = 0; i < number_of_roots; ++i) {
385 // This does not need a read barrier because this is called by GC.
386 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100387 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000388 // entry got deleted in a previous sweep.
389 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
390 mirror::Object* new_object = visitor->IsMarked(object);
391 // We know the string is marked because it's a strongly-interned string that
392 // is always alive. The IsMarked implementation of the CMS collector returns
393 // null for newly allocated objects, but we know those haven't moved. Therefore,
394 // only update the entry if we get a different non-null string.
395 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
396 // out of the weak access/creation pause. b/32167580
397 if (new_object != nullptr && new_object != object) {
398 DCHECK(new_object->IsString());
399 roots[i] = GcRoot<mirror::Object>(new_object);
400 }
401 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100402 ProcessWeakClass(
403 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000404 }
405 }
406 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000407 // Walk over inline caches to clear entries containing unloaded classes.
408 for (ProfilingInfo* info : profiling_infos_) {
409 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
410 InlineCache* cache = &info->cache_[i];
411 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100412 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000413 }
414 }
415 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000416}
417
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100418void JitCodeCache::FreeCode(const void* code_ptr) {
419 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000420 // Notify native debugger that we are about to remove the code.
421 // It does nothing if we are not using native debugger.
422 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000423 FreeData(GetRootTable(code_ptr));
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100424 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100425}
426
Mingyao Yang063fc772016-08-02 11:02:54 -0700427void JitCodeCache::FreeAllMethodHeaders(
428 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
429 {
430 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700431 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
Mingyao Yang063fc772016-08-02 11:02:54 -0700432 ->RemoveDependentsWithMethodHeaders(method_headers);
433 }
434
435 // We need to remove entries in method_headers from CHA dependencies
436 // first since once we do FreeCode() below, the memory can be reused
437 // so it's possible for the same method_header to start representing
438 // different compile code.
439 MutexLock mu(Thread::Current(), lock_);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100440 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -0700441 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100442 FreeCode(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700443 }
444}
445
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100446void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800447 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700448 // We use a set to first collect all method_headers whose code need to be
449 // removed. We need to free the underlying code after we remove CHA dependencies
450 // for entries in this set. And it's more efficient to iterate through
451 // the CHA dependency map just once with an unordered_set.
452 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000453 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700454 MutexLock mu(self, lock_);
455 // We do not check if a code cache GC is in progress, as this method comes
456 // with the classlinker_classes_lock_ held, and suspending ourselves could
457 // lead to a deadlock.
458 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100459 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -0700460 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
461 if (alloc.ContainsUnsafe(it->second)) {
462 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
463 it = method_code_map_.erase(it);
464 } else {
465 ++it;
466 }
467 }
468 }
469 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
470 if (alloc.ContainsUnsafe(it->first)) {
471 // Note that the code has already been pushed to method_headers in the loop
472 // above and is going to be removed in FreeCode() below.
473 it = osr_code_map_.erase(it);
474 } else {
475 ++it;
476 }
477 }
478 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
479 ProfilingInfo* info = *it;
480 if (alloc.ContainsUnsafe(info->GetMethod())) {
481 info->GetMethod()->SetProfilingInfo(nullptr);
482 FreeData(reinterpret_cast<uint8_t*>(info));
483 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000484 } else {
485 ++it;
486 }
487 }
488 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700489 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100490}
491
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000492bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
493 return kUseReadBarrier
494 ? self->GetWeakRefAccessEnabled()
495 : is_weak_access_enabled_.LoadSequentiallyConsistent();
496}
497
498void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
499 if (IsWeakAccessEnabled(self)) {
500 return;
501 }
502 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000503 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000504 while (!IsWeakAccessEnabled(self)) {
505 inline_cache_cond_.Wait(self);
506 }
507}
508
509void JitCodeCache::BroadcastForInlineCacheAccess() {
510 Thread* self = Thread::Current();
511 MutexLock mu(self, lock_);
512 inline_cache_cond_.Broadcast(self);
513}
514
515void JitCodeCache::AllowInlineCacheAccess() {
516 DCHECK(!kUseReadBarrier);
517 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
518 BroadcastForInlineCacheAccess();
519}
520
521void JitCodeCache::DisallowInlineCacheAccess() {
522 DCHECK(!kUseReadBarrier);
523 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
524}
525
526void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
527 Handle<mirror::ObjectArray<mirror::Class>> array) {
528 WaitUntilInlineCacheAccessible(Thread::Current());
529 // Note that we don't need to lock `lock_` here, the compiler calling
530 // this method has already ensured the inline cache will not be deleted.
531 for (size_t in_cache = 0, in_array = 0;
532 in_cache < InlineCache::kIndividualCacheSize;
533 ++in_cache) {
534 mirror::Class* object = ic.classes_[in_cache].Read();
535 if (object != nullptr) {
536 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000537 }
538 }
539}
540
Mathieu Chartierf044c222017-05-31 15:27:54 -0700541static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
542 if (was_warm) {
Orion Hodsoncfcc9cf2017-09-29 15:07:27 +0100543 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700544 }
545 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
546 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100547 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
548 // the warmup threshold is 1.
549 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
550 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700551}
552
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100553uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
554 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000555 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700556 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000557 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100558 size_t frame_size_in_bytes,
559 size_t core_spill_mask,
560 size_t fp_spill_mask,
561 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000562 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100563 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000564 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700565 Handle<mirror::ObjectArray<mirror::Object>> roots,
566 bool has_should_deoptimize_flag,
567 const ArenaSet<ArtMethod*>&
568 cha_single_implementation_list) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000569 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100570 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
571 // Ensure the header ends up at expected instruction alignment.
572 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
573 size_t total_size = header_size + code_size;
574
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100575 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100576 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000577 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100578 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000579 ScopedThreadSuspension sts(self, kSuspended);
580 MutexLock mu(self, lock_);
581 WaitForPotentialCollectionToComplete(self);
582 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100583 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000584 memory = AllocateCode(total_size);
585 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000586 return nullptr;
587 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100588 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000589
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100590 std::copy(code, code + code_size, code_ptr);
591 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
592 new (method_header) OatQuickMethodHeader(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000593 code_ptr - stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700594 code_ptr - method_info,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000595 frame_size_in_bytes,
596 core_spill_mask,
597 fp_spill_mask,
598 code_size);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100599 // Flush caches before we remove write permission because some ARMv8 Qualcomm kernels may
600 // trigger a segfault if a page fault occurs when requesting a cache maintenance operation.
601 // This is a kernel bug that we need to work around until affected devices (e.g. Nexus 5X and
602 // 6P) stop being supported or their kernels are fixed.
603 //
604 // For reference, this behavior is caused by this commit:
605 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
606 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
607 reinterpret_cast<char*>(code_ptr + code_size));
Mingyao Yang063fc772016-08-02 11:02:54 -0700608 DCHECK(!Runtime::Current()->IsAotCompiler());
609 if (has_should_deoptimize_flag) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100610 method_header->SetHasShouldDeoptimizeFlag();
Mingyao Yang063fc772016-08-02 11:02:54 -0700611 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100612 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100613
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000614 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100615 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000616 // We need to update the entry point in the runnable state for the instrumentation.
617 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700618 // Need cha_lock_ for checking all single-implementation flags and register
619 // dependencies.
620 MutexLock cha_mu(self, *Locks::cha_lock_);
621 bool single_impl_still_valid = true;
622 for (ArtMethod* single_impl : cha_single_implementation_list) {
623 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700624 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
625 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700626 single_impl_still_valid = false;
Mathieu Chartierf044c222017-05-31 15:27:54 -0700627 ClearMethodCounter(method, /*was_warm*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700628 break;
629 }
630 }
631
632 // Discard the code if any single-implementation assumptions are now invalid.
633 if (!single_impl_still_valid) {
634 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
635 return nullptr;
636 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000637 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800638 << "Should not be using cha on debuggable apps/runs!";
639
Mingyao Yang063fc772016-08-02 11:02:54 -0700640 for (ArtMethod* single_impl : cha_single_implementation_list) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700641 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()->AddDependency(
Mingyao Yang063fc772016-08-02 11:02:54 -0700642 single_impl, method, method_header);
643 }
644
645 // The following needs to be guarded by cha_lock_ also. Otherwise it's
646 // possible that the compiled code is considered invalidated by some class linking,
647 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000648 MutexLock mu(self, lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000649 // Fill the root table before updating the entry point.
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000650 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100651 DCHECK_LE(roots_data, stack_map);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000652 FillRootTable(roots_data, roots);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100653 {
654 // Flush data cache, as compiled code references literals in it.
655 // We also need a TLB shootdown to act as memory barrier across cores.
656 ScopedCodeCacheWrite ccw(code_map_.get(), /* only_for_tlb_shootdown */ true);
657 FlushDataCache(reinterpret_cast<char*>(roots_data),
658 reinterpret_cast<char*>(roots_data + data_size));
659 }
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100660 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000661 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000662 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000663 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100664 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000665 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
666 method, method_header->GetEntryPoint());
667 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000668 if (collection_in_progress_) {
669 // We need to update the live bitmap if there is a GC to ensure it sees this new
670 // code.
671 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
672 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000673 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000674 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100675 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700676 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000677 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
678 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
679 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700680 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
681 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000682 histogram_code_memory_use_.AddValue(code_size);
683 if (code_size > kCodeSizeLogThreshold) {
684 LOG(INFO) << "JIT allocated "
685 << PrettySize(code_size)
686 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700687 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000688 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000689 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100690
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100691 return reinterpret_cast<uint8_t*>(method_header);
692}
693
694size_t JitCodeCache::CodeCacheSize() {
695 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000696 return CodeCacheSizeLocked();
697}
698
Orion Hodsoneced6922017-06-01 10:54:28 +0100699bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
700 MutexLock mu(Thread::Current(), lock_);
701 if (method->IsNative()) {
702 return false;
703 }
704
705 bool in_cache = false;
706 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100707 ScopedCodeCacheWrite ccw(code_map_.get());
Orion Hodsoneced6922017-06-01 10:54:28 +0100708 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
709 if (code_iter->second == method) {
710 if (release_memory) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100711 FreeCode(code_iter->first);
Orion Hodsoneced6922017-06-01 10:54:28 +0100712 }
713 code_iter = method_code_map_.erase(code_iter);
714 in_cache = true;
715 continue;
716 }
717 ++code_iter;
718 }
719 }
720
721 bool osr = false;
722 auto code_map = osr_code_map_.find(method);
723 if (code_map != osr_code_map_.end()) {
724 osr_code_map_.erase(code_map);
725 osr = true;
726 }
727
728 if (!in_cache) {
729 return false;
730 }
731
732 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
733 if (info != nullptr) {
734 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
735 DCHECK(profile != profiling_infos_.end());
736 profiling_infos_.erase(profile);
737 }
738 method->SetProfilingInfo(nullptr);
739 method->ClearCounter();
740 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
741 method, GetQuickToInterpreterBridge());
742 VLOG(jit)
743 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
744 << ArtMethod::PrettyMethod(method) << "@" << method
745 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
746 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
747 return true;
748}
749
Alex Lightdba61482016-12-21 08:20:29 -0800750// This notifies the code cache that the given method has been redefined and that it should remove
751// any cached information it has on the method. All threads must be suspended before calling this
752// method. The compiled code for the method (if there is any) must not be in any threads call stack.
753void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
754 MutexLock mu(Thread::Current(), lock_);
755 if (method->IsNative()) {
756 return;
757 }
758 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
759 if (info != nullptr) {
760 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
761 DCHECK(profile != profiling_infos_.end());
762 profiling_infos_.erase(profile);
763 }
764 method->SetProfilingInfo(nullptr);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100765 ScopedCodeCacheWrite ccw(code_map_.get());
Andreas Gampe39e67382017-05-15 19:26:38 -0700766 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
Alex Lightdba61482016-12-21 08:20:29 -0800767 if (code_iter->second == method) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100768 FreeCode(code_iter->first);
Andreas Gampe39e67382017-05-15 19:26:38 -0700769 code_iter = method_code_map_.erase(code_iter);
770 continue;
Alex Lightdba61482016-12-21 08:20:29 -0800771 }
Andreas Gampe39e67382017-05-15 19:26:38 -0700772 ++code_iter;
Alex Lightdba61482016-12-21 08:20:29 -0800773 }
774 auto code_map = osr_code_map_.find(method);
775 if (code_map != osr_code_map_.end()) {
776 osr_code_map_.erase(code_map);
777 }
778}
779
780// This invalidates old_method. Once this function returns one can no longer use old_method to
781// execute code unless it is fixed up. This fixup will happen later in the process of installing a
782// class redefinition.
783// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
784// shouldn't be used since it is no longer logically in the jit code cache.
785// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
786void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000787 // Native methods have no profiling info and need no special handling from the JIT code cache.
788 if (old_method->IsNative()) {
789 return;
790 }
Alex Lightdba61482016-12-21 08:20:29 -0800791 MutexLock mu(Thread::Current(), lock_);
792 // Update ProfilingInfo to the new one and remove it from the old_method.
793 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
794 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
795 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
796 old_method->SetProfilingInfo(nullptr);
797 // Since the JIT should be paused and all threads suspended by the time this is called these
798 // checks should always pass.
799 DCHECK(!info->IsInUseByCompiler());
800 new_method->SetProfilingInfo(info);
801 info->method_ = new_method;
802 }
803 // Update method_code_map_ to point to the new method.
804 for (auto& it : method_code_map_) {
805 if (it.second == old_method) {
806 it.second = new_method;
807 }
808 }
809 // Update osr_code_map_ to point to the new method.
810 auto code_map = osr_code_map_.find(old_method);
811 if (code_map != osr_code_map_.end()) {
812 osr_code_map_.Put(new_method, code_map->second);
813 osr_code_map_.erase(old_method);
814 }
815}
816
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000817size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000818 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100819}
820
821size_t JitCodeCache::DataCacheSize() {
822 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000823 return DataCacheSizeLocked();
824}
825
826size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000827 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800828}
829
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000830void JitCodeCache::ClearData(Thread* self,
831 uint8_t* stack_map_data,
832 uint8_t* roots_data) {
833 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000834 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000835 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000836}
837
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000838size_t JitCodeCache::ReserveData(Thread* self,
839 size_t stack_map_size,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700840 size_t method_info_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000841 size_t number_of_roots,
842 ArtMethod* method,
843 uint8_t** stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700844 uint8_t** method_info_data,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000845 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000846 size_t table_size = ComputeRootTableSize(number_of_roots);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700847 size_t size = RoundUp(stack_map_size + method_info_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100848 uint8_t* result = nullptr;
849
850 {
851 ScopedThreadSuspension sts(self, kSuspended);
852 MutexLock mu(self, lock_);
853 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000854 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100855 }
856
857 if (result == nullptr) {
858 // Retry.
859 GarbageCollectCache(self);
860 ScopedThreadSuspension sts(self, kSuspended);
861 MutexLock mu(self, lock_);
862 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000863 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100864 }
865
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000866 MutexLock mu(self, lock_);
867 histogram_stack_map_memory_use_.AddValue(size);
868 if (size > kStackMapSizeLogThreshold) {
869 LOG(INFO) << "JIT allocated "
870 << PrettySize(size)
871 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700872 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800873 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000874 if (result != nullptr) {
875 *roots_data = result;
876 *stack_map_data = result + table_size;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700877 *method_info_data = *stack_map_data + stack_map_size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000878 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000879 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000880 } else {
881 *roots_data = nullptr;
882 *stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700883 *method_info_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000884 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000885 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800886}
887
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100888class MarkCodeVisitor FINAL : public StackVisitor {
889 public:
890 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
891 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
892 code_cache_(code_cache_in),
893 bitmap_(code_cache_->GetLiveBitmap()) {}
894
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700895 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100896 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
897 if (method_header == nullptr) {
898 return true;
899 }
900 const void* code = method_header->GetCode();
901 if (code_cache_->ContainsPc(code)) {
902 // Use the atomic set version, as multiple threads are executing this code.
903 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
904 }
905 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800906 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100907
908 private:
909 JitCodeCache* const code_cache_;
910 CodeCacheBitmap* const bitmap_;
911};
912
913class MarkCodeClosure FINAL : public Closure {
914 public:
915 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
916 : code_cache_(code_cache), barrier_(barrier) {}
917
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700918 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800919 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100920 DCHECK(thread == Thread::Current() || thread->IsSuspended());
921 MarkCodeVisitor visitor(thread, code_cache_);
922 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000923 if (kIsDebugBuild) {
924 // The stack walking code queries the side instrumentation stack if it
925 // sees an instrumentation exit pc, so the JIT code of methods in that stack
926 // must have been seen. We sanity check this below.
927 for (const instrumentation::InstrumentationStackFrame& frame
928 : *thread->GetInstrumentationStack()) {
929 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
930 // its stack frame, it is not the method owning return_pc_. We just pass null to
931 // LookupMethodHeader: the method is only checked against in debug builds.
932 OatQuickMethodHeader* method_header =
933 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
934 if (method_header != nullptr) {
935 const void* code = method_header->GetCode();
936 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
937 }
938 }
939 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700940 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800941 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100942
943 private:
944 JitCodeCache* const code_cache_;
945 Barrier* const barrier_;
946};
947
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000948void JitCodeCache::NotifyCollectionDone(Thread* self) {
949 collection_in_progress_ = false;
950 lock_cond_.Broadcast(self);
951}
952
953void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
954 size_t per_space_footprint = new_footprint / 2;
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100955 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000956 DCHECK_EQ(per_space_footprint * 2, new_footprint);
957 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
958 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100959 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000960 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
961 }
962}
963
964bool JitCodeCache::IncreaseCodeCacheCapacity() {
965 if (current_capacity_ == max_capacity_) {
966 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100967 }
968
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000969 // Double the capacity if we're below 1MB, or increase it by 1MB if
970 // we're above.
971 if (current_capacity_ < 1 * MB) {
972 current_capacity_ *= 2;
973 } else {
974 current_capacity_ += 1 * MB;
975 }
976 if (current_capacity_ > max_capacity_) {
977 current_capacity_ = max_capacity_;
978 }
979
Nicolas Geoffray646d6382017-08-09 10:50:00 +0100980 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000981
982 SetFootprintLimit(current_capacity_);
983
984 return true;
985}
986
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000987void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
988 Barrier barrier(0);
989 size_t threads_running_checkpoint = 0;
990 MarkCodeClosure closure(this, &barrier);
991 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
992 // Now that we have run our checkpoint, move to a suspended state and wait
993 // for other threads to run the checkpoint.
994 ScopedThreadSuspension sts(self, kSuspended);
995 if (threads_running_checkpoint != 0) {
996 barrier.Increment(self, threads_running_checkpoint);
997 }
998}
999
Nicolas Geoffray35122442016-03-02 12:05:30 +00001000bool JitCodeCache::ShouldDoFullCollection() {
1001 if (current_capacity_ == max_capacity_) {
1002 // Always do a full collection when the code cache is full.
1003 return true;
1004 } else if (current_capacity_ < kReservedCapacity) {
1005 // Always do partial collection when the code cache size is below the reserved
1006 // capacity.
1007 return false;
1008 } else if (last_collection_increased_code_cache_) {
1009 // This time do a full collection.
1010 return true;
1011 } else {
1012 // This time do a partial collection.
1013 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001014 }
1015}
1016
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001017void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001018 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001019 if (!garbage_collect_code_) {
1020 MutexLock mu(self, lock_);
1021 IncreaseCodeCacheCapacity();
1022 return;
1023 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001024
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001025 // Wait for an existing collection, or let everyone know we are starting one.
1026 {
1027 ScopedThreadSuspension sts(self, kSuspended);
1028 MutexLock mu(self, lock_);
1029 if (WaitForPotentialCollectionToComplete(self)) {
1030 return;
1031 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001032 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001033 live_bitmap_.reset(CodeCacheBitmap::Create(
1034 "code-cache-bitmap",
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001035 reinterpret_cast<uintptr_t>(code_map_->Begin()),
1036 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001037 collection_in_progress_ = true;
1038 }
1039 }
1040
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001041 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001042 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001043 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001044
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001045 bool do_full_collection = false;
1046 {
1047 MutexLock mu(self, lock_);
1048 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001049 }
1050
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001051 VLOG(jit) << "Do "
1052 << (do_full_collection ? "full" : "partial")
1053 << " code cache collection, code="
1054 << PrettySize(CodeCacheSize())
1055 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001056
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001057 DoCollection(self, /* collect_profiling_info */ do_full_collection);
1058
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001059 VLOG(jit) << "After code cache collection, code="
1060 << PrettySize(CodeCacheSize())
1061 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001062
1063 {
1064 MutexLock mu(self, lock_);
1065
1066 // Increase the code cache only when we do partial collections.
1067 // TODO: base this strategy on how full the code cache is?
1068 if (do_full_collection) {
1069 last_collection_increased_code_cache_ = false;
1070 } else {
1071 last_collection_increased_code_cache_ = true;
1072 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001073 }
1074
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001075 bool next_collection_will_be_full = ShouldDoFullCollection();
1076
1077 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001078 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001079 // Save the entry point of methods we have compiled, and update the entry
1080 // point of those methods to the interpreter. If the method is invoked, the
1081 // interpreter will update its entry point to the compiled code and call it.
1082 for (ProfilingInfo* info : profiling_infos_) {
1083 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1084 if (ContainsPc(entry_point)) {
1085 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001086 // Don't call Instrumentation::UpdateMethods, as it can check the declaring
1087 // class of the method. We may be concurrently running a GC which makes accessing
1088 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1089 // checked that the current entry point is JIT compiled code.
1090 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001091 }
1092 }
1093
1094 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
1095 }
1096 live_bitmap_.reset(nullptr);
1097 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001098 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001099 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001100 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001101}
1102
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001103void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001104 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001105 std::unordered_set<OatQuickMethodHeader*> method_headers;
1106 {
1107 MutexLock mu(self, lock_);
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001108 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -07001109 // Iterate over all compiled code and remove entries that are not marked.
1110 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1111 const void* code_ptr = it->first;
1112 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1113 if (GetLiveBitmap()->Test(allocation)) {
1114 ++it;
1115 } else {
1116 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
1117 it = method_code_map_.erase(it);
1118 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001119 }
1120 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001121 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001122}
1123
1124void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001125 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001126 {
1127 MutexLock mu(self, lock_);
1128 if (collect_profiling_info) {
1129 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1130 // Also remove the saved entry point from the ProfilingInfo objects.
1131 for (ProfilingInfo* info : profiling_infos_) {
1132 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001133 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001134 info->GetMethod()->SetProfilingInfo(nullptr);
1135 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001136
1137 if (info->GetSavedEntryPoint() != nullptr) {
1138 info->SetSavedEntryPoint(nullptr);
1139 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001140 // give it a chance to be hot again.
1141 ClearMethodCounter(info->GetMethod(), /*was_warm*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001142 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001143 }
1144 } else if (kIsDebugBuild) {
1145 // Sanity check that the profiling infos do not have a dangling entry point.
1146 for (ProfilingInfo* info : profiling_infos_) {
1147 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001148 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001149 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001150
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001151 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1152 // an entry point is either:
1153 // - an osr compiled code, that will be removed if not in a thread call stack.
1154 // - discarded compiled code, that will be removed if not in a thread call stack.
1155 for (const auto& it : method_code_map_) {
1156 ArtMethod* method = it.second;
1157 const void* code_ptr = it.first;
1158 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1159 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1160 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1161 }
1162 }
1163
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001164 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001165 // on thread stacks).
1166 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001167 }
1168
1169 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001170 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001171
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001172 // At this point, mutator threads are still running, and entrypoints of methods can
1173 // change. We do know they cannot change to a code cache entry that is not marked,
1174 // therefore we can safely remove those entries.
1175 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001176
Nicolas Geoffray35122442016-03-02 12:05:30 +00001177 if (collect_profiling_info) {
1178 MutexLock mu(self, lock_);
1179 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001180 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001181 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001182 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001183 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1184 // that the compiled code would not get revived. As mutator threads run concurrently,
1185 // they may have revived the compiled code, and now we are in the situation where
1186 // a method has compiled code but no ProfilingInfo.
1187 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1188 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001189 if (ContainsPc(ptr) &&
1190 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001191 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001192 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001193 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001194 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001195 return true;
1196 }
1197 return false;
1198 });
1199 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001200 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001201 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001202}
1203
Nicolas Geoffray35122442016-03-02 12:05:30 +00001204bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001205 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001206 // Check that methods we have compiled do have a ProfilingInfo object. We would
1207 // have memory leaks of compiled code otherwise.
1208 for (const auto& it : method_code_map_) {
1209 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001210 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001211 const void* code_ptr = it.first;
1212 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1213 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1214 // If the code is not dead, then we have a problem. Note that this can even
1215 // happen just after a collection, as mutator threads are running in parallel
1216 // and could deoptimize an existing compiled code.
1217 return false;
1218 }
1219 }
1220 }
1221 return true;
1222}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001223
1224OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
1225 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
1226 if (kRuntimeISA == kArm) {
1227 // On Thumb-2, the pc is offset by one.
1228 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001229 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001230 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1231 return nullptr;
1232 }
1233
1234 MutexLock mu(Thread::Current(), lock_);
1235 if (method_code_map_.empty()) {
1236 return nullptr;
1237 }
1238 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1239 --it;
1240
1241 const void* code_ptr = it->first;
1242 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1243 if (!method_header->Contains(pc)) {
1244 return nullptr;
1245 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001246 if (kIsDebugBuild && method != nullptr) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001247 // When we are walking the stack to redefine classes and creating obsolete methods it is
1248 // possible that we might have updated the method_code_map by making this method obsolete in a
1249 // previous frame. Therefore we should just check that the non-obsolete version of this method
1250 // is the one we expect. We change to the non-obsolete versions in the error message since the
1251 // obsolete version of the method might not be fully initialized yet. This situation can only
1252 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
Andreas Gampe06c42a52017-07-26 14:17:14 -07001253 // method and it->second should be identical. (See openjdkjvmti/ti_redefine.cc for more
Alex Light1ebe4fe2017-01-30 14:57:11 -08001254 // information.)
1255 DCHECK_EQ(it->second->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
1256 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
1257 << ArtMethod::PrettyMethod(it->second->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001258 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001259 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001260 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001261}
1262
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001263OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1264 MutexLock mu(Thread::Current(), lock_);
1265 auto it = osr_code_map_.find(method);
1266 if (it == osr_code_map_.end()) {
1267 return nullptr;
1268 }
1269 return OatQuickMethodHeader::FromCodePointer(it->second);
1270}
1271
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001272ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1273 ArtMethod* method,
1274 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001275 bool retry_allocation)
1276 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1277 NO_THREAD_SAFETY_ANALYSIS {
1278 ProfilingInfo* info = nullptr;
1279 if (!retry_allocation) {
1280 // If we are allocating for the interpreter, just try to lock, to avoid
1281 // lock contention with the JIT.
1282 if (lock_.ExclusiveTryLock(self)) {
1283 info = AddProfilingInfoInternal(self, method, entries);
1284 lock_.ExclusiveUnlock(self);
1285 }
1286 } else {
1287 {
1288 MutexLock mu(self, lock_);
1289 info = AddProfilingInfoInternal(self, method, entries);
1290 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001291
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001292 if (info == nullptr) {
1293 GarbageCollectCache(self);
1294 MutexLock mu(self, lock_);
1295 info = AddProfilingInfoInternal(self, method, entries);
1296 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001297 }
1298 return info;
1299}
1300
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001301ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001302 ArtMethod* method,
1303 const std::vector<uint32_t>& entries) {
1304 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001305 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001306 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001307
1308 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001309 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001310 if (info != nullptr) {
1311 return info;
1312 }
1313
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001314 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001315 if (data == nullptr) {
1316 return nullptr;
1317 }
1318 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001319
1320 // Make sure other threads see the data in the profiling info object before the
1321 // store in the ArtMethod's ProfilingInfo pointer.
1322 QuasiAtomic::ThreadFenceRelease();
1323
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001324 method->SetProfilingInfo(info);
1325 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001326 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001327 return info;
1328}
1329
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001330// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1331// is already held.
1332void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1333 if (code_mspace_ == mspace) {
1334 size_t result = code_end_;
1335 code_end_ += increment;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001336 return reinterpret_cast<void*>(result + code_map_->Begin());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001337 } else {
1338 DCHECK_EQ(data_mspace_, mspace);
1339 size_t result = data_end_;
1340 data_end_ += increment;
1341 return reinterpret_cast<void*>(result + data_map_->Begin());
1342 }
1343}
1344
Calin Juravle99629622016-04-19 16:33:46 +01001345void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001346 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001347 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001348 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001349 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001350 for (const ProfilingInfo* info : profiling_infos_) {
1351 ArtMethod* method = info->GetMethod();
1352 const DexFile* dex_file = method->GetDexFile();
Calin Juravle940eb0c2017-01-30 19:30:44 -08001353 if (!ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
1354 // Skip dex files which are not profiled.
1355 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001356 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001357 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001358
1359 // If the method didn't reach the compilation threshold don't save the inline caches.
1360 // They might be incomplete and cause unnecessary deoptimizations.
1361 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1362 if (method->GetCounter() < jit_compile_threshold) {
1363 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001364 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001365 continue;
1366 }
1367
Calin Juravle940eb0c2017-01-30 19:30:44 -08001368 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001369 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001370 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001371 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001372 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001373 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1374 mirror::Class* cls = cache.classes_[k].Read();
1375 if (cls == nullptr) {
1376 break;
1377 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001378
Calin Juravle13439f02017-02-21 01:17:21 -08001379 // Check if the receiver is in the boot class path or if it's in the
1380 // same class loader as the caller. If not, skip it, as there is not
1381 // much we can do during AOT.
1382 if (!cls->IsBootStrapClassLoaded() &&
1383 caller->GetClassLoader() != cls->GetClassLoader()) {
1384 is_missing_types = true;
1385 continue;
1386 }
1387
Calin Juravle4ca70a32017-02-21 16:22:24 -08001388 const DexFile* class_dex_file = nullptr;
1389 dex::TypeIndex type_index;
1390
1391 if (cls->GetDexCache() == nullptr) {
1392 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001393 // Make a best effort to find the type index in the method's dex file.
1394 // We could search all open dex files but that might turn expensive
1395 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001396 class_dex_file = dex_file;
1397 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1398 } else {
1399 class_dex_file = &(cls->GetDexFile());
1400 type_index = cls->GetDexTypeIndex();
1401 }
1402 if (!type_index.IsValid()) {
1403 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001404 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001405 continue;
1406 }
1407 if (ContainsElement(dex_base_locations, class_dex_file->GetBaseLocation())) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001408 // Only consider classes from the same apk (including multidex).
1409 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001410 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001411 } else {
1412 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001413 }
1414 }
1415 if (!profile_classes.empty()) {
1416 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001417 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001418 }
1419 }
1420 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001421 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001422 }
1423}
1424
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001425uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1426 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001427}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001428
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001429bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1430 MutexLock mu(Thread::Current(), lock_);
1431 return osr_code_map_.find(method) != osr_code_map_.end();
1432}
1433
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001434bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1435 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001436 return false;
1437 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001438
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001439 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001440 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1441 return false;
1442 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001443
Andreas Gampe542451c2016-07-26 09:02:02 -07001444 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001445 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001446 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Jeff Hao00286db2017-05-30 16:53:07 -07001447 // Because the counter is not atomic, there are some rare cases where we may not hit the
1448 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
Mathieu Chartierf044c222017-05-31 15:27:54 -07001449 ClearMethodCounter(method, /*was_warm*/ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001450 return false;
1451 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001452
buzbee454b3b62016-04-07 14:42:47 -07001453 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001454 return false;
1455 }
1456
buzbee454b3b62016-04-07 14:42:47 -07001457 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001458 return true;
1459}
1460
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001461ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001462 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001463 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001464 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001465 if (!info->IncrementInlineUse()) {
1466 // Overflow of inlining uses, just bail.
1467 return nullptr;
1468 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001469 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001470 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001471}
1472
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001473void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001474 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001475 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001476 DCHECK(info != nullptr);
1477 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001478}
1479
buzbee454b3b62016-04-07 14:42:47 -07001480void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001481 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001482 DCHECK(info->IsMethodBeingCompiled(osr));
1483 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001484}
1485
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001486size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1487 MutexLock mu(Thread::Current(), lock_);
1488 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1489}
1490
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001491void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1492 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001493 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001494 if ((profiling_info != nullptr) &&
1495 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1496 // Prevent future uses of the compiled code.
1497 profiling_info->SetSavedEntryPoint(nullptr);
1498 }
1499
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001500 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001501 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001502 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001503 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1504 method, GetQuickToInterpreterBridge());
Mathieu Chartierf044c222017-05-31 15:27:54 -07001505 ClearMethodCounter(method, /*was_warm*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001506 } else {
1507 MutexLock mu(Thread::Current(), lock_);
1508 auto it = osr_code_map_.find(method);
1509 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1510 // Remove the OSR method, to avoid using it again.
1511 osr_code_map_.erase(it);
1512 }
1513 }
1514}
1515
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001516uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1517 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1518 uint8_t* result = reinterpret_cast<uint8_t*>(
1519 mspace_memalign(code_mspace_, alignment, code_size));
1520 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1521 // Ensure the header ends up at expected instruction alignment.
1522 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1523 used_memory_for_code_ += mspace_usable_size(result);
1524 return result;
1525}
1526
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001527void JitCodeCache::FreeCode(uint8_t* code) {
1528 used_memory_for_code_ -= mspace_usable_size(code);
1529 mspace_free(code_mspace_, code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001530}
1531
1532uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1533 void* result = mspace_malloc(data_mspace_, data_size);
1534 used_memory_for_data_ += mspace_usable_size(result);
1535 return reinterpret_cast<uint8_t*>(result);
1536}
1537
1538void JitCodeCache::FreeData(uint8_t* data) {
1539 used_memory_for_data_ -= mspace_usable_size(data);
1540 mspace_free(data_mspace_, data);
1541}
1542
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001543void JitCodeCache::Dump(std::ostream& os) {
1544 MutexLock mu(Thread::Current(), lock_);
1545 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1546 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1547 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1548 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1549 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1550 << "Total number of JIT compilations for on stack replacement: "
1551 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001552 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001553 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1554 histogram_code_memory_use_.PrintMemoryUse(os);
1555 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001556}
1557
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001558} // namespace jit
1559} // namespace art