blob: 820ae6acabd7a7a2e7f615a7ada24c5c1a2d6044 [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"
Calin Juravle66f55232015-12-08 15:09:10 +000022#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080023#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010024#include "base/time_utils.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000025#include "debugger_interface.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010026#include "entrypoints/runtime_asm_entrypoints.h"
27#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000028#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000029#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010030#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080031#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080032#include "oat_file-inl.h"
Nicolas Geoffray62623402015-10-28 19:15:05 +000033#include "scoped_thread_state_change.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010034#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080035
36namespace art {
37namespace jit {
38
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010039static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
40static constexpr int kProtData = PROT_READ | PROT_WRITE;
41static constexpr int kProtCode = PROT_READ | PROT_EXEC;
42
Nicolas Geoffray933330a2016-03-16 14:20:06 +000043static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
44static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
45
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010046#define CHECKED_MPROTECT(memory, size, prot) \
47 do { \
48 int rc = mprotect(memory, size, prot); \
49 if (UNLIKELY(rc != 0)) { \
50 errno = rc; \
51 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
52 } \
53 } while (false) \
54
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000055JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
56 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000057 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000058 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080059 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000060 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000061
62 // Generating debug information is mostly for using the 'perf' tool, which does
63 // not work with ashmem.
64 bool use_ashmem = !generate_debug_info;
65 // With 'perf', we want a 1-1 mapping between an address and a method.
66 bool garbage_collect_code = !generate_debug_info;
67
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000068 // We need to have 32 bit offsets from method headers in code cache which point to things
69 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
70 // Ensure we're below 1 GB to be safe.
71 if (max_capacity > 1 * GB) {
72 std::ostringstream oss;
73 oss << "Maxium code cache capacity is limited to 1 GB, "
74 << PrettySize(max_capacity) << " is too big";
75 *error_msg = oss.str();
76 return nullptr;
77 }
78
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080079 std::string error_str;
80 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010081 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000082 "data-code-cache", nullptr, max_capacity, kProtAll, false, false, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010083 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080084 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000085 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080086 *error_msg = oss.str();
87 return nullptr;
88 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010089
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000090 // Align both capacities to page size, as that's the unit mspaces use.
91 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
92 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
93
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +000094 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010095 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000096 size_t data_size = max_capacity / 2;
97 size_t code_size = max_capacity - data_size;
98 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010099 uint8_t* divider = data_map->Begin() + data_size;
100
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000101 MemMap* code_map =
102 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100103 if (code_map == nullptr) {
104 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000105 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100106 *error_msg = oss.str();
107 return nullptr;
108 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100109 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000110 data_size = initial_capacity / 2;
111 code_size = initial_capacity - data_size;
112 DCHECK_EQ(code_size + data_size, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000113 return new JitCodeCache(
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000114 code_map, data_map, code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800115}
116
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000117JitCodeCache::JitCodeCache(MemMap* code_map,
118 MemMap* data_map,
119 size_t initial_code_capacity,
120 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000121 size_t max_capacity,
122 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100123 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100124 lock_cond_("Jit code cache variable", lock_),
125 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100126 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000127 data_map_(data_map),
128 max_capacity_(max_capacity),
129 current_capacity_(initial_code_capacity + initial_data_capacity),
130 code_end_(initial_code_capacity),
131 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000132 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000133 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000134 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000135 used_memory_for_data_(0),
136 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000137 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000138 number_of_osr_compilations_(0),
139 number_of_deoptimizations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000140 number_of_collections_(0),
141 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
142 histogram_code_memory_use_("Memory used for compiled code", 16),
143 histogram_profiling_info_memory_use_("Memory used for profiling info", 16) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100144
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000145 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000146 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
147 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100148
149 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
150 PLOG(FATAL) << "create_mspace_with_base failed";
151 }
152
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000153 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100154
155 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
156 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100157
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000158 VLOG(jit) << "Created jit code cache: initial data size="
159 << PrettySize(initial_data_capacity)
160 << ", initial code size="
161 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800162}
163
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100164bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100165 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800166}
167
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000168bool JitCodeCache::ContainsMethod(ArtMethod* method) {
169 MutexLock mu(Thread::Current(), lock_);
170 for (auto& it : method_code_map_) {
171 if (it.second == method) {
172 return true;
173 }
174 }
175 return false;
176}
177
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800178class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100179 public:
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800180 explicit ScopedCodeCacheWrite(MemMap* code_map)
181 : ScopedTrace("ScopedCodeCacheWrite"),
182 code_map_(code_map) {
183 ScopedTrace trace("mprotect all");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100184 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800185 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100186 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800187 ScopedTrace trace("mprotect code");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100188 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
189 }
190 private:
191 MemMap* const code_map_;
192
193 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
194};
195
196uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100197 ArtMethod* method,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100198 const uint8_t* vmap_table,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100199 size_t frame_size_in_bytes,
200 size_t core_spill_mask,
201 size_t fp_spill_mask,
202 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000203 size_t code_size,
204 bool osr) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100205 uint8_t* result = CommitCodeInternal(self,
206 method,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100207 vmap_table,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100208 frame_size_in_bytes,
209 core_spill_mask,
210 fp_spill_mask,
211 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000212 code_size,
213 osr);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100214 if (result == nullptr) {
215 // Retry.
216 GarbageCollectCache(self);
217 result = CommitCodeInternal(self,
218 method,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100219 vmap_table,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100220 frame_size_in_bytes,
221 core_spill_mask,
222 fp_spill_mask,
223 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000224 code_size,
225 osr);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100226 }
227 return result;
228}
229
230bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
231 bool in_collection = false;
232 while (collection_in_progress_) {
233 in_collection = true;
234 lock_cond_.Wait(self);
235 }
236 return in_collection;
237}
238
239static uintptr_t FromCodeToAllocation(const void* code) {
240 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
241 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
242}
243
244void JitCodeCache::FreeCode(const void* code_ptr, ArtMethod* method ATTRIBUTE_UNUSED) {
245 uintptr_t allocation = FromCodeToAllocation(code_ptr);
246 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000247 // Notify native debugger that we are about to remove the code.
248 // It does nothing if we are not using native debugger.
249 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000250
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100251 // Use the offset directly to prevent sanity check that the method is
252 // compiled with optimizing.
253 // TODO(ngeoffray): Clean up.
254 if (method_header->vmap_table_offset_ != 0) {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000255 const uint8_t* data = method_header->code_ - method_header->vmap_table_offset_;
256 FreeData(const_cast<uint8_t*>(data));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100257 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000258 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100259}
260
261void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800262 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100263 MutexLock mu(self, lock_);
264 // We do not check if a code cache GC is in progress, as this method comes
265 // with the classlinker_classes_lock_ held, and suspending ourselves could
266 // lead to a deadlock.
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000267 {
268 ScopedCodeCacheWrite scc(code_map_.get());
269 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
270 if (alloc.ContainsUnsafe(it->second)) {
271 FreeCode(it->first, it->second);
272 it = method_code_map_.erase(it);
273 } else {
274 ++it;
275 }
276 }
277 }
Nicolas Geoffraya9b91312016-02-17 09:49:19 +0000278 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
279 if (alloc.ContainsUnsafe(it->first)) {
280 // Note that the code has already been removed in the loop above.
281 it = osr_code_map_.erase(it);
282 } else {
283 ++it;
284 }
285 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000286 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
287 ProfilingInfo* info = *it;
288 if (alloc.ContainsUnsafe(info->GetMethod())) {
289 info->GetMethod()->SetProfilingInfo(nullptr);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000290 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000291 it = profiling_infos_.erase(it);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100292 } else {
293 ++it;
294 }
295 }
296}
297
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000298void JitCodeCache::ClearGcRootsInInlineCaches(Thread* self) {
299 MutexLock mu(self, lock_);
300 for (ProfilingInfo* info : profiling_infos_) {
301 if (!info->IsInUseByCompiler()) {
302 info->ClearGcRootsInInlineCaches();
303 }
304 }
305}
306
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100307uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
308 ArtMethod* method,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100309 const uint8_t* vmap_table,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100310 size_t frame_size_in_bytes,
311 size_t core_spill_mask,
312 size_t fp_spill_mask,
313 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000314 size_t code_size,
315 bool osr) {
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100316 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
317 // Ensure the header ends up at expected instruction alignment.
318 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
319 size_t total_size = header_size + code_size;
320
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100321 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100322 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000323 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100324 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000325 ScopedThreadSuspension sts(self, kSuspended);
326 MutexLock mu(self, lock_);
327 WaitForPotentialCollectionToComplete(self);
328 {
329 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000330 memory = AllocateCode(total_size);
331 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000332 return nullptr;
333 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000334 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000335
336 std::copy(code, code + code_size, code_ptr);
337 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
338 new (method_header) OatQuickMethodHeader(
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000339 (vmap_table == nullptr) ? 0 : code_ptr - vmap_table,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000340 frame_size_in_bytes,
341 core_spill_mask,
342 fp_spill_mask,
343 code_size);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100344 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100345
Roland Levillain32430262016-02-01 15:23:20 +0000346 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
347 reinterpret_cast<char*>(code_ptr + code_size));
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000348 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100349 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000350 // We need to update the entry point in the runnable state for the instrumentation.
351 {
352 MutexLock mu(self, lock_);
353 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000354 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000355 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000356 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray6300fd72016-03-18 09:40:17 +0000357 } else if (!Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
358 // TODO(ngeoffray): Clean up instrumentation and code cache interactions.
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000359 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
360 method, method_header->GetEntryPoint());
361 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000362 if (collection_in_progress_) {
363 // We need to update the live bitmap if there is a GC to ensure it sees this new
364 // code.
365 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
366 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000367 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000368 VLOG(jit)
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000369 << "JIT added (osr = " << std::boolalpha << osr << std::noboolalpha << ") "
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000370 << PrettyMethod(method) << "@" << method
371 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
372 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
373 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
374 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000375 histogram_code_memory_use_.AddValue(code_size);
376 if (code_size > kCodeSizeLogThreshold) {
377 LOG(INFO) << "JIT allocated "
378 << PrettySize(code_size)
379 << " for compiled code of "
380 << PrettyMethod(method);
381 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000382 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100383
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100384 return reinterpret_cast<uint8_t*>(method_header);
385}
386
387size_t JitCodeCache::CodeCacheSize() {
388 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000389 return CodeCacheSizeLocked();
390}
391
392size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000393 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100394}
395
396size_t JitCodeCache::DataCacheSize() {
397 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000398 return DataCacheSizeLocked();
399}
400
401size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000402 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800403}
404
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000405void JitCodeCache::ClearData(Thread* self, void* data) {
406 MutexLock mu(self, lock_);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000407 FreeData(reinterpret_cast<uint8_t*>(data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000408}
409
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000410uint8_t* JitCodeCache::ReserveData(Thread* self, size_t size, ArtMethod* method) {
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100411 size = RoundUp(size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100412 uint8_t* result = nullptr;
413
414 {
415 ScopedThreadSuspension sts(self, kSuspended);
416 MutexLock mu(self, lock_);
417 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000418 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100419 }
420
421 if (result == nullptr) {
422 // Retry.
423 GarbageCollectCache(self);
424 ScopedThreadSuspension sts(self, kSuspended);
425 MutexLock mu(self, lock_);
426 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000427 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100428 }
429
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000430 MutexLock mu(self, lock_);
431 histogram_stack_map_memory_use_.AddValue(size);
432 if (size > kStackMapSizeLogThreshold) {
433 LOG(INFO) << "JIT allocated "
434 << PrettySize(size)
435 << " for stack maps of "
436 << PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800437 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100438 return result;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800439}
440
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100441class MarkCodeVisitor FINAL : public StackVisitor {
442 public:
443 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
444 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
445 code_cache_(code_cache_in),
446 bitmap_(code_cache_->GetLiveBitmap()) {}
447
448 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
449 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
450 if (method_header == nullptr) {
451 return true;
452 }
453 const void* code = method_header->GetCode();
454 if (code_cache_->ContainsPc(code)) {
455 // Use the atomic set version, as multiple threads are executing this code.
456 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
457 }
458 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800459 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100460
461 private:
462 JitCodeCache* const code_cache_;
463 CodeCacheBitmap* const bitmap_;
464};
465
466class MarkCodeClosure FINAL : public Closure {
467 public:
468 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
469 : code_cache_(code_cache), barrier_(barrier) {}
470
471 void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800472 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100473 DCHECK(thread == Thread::Current() || thread->IsSuspended());
474 MarkCodeVisitor visitor(thread, code_cache_);
475 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000476 if (kIsDebugBuild) {
477 // The stack walking code queries the side instrumentation stack if it
478 // sees an instrumentation exit pc, so the JIT code of methods in that stack
479 // must have been seen. We sanity check this below.
480 for (const instrumentation::InstrumentationStackFrame& frame
481 : *thread->GetInstrumentationStack()) {
482 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
483 // its stack frame, it is not the method owning return_pc_. We just pass null to
484 // LookupMethodHeader: the method is only checked against in debug builds.
485 OatQuickMethodHeader* method_header =
486 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
487 if (method_header != nullptr) {
488 const void* code = method_header->GetCode();
489 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
490 }
491 }
492 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700493 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800494 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100495
496 private:
497 JitCodeCache* const code_cache_;
498 Barrier* const barrier_;
499};
500
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000501void JitCodeCache::NotifyCollectionDone(Thread* self) {
502 collection_in_progress_ = false;
503 lock_cond_.Broadcast(self);
504}
505
506void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
507 size_t per_space_footprint = new_footprint / 2;
508 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
509 DCHECK_EQ(per_space_footprint * 2, new_footprint);
510 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
511 {
512 ScopedCodeCacheWrite scc(code_map_.get());
513 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
514 }
515}
516
517bool JitCodeCache::IncreaseCodeCacheCapacity() {
518 if (current_capacity_ == max_capacity_) {
519 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100520 }
521
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000522 // Double the capacity if we're below 1MB, or increase it by 1MB if
523 // we're above.
524 if (current_capacity_ < 1 * MB) {
525 current_capacity_ *= 2;
526 } else {
527 current_capacity_ += 1 * MB;
528 }
529 if (current_capacity_ > max_capacity_) {
530 current_capacity_ = max_capacity_;
531 }
532
533 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
534 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
535 }
536
537 SetFootprintLimit(current_capacity_);
538
539 return true;
540}
541
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000542void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
543 Barrier barrier(0);
544 size_t threads_running_checkpoint = 0;
545 MarkCodeClosure closure(this, &barrier);
546 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
547 // Now that we have run our checkpoint, move to a suspended state and wait
548 // for other threads to run the checkpoint.
549 ScopedThreadSuspension sts(self, kSuspended);
550 if (threads_running_checkpoint != 0) {
551 barrier.Increment(self, threads_running_checkpoint);
552 }
553}
554
Nicolas Geoffray35122442016-03-02 12:05:30 +0000555bool JitCodeCache::ShouldDoFullCollection() {
556 if (current_capacity_ == max_capacity_) {
557 // Always do a full collection when the code cache is full.
558 return true;
559 } else if (current_capacity_ < kReservedCapacity) {
560 // Always do partial collection when the code cache size is below the reserved
561 // capacity.
562 return false;
563 } else if (last_collection_increased_code_cache_) {
564 // This time do a full collection.
565 return true;
566 } else {
567 // This time do a partial collection.
568 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000569 }
570}
571
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000572void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800573 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000574 if (!garbage_collect_code_) {
575 MutexLock mu(self, lock_);
576 IncreaseCodeCacheCapacity();
577 return;
578 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100579
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000580 // Wait for an existing collection, or let everyone know we are starting one.
581 {
582 ScopedThreadSuspension sts(self, kSuspended);
583 MutexLock mu(self, lock_);
584 if (WaitForPotentialCollectionToComplete(self)) {
585 return;
586 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000587 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000588 live_bitmap_.reset(CodeCacheBitmap::Create(
589 "code-cache-bitmap",
590 reinterpret_cast<uintptr_t>(code_map_->Begin()),
591 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000592 collection_in_progress_ = true;
593 }
594 }
595
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000596 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000597 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000598 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000599
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000600 bool do_full_collection = false;
601 {
602 MutexLock mu(self, lock_);
603 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000604 }
605
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000606 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
607 LOG(INFO) << "Do "
608 << (do_full_collection ? "full" : "partial")
609 << " code cache collection, code="
610 << PrettySize(CodeCacheSize())
611 << ", data=" << PrettySize(DataCacheSize());
612 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000613
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000614 DoCollection(self, /* collect_profiling_info */ do_full_collection);
615
616 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
617 LOG(INFO) << "After code cache collection, code="
618 << PrettySize(CodeCacheSize())
619 << ", data=" << PrettySize(DataCacheSize());
620 }
621
622 {
623 MutexLock mu(self, lock_);
624
625 // Increase the code cache only when we do partial collections.
626 // TODO: base this strategy on how full the code cache is?
627 if (do_full_collection) {
628 last_collection_increased_code_cache_ = false;
629 } else {
630 last_collection_increased_code_cache_ = true;
631 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000632 }
633
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000634 bool next_collection_will_be_full = ShouldDoFullCollection();
635
636 // Start polling the liveness of compiled code to prepare for the next full collection.
637 // We avoid doing this if exit stubs are installed to not mess with the instrumentation.
638 // TODO(ngeoffray): Clean up instrumentation and code cache interactions.
639 if (!Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled() &&
640 next_collection_will_be_full) {
641 // Save the entry point of methods we have compiled, and update the entry
642 // point of those methods to the interpreter. If the method is invoked, the
643 // interpreter will update its entry point to the compiled code and call it.
644 for (ProfilingInfo* info : profiling_infos_) {
645 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
646 if (ContainsPc(entry_point)) {
647 info->SetSavedEntryPoint(entry_point);
648 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
649 }
650 }
651
652 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
653 }
654 live_bitmap_.reset(nullptr);
655 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000656 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000657 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000658 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000659}
660
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000661void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800662 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000663 MutexLock mu(self, lock_);
664 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000665 // Iterate over all compiled code and remove entries that are not marked.
Nicolas Geoffray35122442016-03-02 12:05:30 +0000666 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
667 const void* code_ptr = it->first;
668 ArtMethod* method = it->second;
669 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000670 if (GetLiveBitmap()->Test(allocation)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000671 ++it;
672 } else {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000673 FreeCode(code_ptr, method);
674 it = method_code_map_.erase(it);
675 }
676 }
677}
678
679void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800680 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000681 {
682 MutexLock mu(self, lock_);
683 if (collect_profiling_info) {
684 // Clear the profiling info of methods that do not have compiled code as entrypoint.
685 // Also remove the saved entry point from the ProfilingInfo objects.
686 for (ProfilingInfo* info : profiling_infos_) {
687 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000688 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000689 info->GetMethod()->SetProfilingInfo(nullptr);
690 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +0000691
692 if (info->GetSavedEntryPoint() != nullptr) {
693 info->SetSavedEntryPoint(nullptr);
694 // We are going to move this method back to interpreter. Clear the counter now to
695 // give it a chance to be hot again.
696 info->GetMethod()->ClearCounter();
697 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000698 }
699 } else if (kIsDebugBuild) {
700 // Sanity check that the profiling infos do not have a dangling entry point.
701 for (ProfilingInfo* info : profiling_infos_) {
702 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100703 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000704 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000705
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000706 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
707 // an entry point is either:
708 // - an osr compiled code, that will be removed if not in a thread call stack.
709 // - discarded compiled code, that will be removed if not in a thread call stack.
710 for (const auto& it : method_code_map_) {
711 ArtMethod* method = it.second;
712 const void* code_ptr = it.first;
713 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
714 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
715 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
716 }
717 }
718
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000719 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000720 // on thread stacks).
721 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100722 }
723
724 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000725 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100726
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000727 // At this point, mutator threads are still running, and entrypoints of methods can
728 // change. We do know they cannot change to a code cache entry that is not marked,
729 // therefore we can safely remove those entries.
730 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000731
Nicolas Geoffray35122442016-03-02 12:05:30 +0000732 if (collect_profiling_info) {
733 MutexLock mu(self, lock_);
734 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100735 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000736 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000737 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000738 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
739 // that the compiled code would not get revived. As mutator threads run concurrently,
740 // they may have revived the compiled code, and now we are in the situation where
741 // a method has compiled code but no ProfilingInfo.
742 // We make sure compiled methods have a ProfilingInfo object. It is needed for
743 // code cache collection.
Nicolas Geoffray35122442016-03-02 12:05:30 +0000744 if (ContainsPc(ptr) && info->GetMethod()->GetProfilingInfo(sizeof(void*)) == nullptr) {
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000745 // We clear the inline caches as classes in it might be stalled.
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000746 info->ClearGcRootsInInlineCaches();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000747 // Do a fence to make sure the clearing is seen before attaching to the method.
748 QuasiAtomic::ThreadFenceRelease();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000749 info->GetMethod()->SetProfilingInfo(info);
750 } else if (info->GetMethod()->GetProfilingInfo(sizeof(void*)) != info) {
751 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000752 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100753 return true;
754 }
755 return false;
756 });
757 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +0000758 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100759 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800760}
761
Nicolas Geoffray35122442016-03-02 12:05:30 +0000762bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800763 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000764 // Check that methods we have compiled do have a ProfilingInfo object. We would
765 // have memory leaks of compiled code otherwise.
766 for (const auto& it : method_code_map_) {
767 ArtMethod* method = it.second;
768 if (method->GetProfilingInfo(sizeof(void*)) == nullptr) {
769 const void* code_ptr = it.first;
770 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
771 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
772 // If the code is not dead, then we have a problem. Note that this can even
773 // happen just after a collection, as mutator threads are running in parallel
774 // and could deoptimize an existing compiled code.
775 return false;
776 }
777 }
778 }
779 return true;
780}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100781
782OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
783 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
784 if (kRuntimeISA == kArm) {
785 // On Thumb-2, the pc is offset by one.
786 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800787 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100788 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
789 return nullptr;
790 }
791
792 MutexLock mu(Thread::Current(), lock_);
793 if (method_code_map_.empty()) {
794 return nullptr;
795 }
796 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
797 --it;
798
799 const void* code_ptr = it->first;
800 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
801 if (!method_header->Contains(pc)) {
802 return nullptr;
803 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000804 if (kIsDebugBuild && method != nullptr) {
805 DCHECK_EQ(it->second, method)
806 << PrettyMethod(method) << " " << PrettyMethod(it->second) << " " << std::hex << pc;
807 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100808 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800809}
810
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000811OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
812 MutexLock mu(Thread::Current(), lock_);
813 auto it = osr_code_map_.find(method);
814 if (it == osr_code_map_.end()) {
815 return nullptr;
816 }
817 return OatQuickMethodHeader::FromCodePointer(it->second);
818}
819
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000820ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
821 ArtMethod* method,
822 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000823 bool retry_allocation)
824 // No thread safety analysis as we are using TryLock/Unlock explicitly.
825 NO_THREAD_SAFETY_ANALYSIS {
826 ProfilingInfo* info = nullptr;
827 if (!retry_allocation) {
828 // If we are allocating for the interpreter, just try to lock, to avoid
829 // lock contention with the JIT.
830 if (lock_.ExclusiveTryLock(self)) {
831 info = AddProfilingInfoInternal(self, method, entries);
832 lock_.ExclusiveUnlock(self);
833 }
834 } else {
835 {
836 MutexLock mu(self, lock_);
837 info = AddProfilingInfoInternal(self, method, entries);
838 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000839
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000840 if (info == nullptr) {
841 GarbageCollectCache(self);
842 MutexLock mu(self, lock_);
843 info = AddProfilingInfoInternal(self, method, entries);
844 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000845 }
846 return info;
847}
848
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000849ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000850 ArtMethod* method,
851 const std::vector<uint32_t>& entries) {
852 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100853 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000854 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000855
856 // Check whether some other thread has concurrently created it.
857 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
858 if (info != nullptr) {
859 return info;
860 }
861
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000862 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000863 if (data == nullptr) {
864 return nullptr;
865 }
866 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +0000867
868 // Make sure other threads see the data in the profiling info object before the
869 // store in the ArtMethod's ProfilingInfo pointer.
870 QuasiAtomic::ThreadFenceRelease();
871
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000872 method->SetProfilingInfo(info);
873 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000874 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000875 return info;
876}
877
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000878// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
879// is already held.
880void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
881 if (code_mspace_ == mspace) {
882 size_t result = code_end_;
883 code_end_ += increment;
884 return reinterpret_cast<void*>(result + code_map_->Begin());
885 } else {
886 DCHECK_EQ(data_mspace_, mspace);
887 size_t result = data_end_;
888 data_end_ += increment;
889 return reinterpret_cast<void*>(result + data_map_->Begin());
890 }
891}
892
Calin Juravleb4eddd22016-01-13 15:52:33 -0800893void JitCodeCache::GetCompiledArtMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000894 std::vector<ArtMethod*>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800895 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +0100896 MutexLock mu(Thread::Current(), lock_);
897 for (auto it : method_code_map_) {
Calin Juravle66f55232015-12-08 15:09:10 +0000898 if (ContainsElement(dex_base_locations, it.second->GetDexFile()->GetBaseLocation())) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000899 methods.push_back(it.second);
Calin Juravle31f2c152015-10-23 17:56:15 +0100900 }
901 }
902}
903
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000904uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
905 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +0100906}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100907
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000908bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
909 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000910 VLOG(jit) << PrettyMethod(method) << " is already compiled";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100911 return false;
912 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000913
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000914 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000915 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000916 VLOG(jit) << PrettyMethod(method) << " is already osr compiled";
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000917 return false;
918 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000919
Nicolas Geoffrayc26f1282016-01-29 11:41:25 +0000920 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000921 if (info == nullptr) {
922 VLOG(jit) << PrettyMethod(method) << " needs a ProfilingInfo to be compiled";
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +0000923 // Because the counter is not atomic, there are some rare cases where we may not
924 // hit the threshold for creating the ProfilingInfo. Reset the counter now to
925 // "correct" this.
926 method->ClearCounter();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100927 return false;
928 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000929
buzbee454b3b62016-04-07 14:42:47 -0700930 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000931 VLOG(jit) << PrettyMethod(method) << " is already being compiled";
932 return false;
933 }
934
buzbee454b3b62016-04-07 14:42:47 -0700935 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100936 return true;
937}
938
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000939ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000940 MutexLock mu(self, lock_);
941 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
942 if (info != nullptr) {
943 info->IncrementInlineUse();
944 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000945 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000946}
947
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000948void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000949 MutexLock mu(self, lock_);
950 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000951 DCHECK(info != nullptr);
952 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000953}
954
buzbee454b3b62016-04-07 14:42:47 -0700955void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100956 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
buzbee454b3b62016-04-07 14:42:47 -0700957 DCHECK(info->IsMethodBeingCompiled(osr));
958 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100959}
960
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000961size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
962 MutexLock mu(Thread::Current(), lock_);
963 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
964}
965
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000966void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
967 const OatQuickMethodHeader* header) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000968 ProfilingInfo* profiling_info = method->GetProfilingInfo(sizeof(void*));
969 if ((profiling_info != nullptr) &&
970 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
971 // Prevent future uses of the compiled code.
972 profiling_info->SetSavedEntryPoint(nullptr);
973 }
974
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000975 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
976 // The entrypoint is the one to invalidate, so we just update
977 // it to the interpreter entry point and clear the counter to get the method
978 // Jitted again.
979 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
980 method, GetQuickToInterpreterBridge());
981 method->ClearCounter();
982 } else {
983 MutexLock mu(Thread::Current(), lock_);
984 auto it = osr_code_map_.find(method);
985 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
986 // Remove the OSR method, to avoid using it again.
987 osr_code_map_.erase(it);
988 }
989 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000990 MutexLock mu(Thread::Current(), lock_);
991 number_of_deoptimizations_++;
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000992}
993
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000994uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
995 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
996 uint8_t* result = reinterpret_cast<uint8_t*>(
997 mspace_memalign(code_mspace_, alignment, code_size));
998 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
999 // Ensure the header ends up at expected instruction alignment.
1000 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1001 used_memory_for_code_ += mspace_usable_size(result);
1002 return result;
1003}
1004
1005void JitCodeCache::FreeCode(uint8_t* code) {
1006 used_memory_for_code_ -= mspace_usable_size(code);
1007 mspace_free(code_mspace_, code);
1008}
1009
1010uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1011 void* result = mspace_malloc(data_mspace_, data_size);
1012 used_memory_for_data_ += mspace_usable_size(result);
1013 return reinterpret_cast<uint8_t*>(result);
1014}
1015
1016void JitCodeCache::FreeData(uint8_t* data) {
1017 used_memory_for_data_ -= mspace_usable_size(data);
1018 mspace_free(data_mspace_, data);
1019}
1020
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001021void JitCodeCache::Dump(std::ostream& os) {
1022 MutexLock mu(Thread::Current(), lock_);
1023 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1024 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1025 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1026 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1027 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1028 << "Total number of JIT compilations for on stack replacement: "
1029 << number_of_osr_compilations_ << "\n"
1030 << "Total number of deoptimizations: " << number_of_deoptimizations_ << "\n"
1031 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001032 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1033 histogram_code_memory_use_.PrintMemoryUse(os);
1034 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001035}
1036
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001037} // namespace jit
1038} // namespace art