blob: 1b0ad8341bd1c3eb8f7b80a3f1434d78c146686d [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 Geoffray132d8362016-11-16 09:19:42 +0000220 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700221 Handle<mirror::ObjectArray<mirror::Object>> roots,
222 bool has_should_deoptimize_flag,
223 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100224 uint8_t* result = CommitCodeInternal(self,
225 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000226 stack_map,
227 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100228 frame_size_in_bytes,
229 core_spill_mask,
230 fp_spill_mask,
231 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000232 code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000233 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700234 roots,
235 has_should_deoptimize_flag,
236 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100237 if (result == nullptr) {
238 // Retry.
239 GarbageCollectCache(self);
240 result = CommitCodeInternal(self,
241 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000242 stack_map,
243 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100244 frame_size_in_bytes,
245 core_spill_mask,
246 fp_spill_mask,
247 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000248 code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000249 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700250 roots,
251 has_should_deoptimize_flag,
252 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100253 }
254 return result;
255}
256
257bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
258 bool in_collection = false;
259 while (collection_in_progress_) {
260 in_collection = true;
261 lock_cond_.Wait(self);
262 }
263 return in_collection;
264}
265
266static uintptr_t FromCodeToAllocation(const void* code) {
267 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
268 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
269}
270
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000271static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
272 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
273}
274
275static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
276 // The length of the table is stored just before the stack map (and therefore at the end of
277 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
278 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
279}
280
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800281static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
282 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
283 // pointer.
284 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
285}
286
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000287static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
288 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
289}
290
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000291static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
292 REQUIRES_SHARED(Locks::mutator_lock_) {
293 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800294 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000295 // Put all roots in `roots_data`.
296 for (uint32_t i = 0; i < length; ++i) {
297 ObjPtr<mirror::Object> object = roots->Get(i);
298 if (kIsDebugBuild) {
299 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000300 if (object->IsString()) {
301 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
302 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
303 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
304 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000305 }
306 gc_roots[i] = GcRoot<mirror::Object>(object);
307 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000308}
309
310static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
311 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
312 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
313 uint32_t roots = GetNumberOfRoots(data);
314 if (number_of_roots != nullptr) {
315 *number_of_roots = roots;
316 }
317 return data - ComputeRootTableSize(roots);
318}
319
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000320// Helper for the GC to process a weak class in a JIT root table.
321static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr, IsMarkedVisitor* visitor)
322 REQUIRES_SHARED(Locks::mutator_lock_) {
323 // This does not need a read barrier because this is called by GC.
324 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
325 if (cls != nullptr) {
326 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
327 // Look at the classloader of the class to know if it has been unloaded.
328 // This does not need a read barrier because this is called by GC.
329 mirror::Object* class_loader =
330 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
331 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
332 // The class loader is live, update the entry if the class has moved.
333 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
334 // Note that new_object can be null for CMS and newly allocated objects.
335 if (new_cls != nullptr && new_cls != cls) {
336 *root_ptr = GcRoot<mirror::Class>(new_cls);
337 }
338 } else {
339 // The class loader is not live, clear the entry.
340 *root_ptr = GcRoot<mirror::Class>(nullptr);
341 }
342 }
343}
344
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000345void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
346 MutexLock mu(Thread::Current(), lock_);
347 for (const auto& entry : method_code_map_) {
348 uint32_t number_of_roots = 0;
349 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
350 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
351 for (uint32_t i = 0; i < number_of_roots; ++i) {
352 // This does not need a read barrier because this is called by GC.
353 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000354 if (object == nullptr) {
355 // entry got deleted in a previous sweep.
356 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
357 mirror::Object* new_object = visitor->IsMarked(object);
358 // We know the string is marked because it's a strongly-interned string that
359 // is always alive. The IsMarked implementation of the CMS collector returns
360 // null for newly allocated objects, but we know those haven't moved. Therefore,
361 // only update the entry if we get a different non-null string.
362 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
363 // out of the weak access/creation pause. b/32167580
364 if (new_object != nullptr && new_object != object) {
365 DCHECK(new_object->IsString());
366 roots[i] = GcRoot<mirror::Object>(new_object);
367 }
368 } else {
369 ProcessWeakClass(reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000370 }
371 }
372 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000373 // Walk over inline caches to clear entries containing unloaded classes.
374 for (ProfilingInfo* info : profiling_infos_) {
375 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
376 InlineCache* cache = &info->cache_[i];
377 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000378 ProcessWeakClass(&cache->classes_[j], visitor);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000379 }
380 }
381 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000382}
383
Mingyao Yang063fc772016-08-02 11:02:54 -0700384void JitCodeCache::FreeCode(const void* code_ptr) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100385 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000386 // Notify native debugger that we are about to remove the code.
387 // It does nothing if we are not using native debugger.
388 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000389 FreeData(GetRootTable(code_ptr));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000390 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100391}
392
Mingyao Yang063fc772016-08-02 11:02:54 -0700393void JitCodeCache::FreeAllMethodHeaders(
394 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
395 {
396 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
397 Runtime::Current()->GetClassHierarchyAnalysis()
398 ->RemoveDependentsWithMethodHeaders(method_headers);
399 }
400
401 // We need to remove entries in method_headers from CHA dependencies
402 // first since once we do FreeCode() below, the memory can be reused
403 // so it's possible for the same method_header to start representing
404 // different compile code.
405 MutexLock mu(Thread::Current(), lock_);
406 ScopedCodeCacheWrite scc(code_map_.get());
407 for (const OatQuickMethodHeader* method_header : method_headers) {
408 FreeCode(method_header->GetCode());
409 }
410}
411
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100412void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800413 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700414 // We use a set to first collect all method_headers whose code need to be
415 // removed. We need to free the underlying code after we remove CHA dependencies
416 // for entries in this set. And it's more efficient to iterate through
417 // the CHA dependency map just once with an unordered_set.
418 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000419 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700420 MutexLock mu(self, lock_);
421 // We do not check if a code cache GC is in progress, as this method comes
422 // with the classlinker_classes_lock_ held, and suspending ourselves could
423 // lead to a deadlock.
424 {
425 ScopedCodeCacheWrite scc(code_map_.get());
426 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
427 if (alloc.ContainsUnsafe(it->second)) {
428 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
429 it = method_code_map_.erase(it);
430 } else {
431 ++it;
432 }
433 }
434 }
435 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
436 if (alloc.ContainsUnsafe(it->first)) {
437 // Note that the code has already been pushed to method_headers in the loop
438 // above and is going to be removed in FreeCode() below.
439 it = osr_code_map_.erase(it);
440 } else {
441 ++it;
442 }
443 }
444 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
445 ProfilingInfo* info = *it;
446 if (alloc.ContainsUnsafe(info->GetMethod())) {
447 info->GetMethod()->SetProfilingInfo(nullptr);
448 FreeData(reinterpret_cast<uint8_t*>(info));
449 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000450 } else {
451 ++it;
452 }
453 }
454 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700455 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100456}
457
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000458bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
459 return kUseReadBarrier
460 ? self->GetWeakRefAccessEnabled()
461 : is_weak_access_enabled_.LoadSequentiallyConsistent();
462}
463
464void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
465 if (IsWeakAccessEnabled(self)) {
466 return;
467 }
468 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000469 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000470 while (!IsWeakAccessEnabled(self)) {
471 inline_cache_cond_.Wait(self);
472 }
473}
474
475void JitCodeCache::BroadcastForInlineCacheAccess() {
476 Thread* self = Thread::Current();
477 MutexLock mu(self, lock_);
478 inline_cache_cond_.Broadcast(self);
479}
480
481void JitCodeCache::AllowInlineCacheAccess() {
482 DCHECK(!kUseReadBarrier);
483 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
484 BroadcastForInlineCacheAccess();
485}
486
487void JitCodeCache::DisallowInlineCacheAccess() {
488 DCHECK(!kUseReadBarrier);
489 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
490}
491
492void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
493 Handle<mirror::ObjectArray<mirror::Class>> array) {
494 WaitUntilInlineCacheAccessible(Thread::Current());
495 // Note that we don't need to lock `lock_` here, the compiler calling
496 // this method has already ensured the inline cache will not be deleted.
497 for (size_t in_cache = 0, in_array = 0;
498 in_cache < InlineCache::kIndividualCacheSize;
499 ++in_cache) {
500 mirror::Class* object = ic.classes_[in_cache].Read();
501 if (object != nullptr) {
502 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000503 }
504 }
505}
506
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100507uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
508 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000509 uint8_t* stack_map,
510 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100511 size_t frame_size_in_bytes,
512 size_t core_spill_mask,
513 size_t fp_spill_mask,
514 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000515 size_t code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000516 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700517 Handle<mirror::ObjectArray<mirror::Object>> roots,
518 bool has_should_deoptimize_flag,
519 const ArenaSet<ArtMethod*>&
520 cha_single_implementation_list) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000521 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100522 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
523 // Ensure the header ends up at expected instruction alignment.
524 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
525 size_t total_size = header_size + code_size;
526
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100527 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100528 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000529 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100530 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000531 ScopedThreadSuspension sts(self, kSuspended);
532 MutexLock mu(self, lock_);
533 WaitForPotentialCollectionToComplete(self);
534 {
535 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000536 memory = AllocateCode(total_size);
537 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000538 return nullptr;
539 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000540 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000541
542 std::copy(code, code + code_size, code_ptr);
543 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
544 new (method_header) OatQuickMethodHeader(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000545 code_ptr - stack_map,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000546 frame_size_in_bytes,
547 core_spill_mask,
548 fp_spill_mask,
549 code_size);
Artem Udovichenkob18a6692016-11-17 10:51:58 +0300550 // Flush caches before we remove write permission because on some ARMv8 hardware,
551 // flushing caches require write permissions.
552 //
553 // For reference, here are kernel patches discussing about this issue:
554 // https://android.googlesource.com/kernel/msm/%2B/0e7f7bcc3fc87489cda5aa6aff8ce40eed912279
555 // https://patchwork.kernel.org/patch/9047921/
556 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
557 reinterpret_cast<char*>(code_ptr + code_size));
Mingyao Yang063fc772016-08-02 11:02:54 -0700558 DCHECK(!Runtime::Current()->IsAotCompiler());
559 if (has_should_deoptimize_flag) {
560 method_header->SetHasShouldDeoptimizeFlag();
561 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100562 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100563
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000564 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100565 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000566 // We need to update the entry point in the runnable state for the instrumentation.
567 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700568 // Need cha_lock_ for checking all single-implementation flags and register
569 // dependencies.
570 MutexLock cha_mu(self, *Locks::cha_lock_);
571 bool single_impl_still_valid = true;
572 for (ArtMethod* single_impl : cha_single_implementation_list) {
573 if (!single_impl->HasSingleImplementation()) {
574 // We simply discard the compiled code. Clear the
575 // counter so that it may be recompiled later. Hopefully the
576 // class hierarchy will be more stable when compilation is retried.
577 single_impl_still_valid = false;
578 method->ClearCounter();
579 break;
580 }
581 }
582
583 // Discard the code if any single-implementation assumptions are now invalid.
584 if (!single_impl_still_valid) {
585 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
586 return nullptr;
587 }
588 for (ArtMethod* single_impl : cha_single_implementation_list) {
589 Runtime::Current()->GetClassHierarchyAnalysis()->AddDependency(
590 single_impl, method, method_header);
591 }
592
593 // The following needs to be guarded by cha_lock_ also. Otherwise it's
594 // possible that the compiled code is considered invalidated by some class linking,
595 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000596 MutexLock mu(self, lock_);
597 method_code_map_.Put(code_ptr, method);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000598 // Fill the root table before updating the entry point.
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000599 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000600 FillRootTable(roots_data, roots);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000601 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000602 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000603 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100604 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000605 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
606 method, method_header->GetEntryPoint());
607 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000608 if (collection_in_progress_) {
609 // We need to update the live bitmap if there is a GC to ensure it sees this new
610 // code.
611 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
612 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000613 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000614 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100615 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700616 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000617 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
618 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
619 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700620 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
621 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000622 histogram_code_memory_use_.AddValue(code_size);
623 if (code_size > kCodeSizeLogThreshold) {
624 LOG(INFO) << "JIT allocated "
625 << PrettySize(code_size)
626 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700627 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000628 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000629 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100630
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100631 return reinterpret_cast<uint8_t*>(method_header);
632}
633
634size_t JitCodeCache::CodeCacheSize() {
635 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000636 return CodeCacheSizeLocked();
637}
638
639size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000640 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100641}
642
643size_t JitCodeCache::DataCacheSize() {
644 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000645 return DataCacheSizeLocked();
646}
647
648size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000649 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800650}
651
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000652void JitCodeCache::ClearData(Thread* self,
653 uint8_t* stack_map_data,
654 uint8_t* roots_data) {
655 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000656 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000657 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000658}
659
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000660void JitCodeCache::ReserveData(Thread* self,
661 size_t stack_map_size,
662 size_t number_of_roots,
663 ArtMethod* method,
664 uint8_t** stack_map_data,
665 uint8_t** roots_data) {
666 size_t table_size = ComputeRootTableSize(number_of_roots);
667 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100668 uint8_t* result = nullptr;
669
670 {
671 ScopedThreadSuspension sts(self, kSuspended);
672 MutexLock mu(self, lock_);
673 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000674 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100675 }
676
677 if (result == nullptr) {
678 // Retry.
679 GarbageCollectCache(self);
680 ScopedThreadSuspension sts(self, kSuspended);
681 MutexLock mu(self, lock_);
682 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000683 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100684 }
685
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000686 MutexLock mu(self, lock_);
687 histogram_stack_map_memory_use_.AddValue(size);
688 if (size > kStackMapSizeLogThreshold) {
689 LOG(INFO) << "JIT allocated "
690 << PrettySize(size)
691 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700692 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800693 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000694 if (result != nullptr) {
695 *roots_data = result;
696 *stack_map_data = result + table_size;
697 FillRootTableLength(*roots_data, number_of_roots);
698 } else {
699 *roots_data = nullptr;
700 *stack_map_data = nullptr;
701 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800702}
703
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100704class MarkCodeVisitor FINAL : public StackVisitor {
705 public:
706 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
707 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
708 code_cache_(code_cache_in),
709 bitmap_(code_cache_->GetLiveBitmap()) {}
710
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700711 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100712 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
713 if (method_header == nullptr) {
714 return true;
715 }
716 const void* code = method_header->GetCode();
717 if (code_cache_->ContainsPc(code)) {
718 // Use the atomic set version, as multiple threads are executing this code.
719 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
720 }
721 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800722 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100723
724 private:
725 JitCodeCache* const code_cache_;
726 CodeCacheBitmap* const bitmap_;
727};
728
729class MarkCodeClosure FINAL : public Closure {
730 public:
731 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
732 : code_cache_(code_cache), barrier_(barrier) {}
733
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700734 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800735 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100736 DCHECK(thread == Thread::Current() || thread->IsSuspended());
737 MarkCodeVisitor visitor(thread, code_cache_);
738 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000739 if (kIsDebugBuild) {
740 // The stack walking code queries the side instrumentation stack if it
741 // sees an instrumentation exit pc, so the JIT code of methods in that stack
742 // must have been seen. We sanity check this below.
743 for (const instrumentation::InstrumentationStackFrame& frame
744 : *thread->GetInstrumentationStack()) {
745 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
746 // its stack frame, it is not the method owning return_pc_. We just pass null to
747 // LookupMethodHeader: the method is only checked against in debug builds.
748 OatQuickMethodHeader* method_header =
749 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
750 if (method_header != nullptr) {
751 const void* code = method_header->GetCode();
752 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
753 }
754 }
755 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700756 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800757 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100758
759 private:
760 JitCodeCache* const code_cache_;
761 Barrier* const barrier_;
762};
763
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000764void JitCodeCache::NotifyCollectionDone(Thread* self) {
765 collection_in_progress_ = false;
766 lock_cond_.Broadcast(self);
767}
768
769void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
770 size_t per_space_footprint = new_footprint / 2;
771 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
772 DCHECK_EQ(per_space_footprint * 2, new_footprint);
773 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
774 {
775 ScopedCodeCacheWrite scc(code_map_.get());
776 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
777 }
778}
779
780bool JitCodeCache::IncreaseCodeCacheCapacity() {
781 if (current_capacity_ == max_capacity_) {
782 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100783 }
784
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000785 // Double the capacity if we're below 1MB, or increase it by 1MB if
786 // we're above.
787 if (current_capacity_ < 1 * MB) {
788 current_capacity_ *= 2;
789 } else {
790 current_capacity_ += 1 * MB;
791 }
792 if (current_capacity_ > max_capacity_) {
793 current_capacity_ = max_capacity_;
794 }
795
796 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
797 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
798 }
799
800 SetFootprintLimit(current_capacity_);
801
802 return true;
803}
804
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000805void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
806 Barrier barrier(0);
807 size_t threads_running_checkpoint = 0;
808 MarkCodeClosure closure(this, &barrier);
809 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
810 // Now that we have run our checkpoint, move to a suspended state and wait
811 // for other threads to run the checkpoint.
812 ScopedThreadSuspension sts(self, kSuspended);
813 if (threads_running_checkpoint != 0) {
814 barrier.Increment(self, threads_running_checkpoint);
815 }
816}
817
Nicolas Geoffray35122442016-03-02 12:05:30 +0000818bool JitCodeCache::ShouldDoFullCollection() {
819 if (current_capacity_ == max_capacity_) {
820 // Always do a full collection when the code cache is full.
821 return true;
822 } else if (current_capacity_ < kReservedCapacity) {
823 // Always do partial collection when the code cache size is below the reserved
824 // capacity.
825 return false;
826 } else if (last_collection_increased_code_cache_) {
827 // This time do a full collection.
828 return true;
829 } else {
830 // This time do a partial collection.
831 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000832 }
833}
834
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000835void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800836 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000837 if (!garbage_collect_code_) {
838 MutexLock mu(self, lock_);
839 IncreaseCodeCacheCapacity();
840 return;
841 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100842
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000843 // Wait for an existing collection, or let everyone know we are starting one.
844 {
845 ScopedThreadSuspension sts(self, kSuspended);
846 MutexLock mu(self, lock_);
847 if (WaitForPotentialCollectionToComplete(self)) {
848 return;
849 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000850 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000851 live_bitmap_.reset(CodeCacheBitmap::Create(
852 "code-cache-bitmap",
853 reinterpret_cast<uintptr_t>(code_map_->Begin()),
854 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000855 collection_in_progress_ = true;
856 }
857 }
858
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000859 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000860 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000861 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000862
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000863 bool do_full_collection = false;
864 {
865 MutexLock mu(self, lock_);
866 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000867 }
868
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000869 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
870 LOG(INFO) << "Do "
871 << (do_full_collection ? "full" : "partial")
872 << " code cache collection, code="
873 << PrettySize(CodeCacheSize())
874 << ", data=" << PrettySize(DataCacheSize());
875 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000876
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000877 DoCollection(self, /* collect_profiling_info */ do_full_collection);
878
879 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
880 LOG(INFO) << "After code cache collection, code="
881 << PrettySize(CodeCacheSize())
882 << ", data=" << PrettySize(DataCacheSize());
883 }
884
885 {
886 MutexLock mu(self, lock_);
887
888 // Increase the code cache only when we do partial collections.
889 // TODO: base this strategy on how full the code cache is?
890 if (do_full_collection) {
891 last_collection_increased_code_cache_ = false;
892 } else {
893 last_collection_increased_code_cache_ = true;
894 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000895 }
896
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000897 bool next_collection_will_be_full = ShouldDoFullCollection();
898
899 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100900 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000901 // Save the entry point of methods we have compiled, and update the entry
902 // point of those methods to the interpreter. If the method is invoked, the
903 // interpreter will update its entry point to the compiled code and call it.
904 for (ProfilingInfo* info : profiling_infos_) {
905 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
906 if (ContainsPc(entry_point)) {
907 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100908 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
909 info->GetMethod(), GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000910 }
911 }
912
913 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
914 }
915 live_bitmap_.reset(nullptr);
916 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000917 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000918 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000919 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000920}
921
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000922void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800923 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700924 std::unordered_set<OatQuickMethodHeader*> method_headers;
925 {
926 MutexLock mu(self, lock_);
927 ScopedCodeCacheWrite scc(code_map_.get());
928 // Iterate over all compiled code and remove entries that are not marked.
929 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
930 const void* code_ptr = it->first;
931 uintptr_t allocation = FromCodeToAllocation(code_ptr);
932 if (GetLiveBitmap()->Test(allocation)) {
933 ++it;
934 } else {
935 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
936 it = method_code_map_.erase(it);
937 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000938 }
939 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700940 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000941}
942
943void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800944 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000945 {
946 MutexLock mu(self, lock_);
947 if (collect_profiling_info) {
948 // Clear the profiling info of methods that do not have compiled code as entrypoint.
949 // Also remove the saved entry point from the ProfilingInfo objects.
950 for (ProfilingInfo* info : profiling_infos_) {
951 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000952 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000953 info->GetMethod()->SetProfilingInfo(nullptr);
954 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +0000955
956 if (info->GetSavedEntryPoint() != nullptr) {
957 info->SetSavedEntryPoint(nullptr);
958 // We are going to move this method back to interpreter. Clear the counter now to
959 // give it a chance to be hot again.
960 info->GetMethod()->ClearCounter();
961 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000962 }
963 } else if (kIsDebugBuild) {
964 // Sanity check that the profiling infos do not have a dangling entry point.
965 for (ProfilingInfo* info : profiling_infos_) {
966 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100967 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000968 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000969
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000970 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
971 // an entry point is either:
972 // - an osr compiled code, that will be removed if not in a thread call stack.
973 // - discarded compiled code, that will be removed if not in a thread call stack.
974 for (const auto& it : method_code_map_) {
975 ArtMethod* method = it.second;
976 const void* code_ptr = it.first;
977 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
978 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
979 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
980 }
981 }
982
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000983 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000984 // on thread stacks).
985 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100986 }
987
988 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000989 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100990
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000991 // At this point, mutator threads are still running, and entrypoints of methods can
992 // change. We do know they cannot change to a code cache entry that is not marked,
993 // therefore we can safely remove those entries.
994 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000995
Nicolas Geoffray35122442016-03-02 12:05:30 +0000996 if (collect_profiling_info) {
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +0100997 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000998 MutexLock mu(self, lock_);
999 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001000 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001001 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001002 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001003 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1004 // that the compiled code would not get revived. As mutator threads run concurrently,
1005 // they may have revived the compiled code, and now we are in the situation where
1006 // a method has compiled code but no ProfilingInfo.
1007 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1008 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001009 if (ContainsPc(ptr) &&
1010 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001011 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001012 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001013 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001014 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001015 return true;
1016 }
1017 return false;
1018 });
1019 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001020 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001021 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001022}
1023
Nicolas Geoffray35122442016-03-02 12:05:30 +00001024bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001025 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001026 // Check that methods we have compiled do have a ProfilingInfo object. We would
1027 // have memory leaks of compiled code otherwise.
1028 for (const auto& it : method_code_map_) {
1029 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001030 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001031 const void* code_ptr = it.first;
1032 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1033 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1034 // If the code is not dead, then we have a problem. Note that this can even
1035 // happen just after a collection, as mutator threads are running in parallel
1036 // and could deoptimize an existing compiled code.
1037 return false;
1038 }
1039 }
1040 }
1041 return true;
1042}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001043
1044OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
1045 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
1046 if (kRuntimeISA == kArm) {
1047 // On Thumb-2, the pc is offset by one.
1048 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001049 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001050 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1051 return nullptr;
1052 }
1053
1054 MutexLock mu(Thread::Current(), lock_);
1055 if (method_code_map_.empty()) {
1056 return nullptr;
1057 }
1058 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1059 --it;
1060
1061 const void* code_ptr = it->first;
1062 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1063 if (!method_header->Contains(pc)) {
1064 return nullptr;
1065 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001066 if (kIsDebugBuild && method != nullptr) {
1067 DCHECK_EQ(it->second, method)
David Sehr709b0702016-10-13 09:12:37 -07001068 << ArtMethod::PrettyMethod(method) << " " << ArtMethod::PrettyMethod(it->second) << " "
1069 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001070 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001071 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001072}
1073
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001074OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1075 MutexLock mu(Thread::Current(), lock_);
1076 auto it = osr_code_map_.find(method);
1077 if (it == osr_code_map_.end()) {
1078 return nullptr;
1079 }
1080 return OatQuickMethodHeader::FromCodePointer(it->second);
1081}
1082
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001083ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1084 ArtMethod* method,
1085 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001086 bool retry_allocation)
1087 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1088 NO_THREAD_SAFETY_ANALYSIS {
1089 ProfilingInfo* info = nullptr;
1090 if (!retry_allocation) {
1091 // If we are allocating for the interpreter, just try to lock, to avoid
1092 // lock contention with the JIT.
1093 if (lock_.ExclusiveTryLock(self)) {
1094 info = AddProfilingInfoInternal(self, method, entries);
1095 lock_.ExclusiveUnlock(self);
1096 }
1097 } else {
1098 {
1099 MutexLock mu(self, lock_);
1100 info = AddProfilingInfoInternal(self, method, entries);
1101 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001102
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001103 if (info == nullptr) {
1104 GarbageCollectCache(self);
1105 MutexLock mu(self, lock_);
1106 info = AddProfilingInfoInternal(self, method, entries);
1107 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001108 }
1109 return info;
1110}
1111
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001112ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001113 ArtMethod* method,
1114 const std::vector<uint32_t>& entries) {
1115 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001116 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001117 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001118
1119 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001120 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001121 if (info != nullptr) {
1122 return info;
1123 }
1124
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001125 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001126 if (data == nullptr) {
1127 return nullptr;
1128 }
1129 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001130
1131 // Make sure other threads see the data in the profiling info object before the
1132 // store in the ArtMethod's ProfilingInfo pointer.
1133 QuasiAtomic::ThreadFenceRelease();
1134
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001135 method->SetProfilingInfo(info);
1136 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001137 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001138 return info;
1139}
1140
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001141// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1142// is already held.
1143void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1144 if (code_mspace_ == mspace) {
1145 size_t result = code_end_;
1146 code_end_ += increment;
1147 return reinterpret_cast<void*>(result + code_map_->Begin());
1148 } else {
1149 DCHECK_EQ(data_mspace_, mspace);
1150 size_t result = data_end_;
1151 data_end_ += increment;
1152 return reinterpret_cast<void*>(result + data_map_->Begin());
1153 }
1154}
1155
Calin Juravle99629622016-04-19 16:33:46 +01001156void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
1157 std::vector<MethodReference>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001158 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001159 MutexLock mu(Thread::Current(), lock_);
Calin Juravle99629622016-04-19 16:33:46 +01001160 for (const ProfilingInfo* info : profiling_infos_) {
1161 ArtMethod* method = info->GetMethod();
1162 const DexFile* dex_file = method->GetDexFile();
1163 if (ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
1164 methods.emplace_back(dex_file, method->GetDexMethodIndex());
Calin Juravle31f2c152015-10-23 17:56:15 +01001165 }
1166 }
1167}
1168
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001169uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1170 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001171}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001172
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001173bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1174 MutexLock mu(Thread::Current(), lock_);
1175 return osr_code_map_.find(method) != osr_code_map_.end();
1176}
1177
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001178bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1179 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001180 return false;
1181 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001182
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001183 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001184 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1185 return false;
1186 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001187
Andreas Gampe542451c2016-07-26 09:02:02 -07001188 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001189 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001190 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001191 // Because the counter is not atomic, there are some rare cases where we may not
1192 // hit the threshold for creating the ProfilingInfo. Reset the counter now to
1193 // "correct" this.
1194 method->ClearCounter();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001195 return false;
1196 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001197
buzbee454b3b62016-04-07 14:42:47 -07001198 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001199 return false;
1200 }
1201
buzbee454b3b62016-04-07 14:42:47 -07001202 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001203 return true;
1204}
1205
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001206ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001207 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001208 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001209 if (info != nullptr) {
1210 info->IncrementInlineUse();
1211 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001212 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001213}
1214
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001215void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001216 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001217 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001218 DCHECK(info != nullptr);
1219 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001220}
1221
buzbee454b3b62016-04-07 14:42:47 -07001222void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001223 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001224 DCHECK(info->IsMethodBeingCompiled(osr));
1225 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001226}
1227
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001228size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1229 MutexLock mu(Thread::Current(), lock_);
1230 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1231}
1232
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001233void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1234 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001235 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001236 if ((profiling_info != nullptr) &&
1237 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1238 // Prevent future uses of the compiled code.
1239 profiling_info->SetSavedEntryPoint(nullptr);
1240 }
1241
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001242 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
1243 // The entrypoint is the one to invalidate, so we just update
1244 // it to the interpreter entry point and clear the counter to get the method
1245 // Jitted again.
1246 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1247 method, GetQuickToInterpreterBridge());
1248 method->ClearCounter();
1249 } else {
1250 MutexLock mu(Thread::Current(), lock_);
1251 auto it = osr_code_map_.find(method);
1252 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1253 // Remove the OSR method, to avoid using it again.
1254 osr_code_map_.erase(it);
1255 }
1256 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001257 MutexLock mu(Thread::Current(), lock_);
1258 number_of_deoptimizations_++;
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001259}
1260
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001261uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1262 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1263 uint8_t* result = reinterpret_cast<uint8_t*>(
1264 mspace_memalign(code_mspace_, alignment, code_size));
1265 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1266 // Ensure the header ends up at expected instruction alignment.
1267 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1268 used_memory_for_code_ += mspace_usable_size(result);
1269 return result;
1270}
1271
1272void JitCodeCache::FreeCode(uint8_t* code) {
1273 used_memory_for_code_ -= mspace_usable_size(code);
1274 mspace_free(code_mspace_, code);
1275}
1276
1277uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1278 void* result = mspace_malloc(data_mspace_, data_size);
1279 used_memory_for_data_ += mspace_usable_size(result);
1280 return reinterpret_cast<uint8_t*>(result);
1281}
1282
1283void JitCodeCache::FreeData(uint8_t* data) {
1284 used_memory_for_data_ -= mspace_usable_size(data);
1285 mspace_free(data_mspace_, data);
1286}
1287
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001288void JitCodeCache::Dump(std::ostream& os) {
1289 MutexLock mu(Thread::Current(), lock_);
1290 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1291 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1292 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1293 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1294 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1295 << "Total number of JIT compilations for on stack replacement: "
1296 << number_of_osr_compilations_ << "\n"
1297 << "Total number of deoptimizations: " << number_of_deoptimizations_ << "\n"
1298 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001299 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1300 histogram_code_memory_use_.PrintMemoryUse(os);
1301 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001302}
1303
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001304} // namespace jit
1305} // namespace art