blob: 6b6f5a5c15e09d0e6521142d9db30d5e165eec2d [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 Geoffray480d5102016-04-18 12:09:30 +0100357 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000358 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
359 method, method_header->GetEntryPoint());
360 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000361 if (collection_in_progress_) {
362 // We need to update the live bitmap if there is a GC to ensure it sees this new
363 // code.
364 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
365 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000366 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000367 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100368 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000369 << PrettyMethod(method) << "@" << method
370 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
371 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
372 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
373 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000374 histogram_code_memory_use_.AddValue(code_size);
375 if (code_size > kCodeSizeLogThreshold) {
376 LOG(INFO) << "JIT allocated "
377 << PrettySize(code_size)
378 << " for compiled code of "
379 << PrettyMethod(method);
380 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000381 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100382
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100383 return reinterpret_cast<uint8_t*>(method_header);
384}
385
386size_t JitCodeCache::CodeCacheSize() {
387 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000388 return CodeCacheSizeLocked();
389}
390
391size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000392 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100393}
394
395size_t JitCodeCache::DataCacheSize() {
396 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000397 return DataCacheSizeLocked();
398}
399
400size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000401 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800402}
403
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000404void JitCodeCache::ClearData(Thread* self, void* data) {
405 MutexLock mu(self, lock_);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000406 FreeData(reinterpret_cast<uint8_t*>(data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000407}
408
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000409uint8_t* JitCodeCache::ReserveData(Thread* self, size_t size, ArtMethod* method) {
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100410 size = RoundUp(size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100411 uint8_t* result = nullptr;
412
413 {
414 ScopedThreadSuspension sts(self, kSuspended);
415 MutexLock mu(self, lock_);
416 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000417 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100418 }
419
420 if (result == nullptr) {
421 // Retry.
422 GarbageCollectCache(self);
423 ScopedThreadSuspension sts(self, kSuspended);
424 MutexLock mu(self, lock_);
425 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000426 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100427 }
428
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000429 MutexLock mu(self, lock_);
430 histogram_stack_map_memory_use_.AddValue(size);
431 if (size > kStackMapSizeLogThreshold) {
432 LOG(INFO) << "JIT allocated "
433 << PrettySize(size)
434 << " for stack maps of "
435 << PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800436 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100437 return result;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800438}
439
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100440class MarkCodeVisitor FINAL : public StackVisitor {
441 public:
442 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
443 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
444 code_cache_(code_cache_in),
445 bitmap_(code_cache_->GetLiveBitmap()) {}
446
447 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
448 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
449 if (method_header == nullptr) {
450 return true;
451 }
452 const void* code = method_header->GetCode();
453 if (code_cache_->ContainsPc(code)) {
454 // Use the atomic set version, as multiple threads are executing this code.
455 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
456 }
457 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800458 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100459
460 private:
461 JitCodeCache* const code_cache_;
462 CodeCacheBitmap* const bitmap_;
463};
464
465class MarkCodeClosure FINAL : public Closure {
466 public:
467 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
468 : code_cache_(code_cache), barrier_(barrier) {}
469
470 void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800471 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100472 DCHECK(thread == Thread::Current() || thread->IsSuspended());
473 MarkCodeVisitor visitor(thread, code_cache_);
474 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000475 if (kIsDebugBuild) {
476 // The stack walking code queries the side instrumentation stack if it
477 // sees an instrumentation exit pc, so the JIT code of methods in that stack
478 // must have been seen. We sanity check this below.
479 for (const instrumentation::InstrumentationStackFrame& frame
480 : *thread->GetInstrumentationStack()) {
481 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
482 // its stack frame, it is not the method owning return_pc_. We just pass null to
483 // LookupMethodHeader: the method is only checked against in debug builds.
484 OatQuickMethodHeader* method_header =
485 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
486 if (method_header != nullptr) {
487 const void* code = method_header->GetCode();
488 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
489 }
490 }
491 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700492 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800493 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100494
495 private:
496 JitCodeCache* const code_cache_;
497 Barrier* const barrier_;
498};
499
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000500void JitCodeCache::NotifyCollectionDone(Thread* self) {
501 collection_in_progress_ = false;
502 lock_cond_.Broadcast(self);
503}
504
505void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
506 size_t per_space_footprint = new_footprint / 2;
507 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
508 DCHECK_EQ(per_space_footprint * 2, new_footprint);
509 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
510 {
511 ScopedCodeCacheWrite scc(code_map_.get());
512 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
513 }
514}
515
516bool JitCodeCache::IncreaseCodeCacheCapacity() {
517 if (current_capacity_ == max_capacity_) {
518 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100519 }
520
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000521 // Double the capacity if we're below 1MB, or increase it by 1MB if
522 // we're above.
523 if (current_capacity_ < 1 * MB) {
524 current_capacity_ *= 2;
525 } else {
526 current_capacity_ += 1 * MB;
527 }
528 if (current_capacity_ > max_capacity_) {
529 current_capacity_ = max_capacity_;
530 }
531
532 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
533 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
534 }
535
536 SetFootprintLimit(current_capacity_);
537
538 return true;
539}
540
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000541void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
542 Barrier barrier(0);
543 size_t threads_running_checkpoint = 0;
544 MarkCodeClosure closure(this, &barrier);
545 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
546 // Now that we have run our checkpoint, move to a suspended state and wait
547 // for other threads to run the checkpoint.
548 ScopedThreadSuspension sts(self, kSuspended);
549 if (threads_running_checkpoint != 0) {
550 barrier.Increment(self, threads_running_checkpoint);
551 }
552}
553
Nicolas Geoffray35122442016-03-02 12:05:30 +0000554bool JitCodeCache::ShouldDoFullCollection() {
555 if (current_capacity_ == max_capacity_) {
556 // Always do a full collection when the code cache is full.
557 return true;
558 } else if (current_capacity_ < kReservedCapacity) {
559 // Always do partial collection when the code cache size is below the reserved
560 // capacity.
561 return false;
562 } else if (last_collection_increased_code_cache_) {
563 // This time do a full collection.
564 return true;
565 } else {
566 // This time do a partial collection.
567 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000568 }
569}
570
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000571void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800572 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000573 if (!garbage_collect_code_) {
574 MutexLock mu(self, lock_);
575 IncreaseCodeCacheCapacity();
576 return;
577 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100578
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000579 // Wait for an existing collection, or let everyone know we are starting one.
580 {
581 ScopedThreadSuspension sts(self, kSuspended);
582 MutexLock mu(self, lock_);
583 if (WaitForPotentialCollectionToComplete(self)) {
584 return;
585 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000586 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000587 live_bitmap_.reset(CodeCacheBitmap::Create(
588 "code-cache-bitmap",
589 reinterpret_cast<uintptr_t>(code_map_->Begin()),
590 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000591 collection_in_progress_ = true;
592 }
593 }
594
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000595 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000596 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000597 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000598
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000599 bool do_full_collection = false;
600 {
601 MutexLock mu(self, lock_);
602 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000603 }
604
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000605 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
606 LOG(INFO) << "Do "
607 << (do_full_collection ? "full" : "partial")
608 << " code cache collection, code="
609 << PrettySize(CodeCacheSize())
610 << ", data=" << PrettySize(DataCacheSize());
611 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000612
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000613 DoCollection(self, /* collect_profiling_info */ do_full_collection);
614
615 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
616 LOG(INFO) << "After code cache collection, code="
617 << PrettySize(CodeCacheSize())
618 << ", data=" << PrettySize(DataCacheSize());
619 }
620
621 {
622 MutexLock mu(self, lock_);
623
624 // Increase the code cache only when we do partial collections.
625 // TODO: base this strategy on how full the code cache is?
626 if (do_full_collection) {
627 last_collection_increased_code_cache_ = false;
628 } else {
629 last_collection_increased_code_cache_ = true;
630 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000631 }
632
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000633 bool next_collection_will_be_full = ShouldDoFullCollection();
634
635 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100636 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000637 // Save the entry point of methods we have compiled, and update the entry
638 // point of those methods to the interpreter. If the method is invoked, the
639 // interpreter will update its entry point to the compiled code and call it.
640 for (ProfilingInfo* info : profiling_infos_) {
641 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
642 if (ContainsPc(entry_point)) {
643 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100644 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
645 info->GetMethod(), GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000646 }
647 }
648
649 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
650 }
651 live_bitmap_.reset(nullptr);
652 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000653 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000654 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000655 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000656}
657
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000658void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800659 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000660 MutexLock mu(self, lock_);
661 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000662 // Iterate over all compiled code and remove entries that are not marked.
Nicolas Geoffray35122442016-03-02 12:05:30 +0000663 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
664 const void* code_ptr = it->first;
665 ArtMethod* method = it->second;
666 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000667 if (GetLiveBitmap()->Test(allocation)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000668 ++it;
669 } else {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000670 FreeCode(code_ptr, method);
671 it = method_code_map_.erase(it);
672 }
673 }
674}
675
676void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800677 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000678 {
679 MutexLock mu(self, lock_);
680 if (collect_profiling_info) {
681 // Clear the profiling info of methods that do not have compiled code as entrypoint.
682 // Also remove the saved entry point from the ProfilingInfo objects.
683 for (ProfilingInfo* info : profiling_infos_) {
684 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000685 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000686 info->GetMethod()->SetProfilingInfo(nullptr);
687 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +0000688
689 if (info->GetSavedEntryPoint() != nullptr) {
690 info->SetSavedEntryPoint(nullptr);
691 // We are going to move this method back to interpreter. Clear the counter now to
692 // give it a chance to be hot again.
693 info->GetMethod()->ClearCounter();
694 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000695 }
696 } else if (kIsDebugBuild) {
697 // Sanity check that the profiling infos do not have a dangling entry point.
698 for (ProfilingInfo* info : profiling_infos_) {
699 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100700 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000701 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000702
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000703 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
704 // an entry point is either:
705 // - an osr compiled code, that will be removed if not in a thread call stack.
706 // - discarded compiled code, that will be removed if not in a thread call stack.
707 for (const auto& it : method_code_map_) {
708 ArtMethod* method = it.second;
709 const void* code_ptr = it.first;
710 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
711 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
712 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
713 }
714 }
715
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000716 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000717 // on thread stacks).
718 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100719 }
720
721 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000722 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100723
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000724 // At this point, mutator threads are still running, and entrypoints of methods can
725 // change. We do know they cannot change to a code cache entry that is not marked,
726 // therefore we can safely remove those entries.
727 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000728
Nicolas Geoffray35122442016-03-02 12:05:30 +0000729 if (collect_profiling_info) {
730 MutexLock mu(self, lock_);
731 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100732 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000733 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000734 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000735 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
736 // that the compiled code would not get revived. As mutator threads run concurrently,
737 // they may have revived the compiled code, and now we are in the situation where
738 // a method has compiled code but no ProfilingInfo.
739 // We make sure compiled methods have a ProfilingInfo object. It is needed for
740 // code cache collection.
Nicolas Geoffray35122442016-03-02 12:05:30 +0000741 if (ContainsPc(ptr) && info->GetMethod()->GetProfilingInfo(sizeof(void*)) == nullptr) {
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000742 // We clear the inline caches as classes in it might be stalled.
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000743 info->ClearGcRootsInInlineCaches();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000744 // Do a fence to make sure the clearing is seen before attaching to the method.
745 QuasiAtomic::ThreadFenceRelease();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000746 info->GetMethod()->SetProfilingInfo(info);
747 } else if (info->GetMethod()->GetProfilingInfo(sizeof(void*)) != info) {
748 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000749 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100750 return true;
751 }
752 return false;
753 });
754 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +0000755 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100756 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800757}
758
Nicolas Geoffray35122442016-03-02 12:05:30 +0000759bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800760 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000761 // Check that methods we have compiled do have a ProfilingInfo object. We would
762 // have memory leaks of compiled code otherwise.
763 for (const auto& it : method_code_map_) {
764 ArtMethod* method = it.second;
765 if (method->GetProfilingInfo(sizeof(void*)) == nullptr) {
766 const void* code_ptr = it.first;
767 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
768 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
769 // If the code is not dead, then we have a problem. Note that this can even
770 // happen just after a collection, as mutator threads are running in parallel
771 // and could deoptimize an existing compiled code.
772 return false;
773 }
774 }
775 }
776 return true;
777}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100778
779OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
780 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
781 if (kRuntimeISA == kArm) {
782 // On Thumb-2, the pc is offset by one.
783 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800784 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100785 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
786 return nullptr;
787 }
788
789 MutexLock mu(Thread::Current(), lock_);
790 if (method_code_map_.empty()) {
791 return nullptr;
792 }
793 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
794 --it;
795
796 const void* code_ptr = it->first;
797 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
798 if (!method_header->Contains(pc)) {
799 return nullptr;
800 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000801 if (kIsDebugBuild && method != nullptr) {
802 DCHECK_EQ(it->second, method)
803 << PrettyMethod(method) << " " << PrettyMethod(it->second) << " " << std::hex << pc;
804 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100805 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800806}
807
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000808OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
809 MutexLock mu(Thread::Current(), lock_);
810 auto it = osr_code_map_.find(method);
811 if (it == osr_code_map_.end()) {
812 return nullptr;
813 }
814 return OatQuickMethodHeader::FromCodePointer(it->second);
815}
816
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000817ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
818 ArtMethod* method,
819 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000820 bool retry_allocation)
821 // No thread safety analysis as we are using TryLock/Unlock explicitly.
822 NO_THREAD_SAFETY_ANALYSIS {
823 ProfilingInfo* info = nullptr;
824 if (!retry_allocation) {
825 // If we are allocating for the interpreter, just try to lock, to avoid
826 // lock contention with the JIT.
827 if (lock_.ExclusiveTryLock(self)) {
828 info = AddProfilingInfoInternal(self, method, entries);
829 lock_.ExclusiveUnlock(self);
830 }
831 } else {
832 {
833 MutexLock mu(self, lock_);
834 info = AddProfilingInfoInternal(self, method, entries);
835 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000836
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000837 if (info == nullptr) {
838 GarbageCollectCache(self);
839 MutexLock mu(self, lock_);
840 info = AddProfilingInfoInternal(self, method, entries);
841 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000842 }
843 return info;
844}
845
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000846ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000847 ArtMethod* method,
848 const std::vector<uint32_t>& entries) {
849 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100850 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000851 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000852
853 // Check whether some other thread has concurrently created it.
854 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
855 if (info != nullptr) {
856 return info;
857 }
858
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000859 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000860 if (data == nullptr) {
861 return nullptr;
862 }
863 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +0000864
865 // Make sure other threads see the data in the profiling info object before the
866 // store in the ArtMethod's ProfilingInfo pointer.
867 QuasiAtomic::ThreadFenceRelease();
868
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000869 method->SetProfilingInfo(info);
870 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000871 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000872 return info;
873}
874
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000875// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
876// is already held.
877void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
878 if (code_mspace_ == mspace) {
879 size_t result = code_end_;
880 code_end_ += increment;
881 return reinterpret_cast<void*>(result + code_map_->Begin());
882 } else {
883 DCHECK_EQ(data_mspace_, mspace);
884 size_t result = data_end_;
885 data_end_ += increment;
886 return reinterpret_cast<void*>(result + data_map_->Begin());
887 }
888}
889
Calin Juravle99629622016-04-19 16:33:46 +0100890void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
891 std::vector<MethodReference>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800892 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +0100893 MutexLock mu(Thread::Current(), lock_);
Calin Juravle99629622016-04-19 16:33:46 +0100894 for (const ProfilingInfo* info : profiling_infos_) {
895 ArtMethod* method = info->GetMethod();
896 const DexFile* dex_file = method->GetDexFile();
897 if (ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
898 methods.emplace_back(dex_file, method->GetDexMethodIndex());
Calin Juravle31f2c152015-10-23 17:56:15 +0100899 }
900 }
901}
902
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000903uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
904 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +0100905}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100906
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100907bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
908 MutexLock mu(Thread::Current(), lock_);
909 return osr_code_map_.find(method) != osr_code_map_.end();
910}
911
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000912bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
913 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100914 return false;
915 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000916
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000917 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000918 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
919 return false;
920 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000921
Nicolas Geoffrayc26f1282016-01-29 11:41:25 +0000922 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000923 if (info == nullptr) {
924 VLOG(jit) << PrettyMethod(method) << " needs a ProfilingInfo to be compiled";
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +0000925 // Because the counter is not atomic, there are some rare cases where we may not
926 // hit the threshold for creating the ProfilingInfo. Reset the counter now to
927 // "correct" this.
928 method->ClearCounter();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100929 return false;
930 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000931
buzbee454b3b62016-04-07 14:42:47 -0700932 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000933 return false;
934 }
935
buzbee454b3b62016-04-07 14:42:47 -0700936 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100937 return true;
938}
939
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000940ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000941 MutexLock mu(self, lock_);
942 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
943 if (info != nullptr) {
944 info->IncrementInlineUse();
945 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000946 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000947}
948
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000949void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000950 MutexLock mu(self, lock_);
951 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000952 DCHECK(info != nullptr);
953 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000954}
955
buzbee454b3b62016-04-07 14:42:47 -0700956void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100957 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
buzbee454b3b62016-04-07 14:42:47 -0700958 DCHECK(info->IsMethodBeingCompiled(osr));
959 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100960}
961
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000962size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
963 MutexLock mu(Thread::Current(), lock_);
964 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
965}
966
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000967void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
968 const OatQuickMethodHeader* header) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000969 ProfilingInfo* profiling_info = method->GetProfilingInfo(sizeof(void*));
970 if ((profiling_info != nullptr) &&
971 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
972 // Prevent future uses of the compiled code.
973 profiling_info->SetSavedEntryPoint(nullptr);
974 }
975
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000976 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
977 // The entrypoint is the one to invalidate, so we just update
978 // it to the interpreter entry point and clear the counter to get the method
979 // Jitted again.
980 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
981 method, GetQuickToInterpreterBridge());
982 method->ClearCounter();
983 } else {
984 MutexLock mu(Thread::Current(), lock_);
985 auto it = osr_code_map_.find(method);
986 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
987 // Remove the OSR method, to avoid using it again.
988 osr_code_map_.erase(it);
989 }
990 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000991 MutexLock mu(Thread::Current(), lock_);
992 number_of_deoptimizations_++;
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000993}
994
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000995uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
996 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
997 uint8_t* result = reinterpret_cast<uint8_t*>(
998 mspace_memalign(code_mspace_, alignment, code_size));
999 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1000 // Ensure the header ends up at expected instruction alignment.
1001 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1002 used_memory_for_code_ += mspace_usable_size(result);
1003 return result;
1004}
1005
1006void JitCodeCache::FreeCode(uint8_t* code) {
1007 used_memory_for_code_ -= mspace_usable_size(code);
1008 mspace_free(code_mspace_, code);
1009}
1010
1011uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1012 void* result = mspace_malloc(data_mspace_, data_size);
1013 used_memory_for_data_ += mspace_usable_size(result);
1014 return reinterpret_cast<uint8_t*>(result);
1015}
1016
1017void JitCodeCache::FreeData(uint8_t* data) {
1018 used_memory_for_data_ -= mspace_usable_size(data);
1019 mspace_free(data_mspace_, data);
1020}
1021
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001022void JitCodeCache::Dump(std::ostream& os) {
1023 MutexLock mu(Thread::Current(), lock_);
1024 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1025 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1026 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1027 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1028 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1029 << "Total number of JIT compilations for on stack replacement: "
1030 << number_of_osr_compilations_ << "\n"
1031 << "Total number of deoptimizations: " << number_of_deoptimizations_ << "\n"
1032 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001033 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1034 histogram_code_memory_use_.PrintMemoryUse(os);
1035 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001036}
1037
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001038} // namespace jit
1039} // namespace art