blob: 2bd1d646a1a824aecbe07447b4b4c6ab63d82009 [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
Mathieu Chartiere401d142015-04-22 13:56:20 -070021#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070022#include "base/enums.h"
Calin Juravle66f55232015-12-08 15:09:10 +000023#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080024#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010025#include "base/time_utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070026#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000027#include "debugger_interface.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010028#include "entrypoints/runtime_asm_entrypoints.h"
29#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010030#include "gc/scoped_gc_critical_section.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000031#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000032#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010033#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080034#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080035#include "oat_file-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070036#include "scoped_thread_state_change-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010037#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080038
39namespace art {
40namespace jit {
41
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010042static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
43static constexpr int kProtData = PROT_READ | PROT_WRITE;
44static constexpr int kProtCode = PROT_READ | PROT_EXEC;
45
Nicolas Geoffray933330a2016-03-16 14:20:06 +000046static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
47static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
48
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010049#define CHECKED_MPROTECT(memory, size, prot) \
50 do { \
51 int rc = mprotect(memory, size, prot); \
52 if (UNLIKELY(rc != 0)) { \
53 errno = rc; \
54 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
55 } \
56 } while (false) \
57
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000058JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
59 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000060 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000061 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080062 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000063 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000064
65 // Generating debug information is mostly for using the 'perf' tool, which does
66 // not work with ashmem.
67 bool use_ashmem = !generate_debug_info;
68 // With 'perf', we want a 1-1 mapping between an address and a method.
69 bool garbage_collect_code = !generate_debug_info;
70
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000071 // We need to have 32 bit offsets from method headers in code cache which point to things
72 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
73 // Ensure we're below 1 GB to be safe.
74 if (max_capacity > 1 * GB) {
75 std::ostringstream oss;
76 oss << "Maxium code cache capacity is limited to 1 GB, "
77 << PrettySize(max_capacity) << " is too big";
78 *error_msg = oss.str();
79 return nullptr;
80 }
81
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080082 std::string error_str;
83 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +000084 // Map in low 4gb to simplify accessing root tables for x86_64.
85 // We could do PC-relative addressing to avoid this problem, but that
86 // would require reserving code and data area before submitting, which
87 // means more windows for the code memory to be RWX.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010088 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +000089 "data-code-cache", nullptr,
90 max_capacity,
91 kProtAll,
92 /* low_4gb */ true,
93 /* reuse */ false,
94 &error_str,
95 use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010096 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080097 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000098 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080099 *error_msg = oss.str();
100 return nullptr;
101 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100102
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000103 // Align both capacities to page size, as that's the unit mspaces use.
104 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
105 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
106
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +0000107 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100108 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000109 size_t data_size = max_capacity / 2;
110 size_t code_size = max_capacity - data_size;
111 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100112 uint8_t* divider = data_map->Begin() + data_size;
113
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000114 MemMap* code_map =
115 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100116 if (code_map == nullptr) {
117 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000118 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100119 *error_msg = oss.str();
120 return nullptr;
121 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100122 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000123 data_size = initial_capacity / 2;
124 code_size = initial_capacity - data_size;
125 DCHECK_EQ(code_size + data_size, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000126 return new JitCodeCache(
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000127 code_map, data_map, code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800128}
129
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000130JitCodeCache::JitCodeCache(MemMap* code_map,
131 MemMap* data_map,
132 size_t initial_code_capacity,
133 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000134 size_t max_capacity,
135 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100136 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000137 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100138 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100139 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000140 data_map_(data_map),
141 max_capacity_(max_capacity),
142 current_capacity_(initial_code_capacity + initial_data_capacity),
143 code_end_(initial_code_capacity),
144 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000145 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000146 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000147 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000148 used_memory_for_data_(0),
149 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000150 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000151 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000152 number_of_collections_(0),
153 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
154 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000155 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
156 is_weak_access_enabled_(true),
157 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100158
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000159 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000160 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
161 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100162
163 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
164 PLOG(FATAL) << "create_mspace_with_base failed";
165 }
166
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000167 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100168
169 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
170 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100171
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000172 VLOG(jit) << "Created jit code cache: initial data size="
173 << PrettySize(initial_data_capacity)
174 << ", initial code size="
175 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800176}
177
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100178bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100179 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800180}
181
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000182bool JitCodeCache::ContainsMethod(ArtMethod* method) {
183 MutexLock mu(Thread::Current(), lock_);
184 for (auto& it : method_code_map_) {
185 if (it.second == method) {
186 return true;
187 }
188 }
189 return false;
190}
191
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800192class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100193 public:
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800194 explicit ScopedCodeCacheWrite(MemMap* code_map)
195 : ScopedTrace("ScopedCodeCacheWrite"),
196 code_map_(code_map) {
197 ScopedTrace trace("mprotect all");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100198 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800199 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100200 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800201 ScopedTrace trace("mprotect code");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100202 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
203 }
204 private:
205 MemMap* const code_map_;
206
207 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
208};
209
210uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100211 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000212 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700213 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000214 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100215 size_t frame_size_in_bytes,
216 size_t core_spill_mask,
217 size_t fp_spill_mask,
218 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000219 size_t code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000220 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000221 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700222 Handle<mirror::ObjectArray<mirror::Object>> roots,
223 bool has_should_deoptimize_flag,
224 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100225 uint8_t* result = CommitCodeInternal(self,
226 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000227 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700228 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000229 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100230 frame_size_in_bytes,
231 core_spill_mask,
232 fp_spill_mask,
233 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000234 code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000235 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000236 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700237 roots,
238 has_should_deoptimize_flag,
239 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100240 if (result == nullptr) {
241 // Retry.
242 GarbageCollectCache(self);
243 result = CommitCodeInternal(self,
244 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000245 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700246 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000247 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100248 frame_size_in_bytes,
249 core_spill_mask,
250 fp_spill_mask,
251 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000252 code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000253 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000254 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700255 roots,
256 has_should_deoptimize_flag,
257 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100258 }
259 return result;
260}
261
262bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
263 bool in_collection = false;
264 while (collection_in_progress_) {
265 in_collection = true;
266 lock_cond_.Wait(self);
267 }
268 return in_collection;
269}
270
271static uintptr_t FromCodeToAllocation(const void* code) {
272 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
273 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
274}
275
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000276static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
277 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
278}
279
280static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
281 // The length of the table is stored just before the stack map (and therefore at the end of
282 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
283 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
284}
285
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800286static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
287 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
288 // pointer.
289 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
290}
291
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000292static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
293 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
294}
295
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000296static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
297 REQUIRES_SHARED(Locks::mutator_lock_) {
298 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800299 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000300 // Put all roots in `roots_data`.
301 for (uint32_t i = 0; i < length; ++i) {
302 ObjPtr<mirror::Object> object = roots->Get(i);
303 if (kIsDebugBuild) {
304 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000305 if (object->IsString()) {
306 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
307 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
308 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
309 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000310 }
311 gc_roots[i] = GcRoot<mirror::Object>(object);
312 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000313}
314
315static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
316 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
317 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
318 uint32_t roots = GetNumberOfRoots(data);
319 if (number_of_roots != nullptr) {
320 *number_of_roots = roots;
321 }
322 return data - ComputeRootTableSize(roots);
323}
324
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100325// Use a sentinel for marking entries in the JIT table that have been cleared.
326// This helps diagnosing in case the compiled code tries to wrongly access such
327// entries.
328static mirror::Class* const weak_sentinel = reinterpret_cast<mirror::Class*>(0x1);
329
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000330// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100331static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
332 IsMarkedVisitor* visitor,
333 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000334 REQUIRES_SHARED(Locks::mutator_lock_) {
335 // This does not need a read barrier because this is called by GC.
336 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100337 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000338 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
339 // Look at the classloader of the class to know if it has been unloaded.
340 // This does not need a read barrier because this is called by GC.
341 mirror::Object* class_loader =
342 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
343 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
344 // The class loader is live, update the entry if the class has moved.
345 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
346 // Note that new_object can be null for CMS and newly allocated objects.
347 if (new_cls != nullptr && new_cls != cls) {
348 *root_ptr = GcRoot<mirror::Class>(new_cls);
349 }
350 } else {
351 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100352 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000353 }
354 }
355}
356
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000357void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
358 MutexLock mu(Thread::Current(), lock_);
359 for (const auto& entry : method_code_map_) {
360 uint32_t number_of_roots = 0;
361 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
362 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
363 for (uint32_t i = 0; i < number_of_roots; ++i) {
364 // This does not need a read barrier because this is called by GC.
365 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100366 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000367 // entry got deleted in a previous sweep.
368 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
369 mirror::Object* new_object = visitor->IsMarked(object);
370 // We know the string is marked because it's a strongly-interned string that
371 // is always alive. The IsMarked implementation of the CMS collector returns
372 // null for newly allocated objects, but we know those haven't moved. Therefore,
373 // only update the entry if we get a different non-null string.
374 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
375 // out of the weak access/creation pause. b/32167580
376 if (new_object != nullptr && new_object != object) {
377 DCHECK(new_object->IsString());
378 roots[i] = GcRoot<mirror::Object>(new_object);
379 }
380 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100381 ProcessWeakClass(
382 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000383 }
384 }
385 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000386 // Walk over inline caches to clear entries containing unloaded classes.
387 for (ProfilingInfo* info : profiling_infos_) {
388 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
389 InlineCache* cache = &info->cache_[i];
390 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100391 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000392 }
393 }
394 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000395}
396
Mingyao Yang063fc772016-08-02 11:02:54 -0700397void JitCodeCache::FreeCode(const void* code_ptr) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100398 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000399 // Notify native debugger that we are about to remove the code.
400 // It does nothing if we are not using native debugger.
401 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000402 FreeData(GetRootTable(code_ptr));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000403 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100404}
405
Mingyao Yang063fc772016-08-02 11:02:54 -0700406void JitCodeCache::FreeAllMethodHeaders(
407 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
408 {
409 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
410 Runtime::Current()->GetClassHierarchyAnalysis()
411 ->RemoveDependentsWithMethodHeaders(method_headers);
412 }
413
414 // We need to remove entries in method_headers from CHA dependencies
415 // first since once we do FreeCode() below, the memory can be reused
416 // so it's possible for the same method_header to start representing
417 // different compile code.
418 MutexLock mu(Thread::Current(), lock_);
419 ScopedCodeCacheWrite scc(code_map_.get());
420 for (const OatQuickMethodHeader* method_header : method_headers) {
421 FreeCode(method_header->GetCode());
422 }
423}
424
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100425void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800426 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700427 // We use a set to first collect all method_headers whose code need to be
428 // removed. We need to free the underlying code after we remove CHA dependencies
429 // for entries in this set. And it's more efficient to iterate through
430 // the CHA dependency map just once with an unordered_set.
431 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000432 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700433 MutexLock mu(self, lock_);
434 // We do not check if a code cache GC is in progress, as this method comes
435 // with the classlinker_classes_lock_ held, and suspending ourselves could
436 // lead to a deadlock.
437 {
438 ScopedCodeCacheWrite scc(code_map_.get());
439 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
440 if (alloc.ContainsUnsafe(it->second)) {
441 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
442 it = method_code_map_.erase(it);
443 } else {
444 ++it;
445 }
446 }
447 }
448 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
449 if (alloc.ContainsUnsafe(it->first)) {
450 // Note that the code has already been pushed to method_headers in the loop
451 // above and is going to be removed in FreeCode() below.
452 it = osr_code_map_.erase(it);
453 } else {
454 ++it;
455 }
456 }
457 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
458 ProfilingInfo* info = *it;
459 if (alloc.ContainsUnsafe(info->GetMethod())) {
460 info->GetMethod()->SetProfilingInfo(nullptr);
461 FreeData(reinterpret_cast<uint8_t*>(info));
462 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000463 } else {
464 ++it;
465 }
466 }
467 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700468 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100469}
470
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000471bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
472 return kUseReadBarrier
473 ? self->GetWeakRefAccessEnabled()
474 : is_weak_access_enabled_.LoadSequentiallyConsistent();
475}
476
477void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
478 if (IsWeakAccessEnabled(self)) {
479 return;
480 }
481 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000482 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000483 while (!IsWeakAccessEnabled(self)) {
484 inline_cache_cond_.Wait(self);
485 }
486}
487
488void JitCodeCache::BroadcastForInlineCacheAccess() {
489 Thread* self = Thread::Current();
490 MutexLock mu(self, lock_);
491 inline_cache_cond_.Broadcast(self);
492}
493
494void JitCodeCache::AllowInlineCacheAccess() {
495 DCHECK(!kUseReadBarrier);
496 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
497 BroadcastForInlineCacheAccess();
498}
499
500void JitCodeCache::DisallowInlineCacheAccess() {
501 DCHECK(!kUseReadBarrier);
502 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
503}
504
505void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
506 Handle<mirror::ObjectArray<mirror::Class>> array) {
507 WaitUntilInlineCacheAccessible(Thread::Current());
508 // Note that we don't need to lock `lock_` here, the compiler calling
509 // this method has already ensured the inline cache will not be deleted.
510 for (size_t in_cache = 0, in_array = 0;
511 in_cache < InlineCache::kIndividualCacheSize;
512 ++in_cache) {
513 mirror::Class* object = ic.classes_[in_cache].Read();
514 if (object != nullptr) {
515 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000516 }
517 }
518}
519
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100520uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
521 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000522 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700523 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000524 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100525 size_t frame_size_in_bytes,
526 size_t core_spill_mask,
527 size_t fp_spill_mask,
528 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000529 size_t code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000530 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000531 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700532 Handle<mirror::ObjectArray<mirror::Object>> roots,
533 bool has_should_deoptimize_flag,
534 const ArenaSet<ArtMethod*>&
535 cha_single_implementation_list) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000536 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100537 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
538 // Ensure the header ends up at expected instruction alignment.
539 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
540 size_t total_size = header_size + code_size;
541
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100542 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100543 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000544 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100545 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000546 ScopedThreadSuspension sts(self, kSuspended);
547 MutexLock mu(self, lock_);
548 WaitForPotentialCollectionToComplete(self);
549 {
550 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000551 memory = AllocateCode(total_size);
552 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000553 return nullptr;
554 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000555 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000556
557 std::copy(code, code + code_size, code_ptr);
558 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
559 new (method_header) OatQuickMethodHeader(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000560 code_ptr - stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700561 code_ptr - method_info,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000562 frame_size_in_bytes,
563 core_spill_mask,
564 fp_spill_mask,
565 code_size);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000566 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
567 DCHECK_LE(roots_data, stack_map);
568 // Flush data cache, as compiled code references literals in it.
569 FlushDataCache(reinterpret_cast<char*>(roots_data),
570 reinterpret_cast<char*>(roots_data + data_size));
Kevin Brodskyb93ce182016-12-15 14:23:09 +0000571 // Flush caches before we remove write permission because some ARMv8 Qualcomm kernels may
572 // trigger a segfault if a page fault occurs when requesting a cache maintenance operation.
573 // This is a kernel bug that we need to work around until affected devices (e.g. Nexus 5X and
574 // 6P) stop being supported or their kernels are fixed.
Artem Udovichenkob18a6692016-11-17 10:51:58 +0300575 //
Kevin Brodskyb93ce182016-12-15 14:23:09 +0000576 // For reference, this behavior is caused by this commit:
577 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
Artem Udovichenkob18a6692016-11-17 10:51:58 +0300578 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
579 reinterpret_cast<char*>(code_ptr + code_size));
Mingyao Yang063fc772016-08-02 11:02:54 -0700580 DCHECK(!Runtime::Current()->IsAotCompiler());
581 if (has_should_deoptimize_flag) {
582 method_header->SetHasShouldDeoptimizeFlag();
583 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100584 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100585
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000586 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100587 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000588 // We need to update the entry point in the runnable state for the instrumentation.
589 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700590 // Need cha_lock_ for checking all single-implementation flags and register
591 // dependencies.
592 MutexLock cha_mu(self, *Locks::cha_lock_);
593 bool single_impl_still_valid = true;
594 for (ArtMethod* single_impl : cha_single_implementation_list) {
595 if (!single_impl->HasSingleImplementation()) {
596 // We simply discard the compiled code. Clear the
597 // counter so that it may be recompiled later. Hopefully the
598 // class hierarchy will be more stable when compilation is retried.
599 single_impl_still_valid = false;
600 method->ClearCounter();
601 break;
602 }
603 }
604
605 // Discard the code if any single-implementation assumptions are now invalid.
606 if (!single_impl_still_valid) {
607 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
608 return nullptr;
609 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000610 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800611 << "Should not be using cha on debuggable apps/runs!";
612
Mingyao Yang063fc772016-08-02 11:02:54 -0700613 for (ArtMethod* single_impl : cha_single_implementation_list) {
614 Runtime::Current()->GetClassHierarchyAnalysis()->AddDependency(
615 single_impl, method, method_header);
616 }
617
618 // The following needs to be guarded by cha_lock_ also. Otherwise it's
619 // possible that the compiled code is considered invalidated by some class linking,
620 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000621 MutexLock mu(self, lock_);
622 method_code_map_.Put(code_ptr, method);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000623 // Fill the root table before updating the entry point.
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000624 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000625 FillRootTable(roots_data, roots);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000626 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000627 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000628 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100629 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000630 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
631 method, method_header->GetEntryPoint());
632 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000633 if (collection_in_progress_) {
634 // We need to update the live bitmap if there is a GC to ensure it sees this new
635 // code.
636 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
637 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000638 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000639 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100640 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700641 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000642 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
643 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
644 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700645 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
646 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000647 histogram_code_memory_use_.AddValue(code_size);
648 if (code_size > kCodeSizeLogThreshold) {
649 LOG(INFO) << "JIT allocated "
650 << PrettySize(code_size)
651 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700652 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000653 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000654 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100655
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100656 return reinterpret_cast<uint8_t*>(method_header);
657}
658
659size_t JitCodeCache::CodeCacheSize() {
660 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000661 return CodeCacheSizeLocked();
662}
663
Alex Lightdba61482016-12-21 08:20:29 -0800664// This notifies the code cache that the given method has been redefined and that it should remove
665// any cached information it has on the method. All threads must be suspended before calling this
666// method. The compiled code for the method (if there is any) must not be in any threads call stack.
667void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
668 MutexLock mu(Thread::Current(), lock_);
669 if (method->IsNative()) {
670 return;
671 }
672 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
673 if (info != nullptr) {
674 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
675 DCHECK(profile != profiling_infos_.end());
676 profiling_infos_.erase(profile);
677 }
678 method->SetProfilingInfo(nullptr);
679 ScopedCodeCacheWrite ccw(code_map_.get());
680 for (auto code_iter = method_code_map_.begin();
681 code_iter != method_code_map_.end();
682 ++code_iter) {
683 if (code_iter->second == method) {
684 FreeCode(code_iter->first);
685 method_code_map_.erase(code_iter);
686 }
687 }
688 auto code_map = osr_code_map_.find(method);
689 if (code_map != osr_code_map_.end()) {
690 osr_code_map_.erase(code_map);
691 }
692}
693
694// This invalidates old_method. Once this function returns one can no longer use old_method to
695// execute code unless it is fixed up. This fixup will happen later in the process of installing a
696// class redefinition.
697// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
698// shouldn't be used since it is no longer logically in the jit code cache.
699// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
700void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000701 // Native methods have no profiling info and need no special handling from the JIT code cache.
702 if (old_method->IsNative()) {
703 return;
704 }
Alex Lightdba61482016-12-21 08:20:29 -0800705 MutexLock mu(Thread::Current(), lock_);
706 // Update ProfilingInfo to the new one and remove it from the old_method.
707 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
708 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
709 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
710 old_method->SetProfilingInfo(nullptr);
711 // Since the JIT should be paused and all threads suspended by the time this is called these
712 // checks should always pass.
713 DCHECK(!info->IsInUseByCompiler());
714 new_method->SetProfilingInfo(info);
715 info->method_ = new_method;
716 }
717 // Update method_code_map_ to point to the new method.
718 for (auto& it : method_code_map_) {
719 if (it.second == old_method) {
720 it.second = new_method;
721 }
722 }
723 // Update osr_code_map_ to point to the new method.
724 auto code_map = osr_code_map_.find(old_method);
725 if (code_map != osr_code_map_.end()) {
726 osr_code_map_.Put(new_method, code_map->second);
727 osr_code_map_.erase(old_method);
728 }
729}
730
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000731size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000732 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100733}
734
735size_t JitCodeCache::DataCacheSize() {
736 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000737 return DataCacheSizeLocked();
738}
739
740size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000741 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800742}
743
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000744void JitCodeCache::ClearData(Thread* self,
745 uint8_t* stack_map_data,
746 uint8_t* roots_data) {
747 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000748 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000749 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000750}
751
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000752size_t JitCodeCache::ReserveData(Thread* self,
753 size_t stack_map_size,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700754 size_t method_info_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000755 size_t number_of_roots,
756 ArtMethod* method,
757 uint8_t** stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700758 uint8_t** method_info_data,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000759 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000760 size_t table_size = ComputeRootTableSize(number_of_roots);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700761 size_t size = RoundUp(stack_map_size + method_info_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100762 uint8_t* result = nullptr;
763
764 {
765 ScopedThreadSuspension sts(self, kSuspended);
766 MutexLock mu(self, lock_);
767 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000768 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100769 }
770
771 if (result == nullptr) {
772 // Retry.
773 GarbageCollectCache(self);
774 ScopedThreadSuspension sts(self, kSuspended);
775 MutexLock mu(self, lock_);
776 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000777 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100778 }
779
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000780 MutexLock mu(self, lock_);
781 histogram_stack_map_memory_use_.AddValue(size);
782 if (size > kStackMapSizeLogThreshold) {
783 LOG(INFO) << "JIT allocated "
784 << PrettySize(size)
785 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700786 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800787 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000788 if (result != nullptr) {
789 *roots_data = result;
790 *stack_map_data = result + table_size;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700791 *method_info_data = *stack_map_data + stack_map_size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000792 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000793 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000794 } else {
795 *roots_data = nullptr;
796 *stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700797 *method_info_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000798 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000799 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800800}
801
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100802class MarkCodeVisitor FINAL : public StackVisitor {
803 public:
804 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
805 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
806 code_cache_(code_cache_in),
807 bitmap_(code_cache_->GetLiveBitmap()) {}
808
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700809 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100810 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
811 if (method_header == nullptr) {
812 return true;
813 }
814 const void* code = method_header->GetCode();
815 if (code_cache_->ContainsPc(code)) {
816 // Use the atomic set version, as multiple threads are executing this code.
817 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
818 }
819 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800820 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100821
822 private:
823 JitCodeCache* const code_cache_;
824 CodeCacheBitmap* const bitmap_;
825};
826
827class MarkCodeClosure FINAL : public Closure {
828 public:
829 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
830 : code_cache_(code_cache), barrier_(barrier) {}
831
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700832 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800833 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100834 DCHECK(thread == Thread::Current() || thread->IsSuspended());
835 MarkCodeVisitor visitor(thread, code_cache_);
836 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000837 if (kIsDebugBuild) {
838 // The stack walking code queries the side instrumentation stack if it
839 // sees an instrumentation exit pc, so the JIT code of methods in that stack
840 // must have been seen. We sanity check this below.
841 for (const instrumentation::InstrumentationStackFrame& frame
842 : *thread->GetInstrumentationStack()) {
843 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
844 // its stack frame, it is not the method owning return_pc_. We just pass null to
845 // LookupMethodHeader: the method is only checked against in debug builds.
846 OatQuickMethodHeader* method_header =
847 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
848 if (method_header != nullptr) {
849 const void* code = method_header->GetCode();
850 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
851 }
852 }
853 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700854 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800855 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100856
857 private:
858 JitCodeCache* const code_cache_;
859 Barrier* const barrier_;
860};
861
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000862void JitCodeCache::NotifyCollectionDone(Thread* self) {
863 collection_in_progress_ = false;
864 lock_cond_.Broadcast(self);
865}
866
867void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
868 size_t per_space_footprint = new_footprint / 2;
869 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
870 DCHECK_EQ(per_space_footprint * 2, new_footprint);
871 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
872 {
873 ScopedCodeCacheWrite scc(code_map_.get());
874 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
875 }
876}
877
878bool JitCodeCache::IncreaseCodeCacheCapacity() {
879 if (current_capacity_ == max_capacity_) {
880 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100881 }
882
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000883 // Double the capacity if we're below 1MB, or increase it by 1MB if
884 // we're above.
885 if (current_capacity_ < 1 * MB) {
886 current_capacity_ *= 2;
887 } else {
888 current_capacity_ += 1 * MB;
889 }
890 if (current_capacity_ > max_capacity_) {
891 current_capacity_ = max_capacity_;
892 }
893
894 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
895 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
896 }
897
898 SetFootprintLimit(current_capacity_);
899
900 return true;
901}
902
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000903void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
904 Barrier barrier(0);
905 size_t threads_running_checkpoint = 0;
906 MarkCodeClosure closure(this, &barrier);
907 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
908 // Now that we have run our checkpoint, move to a suspended state and wait
909 // for other threads to run the checkpoint.
910 ScopedThreadSuspension sts(self, kSuspended);
911 if (threads_running_checkpoint != 0) {
912 barrier.Increment(self, threads_running_checkpoint);
913 }
914}
915
Nicolas Geoffray35122442016-03-02 12:05:30 +0000916bool JitCodeCache::ShouldDoFullCollection() {
917 if (current_capacity_ == max_capacity_) {
918 // Always do a full collection when the code cache is full.
919 return true;
920 } else if (current_capacity_ < kReservedCapacity) {
921 // Always do partial collection when the code cache size is below the reserved
922 // capacity.
923 return false;
924 } else if (last_collection_increased_code_cache_) {
925 // This time do a full collection.
926 return true;
927 } else {
928 // This time do a partial collection.
929 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000930 }
931}
932
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000933void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800934 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000935 if (!garbage_collect_code_) {
936 MutexLock mu(self, lock_);
937 IncreaseCodeCacheCapacity();
938 return;
939 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100940
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000941 // Wait for an existing collection, or let everyone know we are starting one.
942 {
943 ScopedThreadSuspension sts(self, kSuspended);
944 MutexLock mu(self, lock_);
945 if (WaitForPotentialCollectionToComplete(self)) {
946 return;
947 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000948 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000949 live_bitmap_.reset(CodeCacheBitmap::Create(
950 "code-cache-bitmap",
951 reinterpret_cast<uintptr_t>(code_map_->Begin()),
952 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000953 collection_in_progress_ = true;
954 }
955 }
956
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000957 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000958 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000959 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000960
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000961 bool do_full_collection = false;
962 {
963 MutexLock mu(self, lock_);
964 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000965 }
966
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000967 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
968 LOG(INFO) << "Do "
969 << (do_full_collection ? "full" : "partial")
970 << " code cache collection, code="
971 << PrettySize(CodeCacheSize())
972 << ", data=" << PrettySize(DataCacheSize());
973 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000974
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000975 DoCollection(self, /* collect_profiling_info */ do_full_collection);
976
977 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
978 LOG(INFO) << "After code cache collection, code="
979 << PrettySize(CodeCacheSize())
980 << ", data=" << PrettySize(DataCacheSize());
981 }
982
983 {
984 MutexLock mu(self, lock_);
985
986 // Increase the code cache only when we do partial collections.
987 // TODO: base this strategy on how full the code cache is?
988 if (do_full_collection) {
989 last_collection_increased_code_cache_ = false;
990 } else {
991 last_collection_increased_code_cache_ = true;
992 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000993 }
994
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000995 bool next_collection_will_be_full = ShouldDoFullCollection();
996
997 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100998 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000999 // Save the entry point of methods we have compiled, and update the entry
1000 // point of those methods to the interpreter. If the method is invoked, the
1001 // interpreter will update its entry point to the compiled code and call it.
1002 for (ProfilingInfo* info : profiling_infos_) {
1003 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1004 if (ContainsPc(entry_point)) {
1005 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001006 // Don't call Instrumentation::UpdateMethods, as it can check the declaring
1007 // class of the method. We may be concurrently running a GC which makes accessing
1008 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1009 // checked that the current entry point is JIT compiled code.
1010 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001011 }
1012 }
1013
1014 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
1015 }
1016 live_bitmap_.reset(nullptr);
1017 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001018 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001019 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001020 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001021}
1022
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001023void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001024 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001025 std::unordered_set<OatQuickMethodHeader*> method_headers;
1026 {
1027 MutexLock mu(self, lock_);
1028 ScopedCodeCacheWrite scc(code_map_.get());
1029 // Iterate over all compiled code and remove entries that are not marked.
1030 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1031 const void* code_ptr = it->first;
1032 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1033 if (GetLiveBitmap()->Test(allocation)) {
1034 ++it;
1035 } else {
1036 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
1037 it = method_code_map_.erase(it);
1038 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001039 }
1040 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001041 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001042}
1043
1044void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001045 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001046 {
1047 MutexLock mu(self, lock_);
1048 if (collect_profiling_info) {
1049 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1050 // Also remove the saved entry point from the ProfilingInfo objects.
1051 for (ProfilingInfo* info : profiling_infos_) {
1052 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001053 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001054 info->GetMethod()->SetProfilingInfo(nullptr);
1055 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001056
1057 if (info->GetSavedEntryPoint() != nullptr) {
1058 info->SetSavedEntryPoint(nullptr);
1059 // We are going to move this method back to interpreter. Clear the counter now to
1060 // give it a chance to be hot again.
1061 info->GetMethod()->ClearCounter();
1062 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001063 }
1064 } else if (kIsDebugBuild) {
1065 // Sanity check that the profiling infos do not have a dangling entry point.
1066 for (ProfilingInfo* info : profiling_infos_) {
1067 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001068 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001069 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001070
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001071 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1072 // an entry point is either:
1073 // - an osr compiled code, that will be removed if not in a thread call stack.
1074 // - discarded compiled code, that will be removed if not in a thread call stack.
1075 for (const auto& it : method_code_map_) {
1076 ArtMethod* method = it.second;
1077 const void* code_ptr = it.first;
1078 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1079 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1080 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1081 }
1082 }
1083
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001084 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001085 // on thread stacks).
1086 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001087 }
1088
1089 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001090 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001091
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001092 // At this point, mutator threads are still running, and entrypoints of methods can
1093 // change. We do know they cannot change to a code cache entry that is not marked,
1094 // therefore we can safely remove those entries.
1095 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001096
Nicolas Geoffray35122442016-03-02 12:05:30 +00001097 if (collect_profiling_info) {
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +01001098 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001099 MutexLock mu(self, lock_);
1100 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001101 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001102 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001103 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001104 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1105 // that the compiled code would not get revived. As mutator threads run concurrently,
1106 // they may have revived the compiled code, and now we are in the situation where
1107 // a method has compiled code but no ProfilingInfo.
1108 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1109 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001110 if (ContainsPc(ptr) &&
1111 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001112 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001113 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001114 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001115 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001116 return true;
1117 }
1118 return false;
1119 });
1120 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001121 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001122 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001123}
1124
Nicolas Geoffray35122442016-03-02 12:05:30 +00001125bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001126 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001127 // Check that methods we have compiled do have a ProfilingInfo object. We would
1128 // have memory leaks of compiled code otherwise.
1129 for (const auto& it : method_code_map_) {
1130 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001131 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001132 const void* code_ptr = it.first;
1133 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1134 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1135 // If the code is not dead, then we have a problem. Note that this can even
1136 // happen just after a collection, as mutator threads are running in parallel
1137 // and could deoptimize an existing compiled code.
1138 return false;
1139 }
1140 }
1141 }
1142 return true;
1143}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001144
1145OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
1146 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
1147 if (kRuntimeISA == kArm) {
1148 // On Thumb-2, the pc is offset by one.
1149 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001150 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001151 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1152 return nullptr;
1153 }
1154
1155 MutexLock mu(Thread::Current(), lock_);
1156 if (method_code_map_.empty()) {
1157 return nullptr;
1158 }
1159 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1160 --it;
1161
1162 const void* code_ptr = it->first;
1163 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1164 if (!method_header->Contains(pc)) {
1165 return nullptr;
1166 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001167 if (kIsDebugBuild && method != nullptr) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001168 // When we are walking the stack to redefine classes and creating obsolete methods it is
1169 // possible that we might have updated the method_code_map by making this method obsolete in a
1170 // previous frame. Therefore we should just check that the non-obsolete version of this method
1171 // is the one we expect. We change to the non-obsolete versions in the error message since the
1172 // obsolete version of the method might not be fully initialized yet. This situation can only
1173 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
1174 // method and it->second should be identical. (See runtime/openjdkjvmti/ti_redefine.cc for more
1175 // information.)
1176 DCHECK_EQ(it->second->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
1177 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
1178 << ArtMethod::PrettyMethod(it->second->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001179 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001180 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001181 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001182}
1183
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001184OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1185 MutexLock mu(Thread::Current(), lock_);
1186 auto it = osr_code_map_.find(method);
1187 if (it == osr_code_map_.end()) {
1188 return nullptr;
1189 }
1190 return OatQuickMethodHeader::FromCodePointer(it->second);
1191}
1192
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001193ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1194 ArtMethod* method,
1195 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001196 bool retry_allocation)
1197 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1198 NO_THREAD_SAFETY_ANALYSIS {
1199 ProfilingInfo* info = nullptr;
1200 if (!retry_allocation) {
1201 // If we are allocating for the interpreter, just try to lock, to avoid
1202 // lock contention with the JIT.
1203 if (lock_.ExclusiveTryLock(self)) {
1204 info = AddProfilingInfoInternal(self, method, entries);
1205 lock_.ExclusiveUnlock(self);
1206 }
1207 } else {
1208 {
1209 MutexLock mu(self, lock_);
1210 info = AddProfilingInfoInternal(self, method, entries);
1211 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001212
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001213 if (info == nullptr) {
1214 GarbageCollectCache(self);
1215 MutexLock mu(self, lock_);
1216 info = AddProfilingInfoInternal(self, method, entries);
1217 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001218 }
1219 return info;
1220}
1221
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001222ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001223 ArtMethod* method,
1224 const std::vector<uint32_t>& entries) {
1225 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001226 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001227 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001228
1229 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001230 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001231 if (info != nullptr) {
1232 return info;
1233 }
1234
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001235 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001236 if (data == nullptr) {
1237 return nullptr;
1238 }
1239 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001240
1241 // Make sure other threads see the data in the profiling info object before the
1242 // store in the ArtMethod's ProfilingInfo pointer.
1243 QuasiAtomic::ThreadFenceRelease();
1244
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001245 method->SetProfilingInfo(info);
1246 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001247 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001248 return info;
1249}
1250
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001251// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1252// is already held.
1253void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1254 if (code_mspace_ == mspace) {
1255 size_t result = code_end_;
1256 code_end_ += increment;
1257 return reinterpret_cast<void*>(result + code_map_->Begin());
1258 } else {
1259 DCHECK_EQ(data_mspace_, mspace);
1260 size_t result = data_end_;
1261 data_end_ += increment;
1262 return reinterpret_cast<void*>(result + data_map_->Begin());
1263 }
1264}
1265
Calin Juravle99629622016-04-19 16:33:46 +01001266void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001267 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001268 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001269 MutexLock mu(Thread::Current(), lock_);
Calin Juravle99629622016-04-19 16:33:46 +01001270 for (const ProfilingInfo* info : profiling_infos_) {
1271 ArtMethod* method = info->GetMethod();
1272 const DexFile* dex_file = method->GetDexFile();
Calin Juravle940eb0c2017-01-30 19:30:44 -08001273 if (!ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
1274 // Skip dex files which are not profiled.
1275 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001276 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001277 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
1278 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
1279 std::vector<ProfileMethodInfo::ProfileClassReference> profile_classes;
1280 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001281 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001282 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001283 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1284 mirror::Class* cls = cache.classes_[k].Read();
1285 if (cls == nullptr) {
1286 break;
1287 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001288
Calin Juravle13439f02017-02-21 01:17:21 -08001289 // Check if the receiver is in the boot class path or if it's in the
1290 // same class loader as the caller. If not, skip it, as there is not
1291 // much we can do during AOT.
1292 if (!cls->IsBootStrapClassLoaded() &&
1293 caller->GetClassLoader() != cls->GetClassLoader()) {
1294 is_missing_types = true;
1295 continue;
1296 }
1297
Calin Juravle4ca70a32017-02-21 16:22:24 -08001298 const DexFile* class_dex_file = nullptr;
1299 dex::TypeIndex type_index;
1300
1301 if (cls->GetDexCache() == nullptr) {
1302 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001303 // Make a best effort to find the type index in the method's dex file.
1304 // We could search all open dex files but that might turn expensive
1305 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001306 class_dex_file = dex_file;
1307 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1308 } else {
1309 class_dex_file = &(cls->GetDexFile());
1310 type_index = cls->GetDexTypeIndex();
1311 }
1312 if (!type_index.IsValid()) {
1313 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001314 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001315 continue;
1316 }
1317 if (ContainsElement(dex_base_locations, class_dex_file->GetBaseLocation())) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001318 // Only consider classes from the same apk (including multidex).
1319 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001320 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001321 } else {
1322 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001323 }
1324 }
1325 if (!profile_classes.empty()) {
1326 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001327 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001328 }
1329 }
1330 methods.emplace_back(/*ProfileMethodInfo*/
1331 dex_file, method->GetDexMethodIndex(), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001332 }
1333}
1334
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001335uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1336 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001337}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001338
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001339bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1340 MutexLock mu(Thread::Current(), lock_);
1341 return osr_code_map_.find(method) != osr_code_map_.end();
1342}
1343
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001344bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1345 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001346 return false;
1347 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001348
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001349 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001350 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1351 return false;
1352 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001353
Andreas Gampe542451c2016-07-26 09:02:02 -07001354 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001355 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001356 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001357 // Because the counter is not atomic, there are some rare cases where we may not
1358 // hit the threshold for creating the ProfilingInfo. Reset the counter now to
1359 // "correct" this.
1360 method->ClearCounter();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001361 return false;
1362 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001363
buzbee454b3b62016-04-07 14:42:47 -07001364 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001365 return false;
1366 }
1367
buzbee454b3b62016-04-07 14:42:47 -07001368 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001369 return true;
1370}
1371
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001372ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001373 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001374 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001375 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001376 if (!info->IncrementInlineUse()) {
1377 // Overflow of inlining uses, just bail.
1378 return nullptr;
1379 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001380 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001381 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001382}
1383
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001384void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001385 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001386 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001387 DCHECK(info != nullptr);
1388 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001389}
1390
buzbee454b3b62016-04-07 14:42:47 -07001391void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001392 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001393 DCHECK(info->IsMethodBeingCompiled(osr));
1394 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001395}
1396
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001397size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1398 MutexLock mu(Thread::Current(), lock_);
1399 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1400}
1401
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001402void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1403 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001404 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001405 if ((profiling_info != nullptr) &&
1406 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1407 // Prevent future uses of the compiled code.
1408 profiling_info->SetSavedEntryPoint(nullptr);
1409 }
1410
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001411 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
1412 // The entrypoint is the one to invalidate, so we just update
1413 // it to the interpreter entry point and clear the counter to get the method
1414 // Jitted again.
1415 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1416 method, GetQuickToInterpreterBridge());
1417 method->ClearCounter();
1418 } else {
1419 MutexLock mu(Thread::Current(), lock_);
1420 auto it = osr_code_map_.find(method);
1421 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1422 // Remove the OSR method, to avoid using it again.
1423 osr_code_map_.erase(it);
1424 }
1425 }
1426}
1427
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001428uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1429 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1430 uint8_t* result = reinterpret_cast<uint8_t*>(
1431 mspace_memalign(code_mspace_, alignment, code_size));
1432 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1433 // Ensure the header ends up at expected instruction alignment.
1434 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1435 used_memory_for_code_ += mspace_usable_size(result);
1436 return result;
1437}
1438
1439void JitCodeCache::FreeCode(uint8_t* code) {
1440 used_memory_for_code_ -= mspace_usable_size(code);
1441 mspace_free(code_mspace_, code);
1442}
1443
1444uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1445 void* result = mspace_malloc(data_mspace_, data_size);
1446 used_memory_for_data_ += mspace_usable_size(result);
1447 return reinterpret_cast<uint8_t*>(result);
1448}
1449
1450void JitCodeCache::FreeData(uint8_t* data) {
1451 used_memory_for_data_ -= mspace_usable_size(data);
1452 mspace_free(data_mspace_, data);
1453}
1454
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001455void JitCodeCache::Dump(std::ostream& os) {
1456 MutexLock mu(Thread::Current(), lock_);
1457 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1458 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1459 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1460 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1461 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1462 << "Total number of JIT compilations for on stack replacement: "
1463 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001464 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001465 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1466 histogram_code_memory_use_.PrintMemoryUse(os);
1467 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001468}
1469
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001470} // namespace jit
1471} // namespace art