blob: b1ba95287babf13bda7c68e05e32f90d9f389e6a [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),
152 number_of_deoptimizations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000153 number_of_collections_(0),
154 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
155 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000156 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
157 is_weak_access_enabled_(true),
158 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100159
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000160 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000161 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
162 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100163
164 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
165 PLOG(FATAL) << "create_mspace_with_base failed";
166 }
167
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000168 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100169
170 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
171 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100172
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000173 VLOG(jit) << "Created jit code cache: initial data size="
174 << PrettySize(initial_data_capacity)
175 << ", initial code size="
176 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800177}
178
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100179bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100180 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800181}
182
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000183bool JitCodeCache::ContainsMethod(ArtMethod* method) {
184 MutexLock mu(Thread::Current(), lock_);
185 for (auto& it : method_code_map_) {
186 if (it.second == method) {
187 return true;
188 }
189 }
190 return false;
191}
192
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800193class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100194 public:
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800195 explicit ScopedCodeCacheWrite(MemMap* code_map)
196 : ScopedTrace("ScopedCodeCacheWrite"),
197 code_map_(code_map) {
198 ScopedTrace trace("mprotect all");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100199 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800200 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100201 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800202 ScopedTrace trace("mprotect code");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100203 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
204 }
205 private:
206 MemMap* const code_map_;
207
208 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
209};
210
211uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100212 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000213 uint8_t* stack_map,
214 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,
228 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100229 frame_size_in_bytes,
230 core_spill_mask,
231 fp_spill_mask,
232 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000233 code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000234 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000235 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700236 roots,
237 has_should_deoptimize_flag,
238 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100239 if (result == nullptr) {
240 // Retry.
241 GarbageCollectCache(self);
242 result = CommitCodeInternal(self,
243 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000244 stack_map,
245 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100246 frame_size_in_bytes,
247 core_spill_mask,
248 fp_spill_mask,
249 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000250 code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000251 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000252 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700253 roots,
254 has_should_deoptimize_flag,
255 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100256 }
257 return result;
258}
259
260bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
261 bool in_collection = false;
262 while (collection_in_progress_) {
263 in_collection = true;
264 lock_cond_.Wait(self);
265 }
266 return in_collection;
267}
268
269static uintptr_t FromCodeToAllocation(const void* code) {
270 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
271 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
272}
273
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000274static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
275 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
276}
277
278static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
279 // The length of the table is stored just before the stack map (and therefore at the end of
280 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
281 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
282}
283
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800284static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
285 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
286 // pointer.
287 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
288}
289
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000290static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
291 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
292}
293
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000294static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
295 REQUIRES_SHARED(Locks::mutator_lock_) {
296 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800297 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000298 // Put all roots in `roots_data`.
299 for (uint32_t i = 0; i < length; ++i) {
300 ObjPtr<mirror::Object> object = roots->Get(i);
301 if (kIsDebugBuild) {
302 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000303 if (object->IsString()) {
304 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
305 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
306 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
307 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000308 }
309 gc_roots[i] = GcRoot<mirror::Object>(object);
310 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000311}
312
313static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
314 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
315 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
316 uint32_t roots = GetNumberOfRoots(data);
317 if (number_of_roots != nullptr) {
318 *number_of_roots = roots;
319 }
320 return data - ComputeRootTableSize(roots);
321}
322
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000323// Helper for the GC to process a weak class in a JIT root table.
324static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr, IsMarkedVisitor* visitor)
325 REQUIRES_SHARED(Locks::mutator_lock_) {
326 // This does not need a read barrier because this is called by GC.
327 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
328 if (cls != nullptr) {
329 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
330 // Look at the classloader of the class to know if it has been unloaded.
331 // This does not need a read barrier because this is called by GC.
332 mirror::Object* class_loader =
333 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
334 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
335 // The class loader is live, update the entry if the class has moved.
336 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
337 // Note that new_object can be null for CMS and newly allocated objects.
338 if (new_cls != nullptr && new_cls != cls) {
339 *root_ptr = GcRoot<mirror::Class>(new_cls);
340 }
341 } else {
342 // The class loader is not live, clear the entry.
343 *root_ptr = GcRoot<mirror::Class>(nullptr);
344 }
345 }
346}
347
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000348void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
349 MutexLock mu(Thread::Current(), lock_);
350 for (const auto& entry : method_code_map_) {
351 uint32_t number_of_roots = 0;
352 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
353 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
354 for (uint32_t i = 0; i < number_of_roots; ++i) {
355 // This does not need a read barrier because this is called by GC.
356 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000357 if (object == nullptr) {
358 // entry got deleted in a previous sweep.
359 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
360 mirror::Object* new_object = visitor->IsMarked(object);
361 // We know the string is marked because it's a strongly-interned string that
362 // is always alive. The IsMarked implementation of the CMS collector returns
363 // null for newly allocated objects, but we know those haven't moved. Therefore,
364 // only update the entry if we get a different non-null string.
365 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
366 // out of the weak access/creation pause. b/32167580
367 if (new_object != nullptr && new_object != object) {
368 DCHECK(new_object->IsString());
369 roots[i] = GcRoot<mirror::Object>(new_object);
370 }
371 } else {
372 ProcessWeakClass(reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000373 }
374 }
375 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000376 // Walk over inline caches to clear entries containing unloaded classes.
377 for (ProfilingInfo* info : profiling_infos_) {
378 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
379 InlineCache* cache = &info->cache_[i];
380 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000381 ProcessWeakClass(&cache->classes_[j], visitor);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000382 }
383 }
384 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000385}
386
Mingyao Yang063fc772016-08-02 11:02:54 -0700387void JitCodeCache::FreeCode(const void* code_ptr) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100388 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000389 // Notify native debugger that we are about to remove the code.
390 // It does nothing if we are not using native debugger.
391 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000392 FreeData(GetRootTable(code_ptr));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000393 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100394}
395
Mingyao Yang063fc772016-08-02 11:02:54 -0700396void JitCodeCache::FreeAllMethodHeaders(
397 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
398 {
399 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
400 Runtime::Current()->GetClassHierarchyAnalysis()
401 ->RemoveDependentsWithMethodHeaders(method_headers);
402 }
403
404 // We need to remove entries in method_headers from CHA dependencies
405 // first since once we do FreeCode() below, the memory can be reused
406 // so it's possible for the same method_header to start representing
407 // different compile code.
408 MutexLock mu(Thread::Current(), lock_);
409 ScopedCodeCacheWrite scc(code_map_.get());
410 for (const OatQuickMethodHeader* method_header : method_headers) {
411 FreeCode(method_header->GetCode());
412 }
413}
414
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100415void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800416 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700417 // We use a set to first collect all method_headers whose code need to be
418 // removed. We need to free the underlying code after we remove CHA dependencies
419 // for entries in this set. And it's more efficient to iterate through
420 // the CHA dependency map just once with an unordered_set.
421 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000422 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700423 MutexLock mu(self, lock_);
424 // We do not check if a code cache GC is in progress, as this method comes
425 // with the classlinker_classes_lock_ held, and suspending ourselves could
426 // lead to a deadlock.
427 {
428 ScopedCodeCacheWrite scc(code_map_.get());
429 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
430 if (alloc.ContainsUnsafe(it->second)) {
431 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
432 it = method_code_map_.erase(it);
433 } else {
434 ++it;
435 }
436 }
437 }
438 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
439 if (alloc.ContainsUnsafe(it->first)) {
440 // Note that the code has already been pushed to method_headers in the loop
441 // above and is going to be removed in FreeCode() below.
442 it = osr_code_map_.erase(it);
443 } else {
444 ++it;
445 }
446 }
447 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
448 ProfilingInfo* info = *it;
449 if (alloc.ContainsUnsafe(info->GetMethod())) {
450 info->GetMethod()->SetProfilingInfo(nullptr);
451 FreeData(reinterpret_cast<uint8_t*>(info));
452 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000453 } else {
454 ++it;
455 }
456 }
457 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700458 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100459}
460
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000461bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
462 return kUseReadBarrier
463 ? self->GetWeakRefAccessEnabled()
464 : is_weak_access_enabled_.LoadSequentiallyConsistent();
465}
466
467void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
468 if (IsWeakAccessEnabled(self)) {
469 return;
470 }
471 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000472 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000473 while (!IsWeakAccessEnabled(self)) {
474 inline_cache_cond_.Wait(self);
475 }
476}
477
478void JitCodeCache::BroadcastForInlineCacheAccess() {
479 Thread* self = Thread::Current();
480 MutexLock mu(self, lock_);
481 inline_cache_cond_.Broadcast(self);
482}
483
484void JitCodeCache::AllowInlineCacheAccess() {
485 DCHECK(!kUseReadBarrier);
486 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
487 BroadcastForInlineCacheAccess();
488}
489
490void JitCodeCache::DisallowInlineCacheAccess() {
491 DCHECK(!kUseReadBarrier);
492 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
493}
494
495void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
496 Handle<mirror::ObjectArray<mirror::Class>> array) {
497 WaitUntilInlineCacheAccessible(Thread::Current());
498 // Note that we don't need to lock `lock_` here, the compiler calling
499 // this method has already ensured the inline cache will not be deleted.
500 for (size_t in_cache = 0, in_array = 0;
501 in_cache < InlineCache::kIndividualCacheSize;
502 ++in_cache) {
503 mirror::Class* object = ic.classes_[in_cache].Read();
504 if (object != nullptr) {
505 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000506 }
507 }
508}
509
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100510uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
511 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000512 uint8_t* stack_map,
513 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100514 size_t frame_size_in_bytes,
515 size_t core_spill_mask,
516 size_t fp_spill_mask,
517 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000518 size_t code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000519 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000520 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700521 Handle<mirror::ObjectArray<mirror::Object>> roots,
522 bool has_should_deoptimize_flag,
523 const ArenaSet<ArtMethod*>&
524 cha_single_implementation_list) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000525 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100526 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
527 // Ensure the header ends up at expected instruction alignment.
528 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
529 size_t total_size = header_size + code_size;
530
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100531 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100532 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000533 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100534 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000535 ScopedThreadSuspension sts(self, kSuspended);
536 MutexLock mu(self, lock_);
537 WaitForPotentialCollectionToComplete(self);
538 {
539 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000540 memory = AllocateCode(total_size);
541 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000542 return nullptr;
543 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000544 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000545
546 std::copy(code, code + code_size, code_ptr);
547 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
548 new (method_header) OatQuickMethodHeader(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000549 code_ptr - stack_map,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000550 frame_size_in_bytes,
551 core_spill_mask,
552 fp_spill_mask,
553 code_size);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000554 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
555 DCHECK_LE(roots_data, stack_map);
556 // Flush data cache, as compiled code references literals in it.
557 FlushDataCache(reinterpret_cast<char*>(roots_data),
558 reinterpret_cast<char*>(roots_data + data_size));
Kevin Brodskyb93ce182016-12-15 14:23:09 +0000559 // Flush caches before we remove write permission because some ARMv8 Qualcomm kernels may
560 // trigger a segfault if a page fault occurs when requesting a cache maintenance operation.
561 // This is a kernel bug that we need to work around until affected devices (e.g. Nexus 5X and
562 // 6P) stop being supported or their kernels are fixed.
Artem Udovichenkob18a6692016-11-17 10:51:58 +0300563 //
Kevin Brodskyb93ce182016-12-15 14:23:09 +0000564 // For reference, this behavior is caused by this commit:
565 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
Artem Udovichenkob18a6692016-11-17 10:51:58 +0300566 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
567 reinterpret_cast<char*>(code_ptr + code_size));
Mingyao Yang063fc772016-08-02 11:02:54 -0700568 DCHECK(!Runtime::Current()->IsAotCompiler());
569 if (has_should_deoptimize_flag) {
570 method_header->SetHasShouldDeoptimizeFlag();
571 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100572 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100573
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000574 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100575 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000576 // We need to update the entry point in the runnable state for the instrumentation.
577 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700578 // Need cha_lock_ for checking all single-implementation flags and register
579 // dependencies.
580 MutexLock cha_mu(self, *Locks::cha_lock_);
581 bool single_impl_still_valid = true;
582 for (ArtMethod* single_impl : cha_single_implementation_list) {
583 if (!single_impl->HasSingleImplementation()) {
584 // We simply discard the compiled code. Clear the
585 // counter so that it may be recompiled later. Hopefully the
586 // class hierarchy will be more stable when compilation is retried.
587 single_impl_still_valid = false;
588 method->ClearCounter();
589 break;
590 }
591 }
592
593 // Discard the code if any single-implementation assumptions are now invalid.
594 if (!single_impl_still_valid) {
595 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
596 return nullptr;
597 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000598 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800599 << "Should not be using cha on debuggable apps/runs!";
600
Mingyao Yang063fc772016-08-02 11:02:54 -0700601 for (ArtMethod* single_impl : cha_single_implementation_list) {
602 Runtime::Current()->GetClassHierarchyAnalysis()->AddDependency(
603 single_impl, method, method_header);
604 }
605
606 // The following needs to be guarded by cha_lock_ also. Otherwise it's
607 // possible that the compiled code is considered invalidated by some class linking,
608 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000609 MutexLock mu(self, lock_);
610 method_code_map_.Put(code_ptr, method);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000611 // Fill the root table before updating the entry point.
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000612 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000613 FillRootTable(roots_data, roots);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000614 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000615 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000616 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100617 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000618 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
619 method, method_header->GetEntryPoint());
620 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000621 if (collection_in_progress_) {
622 // We need to update the live bitmap if there is a GC to ensure it sees this new
623 // code.
624 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
625 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000626 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000627 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100628 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700629 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000630 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
631 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
632 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700633 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
634 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000635 histogram_code_memory_use_.AddValue(code_size);
636 if (code_size > kCodeSizeLogThreshold) {
637 LOG(INFO) << "JIT allocated "
638 << PrettySize(code_size)
639 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700640 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000641 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000642 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100643
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100644 return reinterpret_cast<uint8_t*>(method_header);
645}
646
647size_t JitCodeCache::CodeCacheSize() {
648 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000649 return CodeCacheSizeLocked();
650}
651
Alex Lightdba61482016-12-21 08:20:29 -0800652// This notifies the code cache that the given method has been redefined and that it should remove
653// any cached information it has on the method. All threads must be suspended before calling this
654// method. The compiled code for the method (if there is any) must not be in any threads call stack.
655void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
656 MutexLock mu(Thread::Current(), lock_);
657 if (method->IsNative()) {
658 return;
659 }
660 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
661 if (info != nullptr) {
662 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
663 DCHECK(profile != profiling_infos_.end());
664 profiling_infos_.erase(profile);
665 }
666 method->SetProfilingInfo(nullptr);
667 ScopedCodeCacheWrite ccw(code_map_.get());
668 for (auto code_iter = method_code_map_.begin();
669 code_iter != method_code_map_.end();
670 ++code_iter) {
671 if (code_iter->second == method) {
672 FreeCode(code_iter->first);
673 method_code_map_.erase(code_iter);
674 }
675 }
676 auto code_map = osr_code_map_.find(method);
677 if (code_map != osr_code_map_.end()) {
678 osr_code_map_.erase(code_map);
679 }
680}
681
682// This invalidates old_method. Once this function returns one can no longer use old_method to
683// execute code unless it is fixed up. This fixup will happen later in the process of installing a
684// class redefinition.
685// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
686// shouldn't be used since it is no longer logically in the jit code cache.
687// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
688void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000689 // Native methods have no profiling info and need no special handling from the JIT code cache.
690 if (old_method->IsNative()) {
691 return;
692 }
Alex Lightdba61482016-12-21 08:20:29 -0800693 MutexLock mu(Thread::Current(), lock_);
694 // Update ProfilingInfo to the new one and remove it from the old_method.
695 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
696 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
697 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
698 old_method->SetProfilingInfo(nullptr);
699 // Since the JIT should be paused and all threads suspended by the time this is called these
700 // checks should always pass.
701 DCHECK(!info->IsInUseByCompiler());
702 new_method->SetProfilingInfo(info);
703 info->method_ = new_method;
704 }
705 // Update method_code_map_ to point to the new method.
706 for (auto& it : method_code_map_) {
707 if (it.second == old_method) {
708 it.second = new_method;
709 }
710 }
711 // Update osr_code_map_ to point to the new method.
712 auto code_map = osr_code_map_.find(old_method);
713 if (code_map != osr_code_map_.end()) {
714 osr_code_map_.Put(new_method, code_map->second);
715 osr_code_map_.erase(old_method);
716 }
717}
718
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000719size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000720 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100721}
722
723size_t JitCodeCache::DataCacheSize() {
724 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000725 return DataCacheSizeLocked();
726}
727
728size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000729 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800730}
731
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000732void JitCodeCache::ClearData(Thread* self,
733 uint8_t* stack_map_data,
734 uint8_t* roots_data) {
735 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000736 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000737 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000738}
739
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000740size_t JitCodeCache::ReserveData(Thread* self,
741 size_t stack_map_size,
742 size_t number_of_roots,
743 ArtMethod* method,
744 uint8_t** stack_map_data,
745 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000746 size_t table_size = ComputeRootTableSize(number_of_roots);
747 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100748 uint8_t* result = nullptr;
749
750 {
751 ScopedThreadSuspension sts(self, kSuspended);
752 MutexLock mu(self, lock_);
753 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000754 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100755 }
756
757 if (result == nullptr) {
758 // Retry.
759 GarbageCollectCache(self);
760 ScopedThreadSuspension sts(self, kSuspended);
761 MutexLock mu(self, lock_);
762 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000763 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100764 }
765
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000766 MutexLock mu(self, lock_);
767 histogram_stack_map_memory_use_.AddValue(size);
768 if (size > kStackMapSizeLogThreshold) {
769 LOG(INFO) << "JIT allocated "
770 << PrettySize(size)
771 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700772 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800773 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000774 if (result != nullptr) {
775 *roots_data = result;
776 *stack_map_data = result + table_size;
777 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000778 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000779 } else {
780 *roots_data = nullptr;
781 *stack_map_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000782 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000783 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800784}
785
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100786class MarkCodeVisitor FINAL : public StackVisitor {
787 public:
788 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
789 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
790 code_cache_(code_cache_in),
791 bitmap_(code_cache_->GetLiveBitmap()) {}
792
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700793 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100794 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
795 if (method_header == nullptr) {
796 return true;
797 }
798 const void* code = method_header->GetCode();
799 if (code_cache_->ContainsPc(code)) {
800 // Use the atomic set version, as multiple threads are executing this code.
801 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
802 }
803 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800804 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100805
806 private:
807 JitCodeCache* const code_cache_;
808 CodeCacheBitmap* const bitmap_;
809};
810
811class MarkCodeClosure FINAL : public Closure {
812 public:
813 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
814 : code_cache_(code_cache), barrier_(barrier) {}
815
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700816 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800817 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100818 DCHECK(thread == Thread::Current() || thread->IsSuspended());
819 MarkCodeVisitor visitor(thread, code_cache_);
820 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000821 if (kIsDebugBuild) {
822 // The stack walking code queries the side instrumentation stack if it
823 // sees an instrumentation exit pc, so the JIT code of methods in that stack
824 // must have been seen. We sanity check this below.
825 for (const instrumentation::InstrumentationStackFrame& frame
826 : *thread->GetInstrumentationStack()) {
827 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
828 // its stack frame, it is not the method owning return_pc_. We just pass null to
829 // LookupMethodHeader: the method is only checked against in debug builds.
830 OatQuickMethodHeader* method_header =
831 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
832 if (method_header != nullptr) {
833 const void* code = method_header->GetCode();
834 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
835 }
836 }
837 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700838 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800839 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100840
841 private:
842 JitCodeCache* const code_cache_;
843 Barrier* const barrier_;
844};
845
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000846void JitCodeCache::NotifyCollectionDone(Thread* self) {
847 collection_in_progress_ = false;
848 lock_cond_.Broadcast(self);
849}
850
851void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
852 size_t per_space_footprint = new_footprint / 2;
853 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
854 DCHECK_EQ(per_space_footprint * 2, new_footprint);
855 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
856 {
857 ScopedCodeCacheWrite scc(code_map_.get());
858 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
859 }
860}
861
862bool JitCodeCache::IncreaseCodeCacheCapacity() {
863 if (current_capacity_ == max_capacity_) {
864 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100865 }
866
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000867 // Double the capacity if we're below 1MB, or increase it by 1MB if
868 // we're above.
869 if (current_capacity_ < 1 * MB) {
870 current_capacity_ *= 2;
871 } else {
872 current_capacity_ += 1 * MB;
873 }
874 if (current_capacity_ > max_capacity_) {
875 current_capacity_ = max_capacity_;
876 }
877
878 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
879 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
880 }
881
882 SetFootprintLimit(current_capacity_);
883
884 return true;
885}
886
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000887void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
888 Barrier barrier(0);
889 size_t threads_running_checkpoint = 0;
890 MarkCodeClosure closure(this, &barrier);
891 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
892 // Now that we have run our checkpoint, move to a suspended state and wait
893 // for other threads to run the checkpoint.
894 ScopedThreadSuspension sts(self, kSuspended);
895 if (threads_running_checkpoint != 0) {
896 barrier.Increment(self, threads_running_checkpoint);
897 }
898}
899
Nicolas Geoffray35122442016-03-02 12:05:30 +0000900bool JitCodeCache::ShouldDoFullCollection() {
901 if (current_capacity_ == max_capacity_) {
902 // Always do a full collection when the code cache is full.
903 return true;
904 } else if (current_capacity_ < kReservedCapacity) {
905 // Always do partial collection when the code cache size is below the reserved
906 // capacity.
907 return false;
908 } else if (last_collection_increased_code_cache_) {
909 // This time do a full collection.
910 return true;
911 } else {
912 // This time do a partial collection.
913 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000914 }
915}
916
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000917void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800918 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000919 if (!garbage_collect_code_) {
920 MutexLock mu(self, lock_);
921 IncreaseCodeCacheCapacity();
922 return;
923 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100924
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000925 // Wait for an existing collection, or let everyone know we are starting one.
926 {
927 ScopedThreadSuspension sts(self, kSuspended);
928 MutexLock mu(self, lock_);
929 if (WaitForPotentialCollectionToComplete(self)) {
930 return;
931 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000932 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000933 live_bitmap_.reset(CodeCacheBitmap::Create(
934 "code-cache-bitmap",
935 reinterpret_cast<uintptr_t>(code_map_->Begin()),
936 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000937 collection_in_progress_ = true;
938 }
939 }
940
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000941 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000942 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000943 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000944
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000945 bool do_full_collection = false;
946 {
947 MutexLock mu(self, lock_);
948 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000949 }
950
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000951 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
952 LOG(INFO) << "Do "
953 << (do_full_collection ? "full" : "partial")
954 << " code cache collection, code="
955 << PrettySize(CodeCacheSize())
956 << ", data=" << PrettySize(DataCacheSize());
957 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000958
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000959 DoCollection(self, /* collect_profiling_info */ do_full_collection);
960
961 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
962 LOG(INFO) << "After code cache collection, code="
963 << PrettySize(CodeCacheSize())
964 << ", data=" << PrettySize(DataCacheSize());
965 }
966
967 {
968 MutexLock mu(self, lock_);
969
970 // Increase the code cache only when we do partial collections.
971 // TODO: base this strategy on how full the code cache is?
972 if (do_full_collection) {
973 last_collection_increased_code_cache_ = false;
974 } else {
975 last_collection_increased_code_cache_ = true;
976 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000977 }
978
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000979 bool next_collection_will_be_full = ShouldDoFullCollection();
980
981 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100982 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000983 // Save the entry point of methods we have compiled, and update the entry
984 // point of those methods to the interpreter. If the method is invoked, the
985 // interpreter will update its entry point to the compiled code and call it.
986 for (ProfilingInfo* info : profiling_infos_) {
987 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
988 if (ContainsPc(entry_point)) {
989 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100990 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
991 info->GetMethod(), GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000992 }
993 }
994
995 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
996 }
997 live_bitmap_.reset(nullptr);
998 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000999 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001000 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001001 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001002}
1003
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001004void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001005 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001006 std::unordered_set<OatQuickMethodHeader*> method_headers;
1007 {
1008 MutexLock mu(self, lock_);
1009 ScopedCodeCacheWrite scc(code_map_.get());
1010 // Iterate over all compiled code and remove entries that are not marked.
1011 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1012 const void* code_ptr = it->first;
1013 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1014 if (GetLiveBitmap()->Test(allocation)) {
1015 ++it;
1016 } else {
1017 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
1018 it = method_code_map_.erase(it);
1019 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001020 }
1021 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001022 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001023}
1024
1025void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001026 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001027 {
1028 MutexLock mu(self, lock_);
1029 if (collect_profiling_info) {
1030 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1031 // Also remove the saved entry point from the ProfilingInfo objects.
1032 for (ProfilingInfo* info : profiling_infos_) {
1033 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001034 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001035 info->GetMethod()->SetProfilingInfo(nullptr);
1036 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001037
1038 if (info->GetSavedEntryPoint() != nullptr) {
1039 info->SetSavedEntryPoint(nullptr);
1040 // We are going to move this method back to interpreter. Clear the counter now to
1041 // give it a chance to be hot again.
1042 info->GetMethod()->ClearCounter();
1043 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001044 }
1045 } else if (kIsDebugBuild) {
1046 // Sanity check that the profiling infos do not have a dangling entry point.
1047 for (ProfilingInfo* info : profiling_infos_) {
1048 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001049 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001050 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001051
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001052 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1053 // an entry point is either:
1054 // - an osr compiled code, that will be removed if not in a thread call stack.
1055 // - discarded compiled code, that will be removed if not in a thread call stack.
1056 for (const auto& it : method_code_map_) {
1057 ArtMethod* method = it.second;
1058 const void* code_ptr = it.first;
1059 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1060 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1061 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1062 }
1063 }
1064
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001065 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001066 // on thread stacks).
1067 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001068 }
1069
1070 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001071 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001072
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001073 // At this point, mutator threads are still running, and entrypoints of methods can
1074 // change. We do know they cannot change to a code cache entry that is not marked,
1075 // therefore we can safely remove those entries.
1076 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001077
Nicolas Geoffray35122442016-03-02 12:05:30 +00001078 if (collect_profiling_info) {
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +01001079 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001080 MutexLock mu(self, lock_);
1081 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001082 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001083 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001084 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001085 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1086 // that the compiled code would not get revived. As mutator threads run concurrently,
1087 // they may have revived the compiled code, and now we are in the situation where
1088 // a method has compiled code but no ProfilingInfo.
1089 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1090 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001091 if (ContainsPc(ptr) &&
1092 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001093 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001094 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001095 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001096 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001097 return true;
1098 }
1099 return false;
1100 });
1101 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001102 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001103 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001104}
1105
Nicolas Geoffray35122442016-03-02 12:05:30 +00001106bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001107 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001108 // Check that methods we have compiled do have a ProfilingInfo object. We would
1109 // have memory leaks of compiled code otherwise.
1110 for (const auto& it : method_code_map_) {
1111 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001112 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001113 const void* code_ptr = it.first;
1114 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1115 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1116 // If the code is not dead, then we have a problem. Note that this can even
1117 // happen just after a collection, as mutator threads are running in parallel
1118 // and could deoptimize an existing compiled code.
1119 return false;
1120 }
1121 }
1122 }
1123 return true;
1124}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001125
1126OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
1127 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
1128 if (kRuntimeISA == kArm) {
1129 // On Thumb-2, the pc is offset by one.
1130 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001131 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001132 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1133 return nullptr;
1134 }
1135
1136 MutexLock mu(Thread::Current(), lock_);
1137 if (method_code_map_.empty()) {
1138 return nullptr;
1139 }
1140 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1141 --it;
1142
1143 const void* code_ptr = it->first;
1144 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1145 if (!method_header->Contains(pc)) {
1146 return nullptr;
1147 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001148 if (kIsDebugBuild && method != nullptr) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001149 // When we are walking the stack to redefine classes and creating obsolete methods it is
1150 // possible that we might have updated the method_code_map by making this method obsolete in a
1151 // previous frame. Therefore we should just check that the non-obsolete version of this method
1152 // is the one we expect. We change to the non-obsolete versions in the error message since the
1153 // obsolete version of the method might not be fully initialized yet. This situation can only
1154 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
1155 // method and it->second should be identical. (See runtime/openjdkjvmti/ti_redefine.cc for more
1156 // information.)
1157 DCHECK_EQ(it->second->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
1158 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
1159 << ArtMethod::PrettyMethod(it->second->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001160 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001161 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001162 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001163}
1164
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001165OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1166 MutexLock mu(Thread::Current(), lock_);
1167 auto it = osr_code_map_.find(method);
1168 if (it == osr_code_map_.end()) {
1169 return nullptr;
1170 }
1171 return OatQuickMethodHeader::FromCodePointer(it->second);
1172}
1173
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001174ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1175 ArtMethod* method,
1176 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001177 bool retry_allocation)
1178 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1179 NO_THREAD_SAFETY_ANALYSIS {
1180 ProfilingInfo* info = nullptr;
1181 if (!retry_allocation) {
1182 // If we are allocating for the interpreter, just try to lock, to avoid
1183 // lock contention with the JIT.
1184 if (lock_.ExclusiveTryLock(self)) {
1185 info = AddProfilingInfoInternal(self, method, entries);
1186 lock_.ExclusiveUnlock(self);
1187 }
1188 } else {
1189 {
1190 MutexLock mu(self, lock_);
1191 info = AddProfilingInfoInternal(self, method, entries);
1192 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001193
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001194 if (info == nullptr) {
1195 GarbageCollectCache(self);
1196 MutexLock mu(self, lock_);
1197 info = AddProfilingInfoInternal(self, method, entries);
1198 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001199 }
1200 return info;
1201}
1202
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001203ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001204 ArtMethod* method,
1205 const std::vector<uint32_t>& entries) {
1206 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001207 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001208 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001209
1210 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001211 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001212 if (info != nullptr) {
1213 return info;
1214 }
1215
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001216 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001217 if (data == nullptr) {
1218 return nullptr;
1219 }
1220 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001221
1222 // Make sure other threads see the data in the profiling info object before the
1223 // store in the ArtMethod's ProfilingInfo pointer.
1224 QuasiAtomic::ThreadFenceRelease();
1225
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001226 method->SetProfilingInfo(info);
1227 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001228 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001229 return info;
1230}
1231
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001232// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1233// is already held.
1234void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1235 if (code_mspace_ == mspace) {
1236 size_t result = code_end_;
1237 code_end_ += increment;
1238 return reinterpret_cast<void*>(result + code_map_->Begin());
1239 } else {
1240 DCHECK_EQ(data_mspace_, mspace);
1241 size_t result = data_end_;
1242 data_end_ += increment;
1243 return reinterpret_cast<void*>(result + data_map_->Begin());
1244 }
1245}
1246
Calin Juravle99629622016-04-19 16:33:46 +01001247void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001248 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001249 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001250 MutexLock mu(Thread::Current(), lock_);
Calin Juravle99629622016-04-19 16:33:46 +01001251 for (const ProfilingInfo* info : profiling_infos_) {
1252 ArtMethod* method = info->GetMethod();
1253 const DexFile* dex_file = method->GetDexFile();
Calin Juravle940eb0c2017-01-30 19:30:44 -08001254 if (!ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
1255 // Skip dex files which are not profiled.
1256 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001257 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001258 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
1259 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
1260 std::vector<ProfileMethodInfo::ProfileClassReference> profile_classes;
1261 const InlineCache& cache = info->cache_[i];
1262 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1263 mirror::Class* cls = cache.classes_[k].Read();
1264 if (cls == nullptr) {
1265 break;
1266 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001267
1268 const DexFile* class_dex_file = nullptr;
1269 dex::TypeIndex type_index;
1270
1271 if (cls->GetDexCache() == nullptr) {
1272 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
1273 class_dex_file = dex_file;
1274 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1275 } else {
1276 class_dex_file = &(cls->GetDexFile());
1277 type_index = cls->GetDexTypeIndex();
1278 }
1279 if (!type_index.IsValid()) {
1280 // Could be a proxy class or an array for which we couldn't find the type index.
1281 // TODO(calin): can we really miss the type index for arrays here?
1282 continue;
1283 }
1284 if (ContainsElement(dex_base_locations, class_dex_file->GetBaseLocation())) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001285 // Only consider classes from the same apk (including multidex).
1286 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001287 class_dex_file, type_index);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001288 }
1289 }
1290 if (!profile_classes.empty()) {
1291 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
1292 cache.dex_pc_, profile_classes);
1293 }
1294 }
1295 methods.emplace_back(/*ProfileMethodInfo*/
1296 dex_file, method->GetDexMethodIndex(), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001297 }
1298}
1299
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001300uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1301 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001302}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001303
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001304bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1305 MutexLock mu(Thread::Current(), lock_);
1306 return osr_code_map_.find(method) != osr_code_map_.end();
1307}
1308
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001309bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1310 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001311 return false;
1312 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001313
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001314 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001315 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1316 return false;
1317 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001318
Andreas Gampe542451c2016-07-26 09:02:02 -07001319 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001320 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001321 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001322 // Because the counter is not atomic, there are some rare cases where we may not
1323 // hit the threshold for creating the ProfilingInfo. Reset the counter now to
1324 // "correct" this.
1325 method->ClearCounter();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001326 return false;
1327 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001328
buzbee454b3b62016-04-07 14:42:47 -07001329 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001330 return false;
1331 }
1332
buzbee454b3b62016-04-07 14:42:47 -07001333 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001334 return true;
1335}
1336
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001337ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001338 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001339 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001340 if (info != nullptr) {
1341 info->IncrementInlineUse();
1342 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001343 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001344}
1345
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001346void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001347 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001348 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001349 DCHECK(info != nullptr);
1350 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001351}
1352
buzbee454b3b62016-04-07 14:42:47 -07001353void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001354 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001355 DCHECK(info->IsMethodBeingCompiled(osr));
1356 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001357}
1358
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001359size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1360 MutexLock mu(Thread::Current(), lock_);
1361 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1362}
1363
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001364void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1365 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001366 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001367 if ((profiling_info != nullptr) &&
1368 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1369 // Prevent future uses of the compiled code.
1370 profiling_info->SetSavedEntryPoint(nullptr);
1371 }
1372
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001373 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
1374 // The entrypoint is the one to invalidate, so we just update
1375 // it to the interpreter entry point and clear the counter to get the method
1376 // Jitted again.
1377 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1378 method, GetQuickToInterpreterBridge());
1379 method->ClearCounter();
1380 } else {
1381 MutexLock mu(Thread::Current(), lock_);
1382 auto it = osr_code_map_.find(method);
1383 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1384 // Remove the OSR method, to avoid using it again.
1385 osr_code_map_.erase(it);
1386 }
1387 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001388 MutexLock mu(Thread::Current(), lock_);
1389 number_of_deoptimizations_++;
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001390}
1391
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001392uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1393 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1394 uint8_t* result = reinterpret_cast<uint8_t*>(
1395 mspace_memalign(code_mspace_, alignment, code_size));
1396 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1397 // Ensure the header ends up at expected instruction alignment.
1398 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1399 used_memory_for_code_ += mspace_usable_size(result);
1400 return result;
1401}
1402
1403void JitCodeCache::FreeCode(uint8_t* code) {
1404 used_memory_for_code_ -= mspace_usable_size(code);
1405 mspace_free(code_mspace_, code);
1406}
1407
1408uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1409 void* result = mspace_malloc(data_mspace_, data_size);
1410 used_memory_for_data_ += mspace_usable_size(result);
1411 return reinterpret_cast<uint8_t*>(result);
1412}
1413
1414void JitCodeCache::FreeData(uint8_t* data) {
1415 used_memory_for_data_ -= mspace_usable_size(data);
1416 mspace_free(data_mspace_, data);
1417}
1418
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001419void JitCodeCache::Dump(std::ostream& os) {
1420 MutexLock mu(Thread::Current(), lock_);
1421 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1422 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1423 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1424 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1425 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1426 << "Total number of JIT compilations for on stack replacement: "
1427 << number_of_osr_compilations_ << "\n"
1428 << "Total number of deoptimizations: " << number_of_deoptimizations_ << "\n"
1429 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001430 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1431 histogram_code_memory_use_.PrintMemoryUse(os);
1432 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001433}
1434
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001435} // namespace jit
1436} // namespace art