blob: 8c69bc810432e84738c37375df3da7e49469bc14 [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"
Calin Juravle31f2c152015-10-23 17:56:15 +010023#include "base/time_utils.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000024#include "debugger_interface.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010025#include "entrypoints/runtime_asm_entrypoints.h"
26#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000027#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000028#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010029#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080030#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080031#include "oat_file-inl.h"
Nicolas Geoffray62623402015-10-28 19:15:05 +000032#include "scoped_thread_state_change.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010033#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080034
35namespace art {
36namespace jit {
37
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010038static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
39static constexpr int kProtData = PROT_READ | PROT_WRITE;
40static constexpr int kProtCode = PROT_READ | PROT_EXEC;
41
42#define CHECKED_MPROTECT(memory, size, prot) \
43 do { \
44 int rc = mprotect(memory, size, prot); \
45 if (UNLIKELY(rc != 0)) { \
46 errno = rc; \
47 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
48 } \
49 } while (false) \
50
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000051JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
52 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000053 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000054 std::string* error_msg) {
55 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000056
57 // Generating debug information is mostly for using the 'perf' tool, which does
58 // not work with ashmem.
59 bool use_ashmem = !generate_debug_info;
60 // With 'perf', we want a 1-1 mapping between an address and a method.
61 bool garbage_collect_code = !generate_debug_info;
62
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000063 // We need to have 32 bit offsets from method headers in code cache which point to things
64 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
65 // Ensure we're below 1 GB to be safe.
66 if (max_capacity > 1 * GB) {
67 std::ostringstream oss;
68 oss << "Maxium code cache capacity is limited to 1 GB, "
69 << PrettySize(max_capacity) << " is too big";
70 *error_msg = oss.str();
71 return nullptr;
72 }
73
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080074 std::string error_str;
75 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010076 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000077 "data-code-cache", nullptr, max_capacity, kProtAll, false, false, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010078 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080079 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000080 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080081 *error_msg = oss.str();
82 return nullptr;
83 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010084
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000085 // Align both capacities to page size, as that's the unit mspaces use.
86 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
87 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
88
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +000089 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010090 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000091 size_t data_size = max_capacity / 2;
92 size_t code_size = max_capacity - data_size;
93 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010094 uint8_t* divider = data_map->Begin() + data_size;
95
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000096 MemMap* code_map =
97 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010098 if (code_map == nullptr) {
99 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000100 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100101 *error_msg = oss.str();
102 return nullptr;
103 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100104 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000105 data_size = initial_capacity / 2;
106 code_size = initial_capacity - data_size;
107 DCHECK_EQ(code_size + data_size, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000108 return new JitCodeCache(
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000109 code_map, data_map, code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800110}
111
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000112JitCodeCache::JitCodeCache(MemMap* code_map,
113 MemMap* data_map,
114 size_t initial_code_capacity,
115 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000116 size_t max_capacity,
117 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100118 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100119 lock_cond_("Jit code cache variable", lock_),
120 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100121 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000122 data_map_(data_map),
123 max_capacity_(max_capacity),
124 current_capacity_(initial_code_capacity + initial_data_capacity),
125 code_end_(initial_code_capacity),
126 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000127 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000128 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000129 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000130 used_memory_for_data_(0),
131 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000132 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000133 number_of_osr_compilations_(0),
134 number_of_deoptimizations_(0),
135 number_of_collections_(0) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100136
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000137 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000138 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
139 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100140
141 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
142 PLOG(FATAL) << "create_mspace_with_base failed";
143 }
144
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000145 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100146
147 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
148 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100149
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000150 VLOG(jit) << "Created jit code cache: initial data size="
151 << PrettySize(initial_data_capacity)
152 << ", initial code size="
153 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800154}
155
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100156bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100157 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800158}
159
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000160bool JitCodeCache::ContainsMethod(ArtMethod* method) {
161 MutexLock mu(Thread::Current(), lock_);
162 for (auto& it : method_code_map_) {
163 if (it.second == method) {
164 return true;
165 }
166 }
167 return false;
168}
169
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100170class ScopedCodeCacheWrite {
171 public:
172 explicit ScopedCodeCacheWrite(MemMap* code_map) : code_map_(code_map) {
173 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800174 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100175 ~ScopedCodeCacheWrite() {
176 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
177 }
178 private:
179 MemMap* const code_map_;
180
181 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
182};
183
184uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100185 ArtMethod* method,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100186 const uint8_t* mapping_table,
187 const uint8_t* vmap_table,
188 const uint8_t* gc_map,
189 size_t frame_size_in_bytes,
190 size_t core_spill_mask,
191 size_t fp_spill_mask,
192 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000193 size_t code_size,
194 bool osr) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100195 uint8_t* result = CommitCodeInternal(self,
196 method,
197 mapping_table,
198 vmap_table,
199 gc_map,
200 frame_size_in_bytes,
201 core_spill_mask,
202 fp_spill_mask,
203 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000204 code_size,
205 osr);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100206 if (result == nullptr) {
207 // Retry.
208 GarbageCollectCache(self);
209 result = CommitCodeInternal(self,
210 method,
211 mapping_table,
212 vmap_table,
213 gc_map,
214 frame_size_in_bytes,
215 core_spill_mask,
216 fp_spill_mask,
217 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000218 code_size,
219 osr);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100220 }
221 return result;
222}
223
224bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
225 bool in_collection = false;
226 while (collection_in_progress_) {
227 in_collection = true;
228 lock_cond_.Wait(self);
229 }
230 return in_collection;
231}
232
233static uintptr_t FromCodeToAllocation(const void* code) {
234 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
235 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
236}
237
238void JitCodeCache::FreeCode(const void* code_ptr, ArtMethod* method ATTRIBUTE_UNUSED) {
239 uintptr_t allocation = FromCodeToAllocation(code_ptr);
240 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000241 // Notify native debugger that we are about to remove the code.
242 // It does nothing if we are not using native debugger.
243 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000244
245 FreeData(const_cast<uint8_t*>(method_header->GetNativeGcMap()));
246 FreeData(const_cast<uint8_t*>(method_header->GetMappingTable()));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100247 // Use the offset directly to prevent sanity check that the method is
248 // compiled with optimizing.
249 // TODO(ngeoffray): Clean up.
250 if (method_header->vmap_table_offset_ != 0) {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000251 const uint8_t* data = method_header->code_ - method_header->vmap_table_offset_;
252 FreeData(const_cast<uint8_t*>(data));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100253 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000254 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100255}
256
257void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
258 MutexLock mu(self, lock_);
259 // We do not check if a code cache GC is in progress, as this method comes
260 // with the classlinker_classes_lock_ held, and suspending ourselves could
261 // lead to a deadlock.
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000262 {
263 ScopedCodeCacheWrite scc(code_map_.get());
264 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
265 if (alloc.ContainsUnsafe(it->second)) {
266 FreeCode(it->first, it->second);
267 it = method_code_map_.erase(it);
268 } else {
269 ++it;
270 }
271 }
272 }
Nicolas Geoffraya9b91312016-02-17 09:49:19 +0000273 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
274 if (alloc.ContainsUnsafe(it->first)) {
275 // Note that the code has already been removed in the loop above.
276 it = osr_code_map_.erase(it);
277 } else {
278 ++it;
279 }
280 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000281 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
282 ProfilingInfo* info = *it;
283 if (alloc.ContainsUnsafe(info->GetMethod())) {
284 info->GetMethod()->SetProfilingInfo(nullptr);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000285 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000286 it = profiling_infos_.erase(it);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100287 } else {
288 ++it;
289 }
290 }
291}
292
293uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
294 ArtMethod* method,
295 const uint8_t* mapping_table,
296 const uint8_t* vmap_table,
297 const uint8_t* gc_map,
298 size_t frame_size_in_bytes,
299 size_t core_spill_mask,
300 size_t fp_spill_mask,
301 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000302 size_t code_size,
303 bool osr) {
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100304 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
305 // Ensure the header ends up at expected instruction alignment.
306 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
307 size_t total_size = header_size + code_size;
308
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100309 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100310 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000311 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100312 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000313 ScopedThreadSuspension sts(self, kSuspended);
314 MutexLock mu(self, lock_);
315 WaitForPotentialCollectionToComplete(self);
316 {
317 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000318 memory = AllocateCode(total_size);
319 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000320 return nullptr;
321 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000322 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000323
324 std::copy(code, code + code_size, code_ptr);
325 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
326 new (method_header) OatQuickMethodHeader(
327 (mapping_table == nullptr) ? 0 : code_ptr - mapping_table,
328 (vmap_table == nullptr) ? 0 : code_ptr - vmap_table,
329 (gc_map == nullptr) ? 0 : code_ptr - gc_map,
330 frame_size_in_bytes,
331 core_spill_mask,
332 fp_spill_mask,
333 code_size);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100334 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100335
Roland Levillain32430262016-02-01 15:23:20 +0000336 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
337 reinterpret_cast<char*>(code_ptr + code_size));
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000338 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100339 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000340 // We need to update the entry point in the runnable state for the instrumentation.
341 {
342 MutexLock mu(self, lock_);
343 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000344 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000345 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000346 osr_code_map_.Put(method, code_ptr);
347 } else {
348 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
349 method, method_header->GetEntryPoint());
350 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000351 if (collection_in_progress_) {
352 // We need to update the live bitmap if there is a GC to ensure it sees this new
353 // code.
354 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
355 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000356 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000357 VLOG(jit)
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000358 << "JIT added (osr = " << std::boolalpha << osr << std::noboolalpha << ") "
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000359 << PrettyMethod(method) << "@" << method
360 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
361 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
362 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
363 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
364 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100365
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100366 return reinterpret_cast<uint8_t*>(method_header);
367}
368
369size_t JitCodeCache::CodeCacheSize() {
370 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000371 return CodeCacheSizeLocked();
372}
373
374size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000375 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100376}
377
378size_t JitCodeCache::DataCacheSize() {
379 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000380 return DataCacheSizeLocked();
381}
382
383size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000384 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800385}
386
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000387void JitCodeCache::ClearData(Thread* self, void* data) {
388 MutexLock mu(self, lock_);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000389 FreeData(reinterpret_cast<uint8_t*>(data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000390}
391
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100392uint8_t* JitCodeCache::ReserveData(Thread* self, size_t size) {
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100393 size = RoundUp(size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100394 uint8_t* result = nullptr;
395
396 {
397 ScopedThreadSuspension sts(self, kSuspended);
398 MutexLock mu(self, lock_);
399 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000400 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100401 }
402
403 if (result == nullptr) {
404 // Retry.
405 GarbageCollectCache(self);
406 ScopedThreadSuspension sts(self, kSuspended);
407 MutexLock mu(self, lock_);
408 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000409 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100410 }
411
412 return result;
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100413}
414
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800415uint8_t* JitCodeCache::AddDataArray(Thread* self, const uint8_t* begin, const uint8_t* end) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100416 uint8_t* result = ReserveData(self, end - begin);
417 if (result == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800418 return nullptr; // Out of space in the data cache.
419 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100420 std::copy(begin, end, result);
421 return result;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800422}
423
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100424class MarkCodeVisitor FINAL : public StackVisitor {
425 public:
426 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
427 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
428 code_cache_(code_cache_in),
429 bitmap_(code_cache_->GetLiveBitmap()) {}
430
431 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
432 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
433 if (method_header == nullptr) {
434 return true;
435 }
436 const void* code = method_header->GetCode();
437 if (code_cache_->ContainsPc(code)) {
438 // Use the atomic set version, as multiple threads are executing this code.
439 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
440 }
441 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800442 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100443
444 private:
445 JitCodeCache* const code_cache_;
446 CodeCacheBitmap* const bitmap_;
447};
448
449class MarkCodeClosure FINAL : public Closure {
450 public:
451 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
452 : code_cache_(code_cache), barrier_(barrier) {}
453
454 void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
455 DCHECK(thread == Thread::Current() || thread->IsSuspended());
456 MarkCodeVisitor visitor(thread, code_cache_);
457 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000458 if (kIsDebugBuild) {
459 // The stack walking code queries the side instrumentation stack if it
460 // sees an instrumentation exit pc, so the JIT code of methods in that stack
461 // must have been seen. We sanity check this below.
462 for (const instrumentation::InstrumentationStackFrame& frame
463 : *thread->GetInstrumentationStack()) {
464 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
465 // its stack frame, it is not the method owning return_pc_. We just pass null to
466 // LookupMethodHeader: the method is only checked against in debug builds.
467 OatQuickMethodHeader* method_header =
468 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
469 if (method_header != nullptr) {
470 const void* code = method_header->GetCode();
471 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
472 }
473 }
474 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700475 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800476 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100477
478 private:
479 JitCodeCache* const code_cache_;
480 Barrier* const barrier_;
481};
482
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000483void JitCodeCache::NotifyCollectionDone(Thread* self) {
484 collection_in_progress_ = false;
485 lock_cond_.Broadcast(self);
486}
487
488void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
489 size_t per_space_footprint = new_footprint / 2;
490 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
491 DCHECK_EQ(per_space_footprint * 2, new_footprint);
492 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
493 {
494 ScopedCodeCacheWrite scc(code_map_.get());
495 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
496 }
497}
498
499bool JitCodeCache::IncreaseCodeCacheCapacity() {
500 if (current_capacity_ == max_capacity_) {
501 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100502 }
503
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000504 // Double the capacity if we're below 1MB, or increase it by 1MB if
505 // we're above.
506 if (current_capacity_ < 1 * MB) {
507 current_capacity_ *= 2;
508 } else {
509 current_capacity_ += 1 * MB;
510 }
511 if (current_capacity_ > max_capacity_) {
512 current_capacity_ = max_capacity_;
513 }
514
515 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
516 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
517 }
518
519 SetFootprintLimit(current_capacity_);
520
521 return true;
522}
523
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000524void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
525 Barrier barrier(0);
526 size_t threads_running_checkpoint = 0;
527 MarkCodeClosure closure(this, &barrier);
528 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
529 // Now that we have run our checkpoint, move to a suspended state and wait
530 // for other threads to run the checkpoint.
531 ScopedThreadSuspension sts(self, kSuspended);
532 if (threads_running_checkpoint != 0) {
533 barrier.Increment(self, threads_running_checkpoint);
534 }
535}
536
Nicolas Geoffray35122442016-03-02 12:05:30 +0000537bool JitCodeCache::ShouldDoFullCollection() {
538 if (current_capacity_ == max_capacity_) {
539 // Always do a full collection when the code cache is full.
540 return true;
541 } else if (current_capacity_ < kReservedCapacity) {
542 // Always do partial collection when the code cache size is below the reserved
543 // capacity.
544 return false;
545 } else if (last_collection_increased_code_cache_) {
546 // This time do a full collection.
547 return true;
548 } else {
549 // This time do a partial collection.
550 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000551 }
552}
553
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000554void JitCodeCache::GarbageCollectCache(Thread* self) {
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000555 if (!garbage_collect_code_) {
556 MutexLock mu(self, lock_);
557 IncreaseCodeCacheCapacity();
558 return;
559 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100560
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000561 // Wait for an existing collection, or let everyone know we are starting one.
562 {
563 ScopedThreadSuspension sts(self, kSuspended);
564 MutexLock mu(self, lock_);
565 if (WaitForPotentialCollectionToComplete(self)) {
566 return;
567 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000568 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000569 live_bitmap_.reset(CodeCacheBitmap::Create(
570 "code-cache-bitmap",
571 reinterpret_cast<uintptr_t>(code_map_->Begin()),
572 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000573 collection_in_progress_ = true;
574 }
575 }
576
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000577 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000578 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000579 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000580
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000581 bool do_full_collection = false;
582 {
583 MutexLock mu(self, lock_);
584 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000585 }
586
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000587 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
588 LOG(INFO) << "Do "
589 << (do_full_collection ? "full" : "partial")
590 << " code cache collection, code="
591 << PrettySize(CodeCacheSize())
592 << ", data=" << PrettySize(DataCacheSize());
593 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000594
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000595 DoCollection(self, /* collect_profiling_info */ do_full_collection);
596
597 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
598 LOG(INFO) << "After code cache collection, code="
599 << PrettySize(CodeCacheSize())
600 << ", data=" << PrettySize(DataCacheSize());
601 }
602
603 {
604 MutexLock mu(self, lock_);
605
606 // Increase the code cache only when we do partial collections.
607 // TODO: base this strategy on how full the code cache is?
608 if (do_full_collection) {
609 last_collection_increased_code_cache_ = false;
610 } else {
611 last_collection_increased_code_cache_ = true;
612 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000613 }
614
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000615 bool next_collection_will_be_full = ShouldDoFullCollection();
616
617 // Start polling the liveness of compiled code to prepare for the next full collection.
618 // We avoid doing this if exit stubs are installed to not mess with the instrumentation.
619 // TODO(ngeoffray): Clean up instrumentation and code cache interactions.
620 if (!Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled() &&
621 next_collection_will_be_full) {
622 // Save the entry point of methods we have compiled, and update the entry
623 // point of those methods to the interpreter. If the method is invoked, the
624 // interpreter will update its entry point to the compiled code and call it.
625 for (ProfilingInfo* info : profiling_infos_) {
626 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
627 if (ContainsPc(entry_point)) {
628 info->SetSavedEntryPoint(entry_point);
629 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
630 }
631 }
632
633 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
634 }
635 live_bitmap_.reset(nullptr);
636 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000637 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000638 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000639 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000640}
641
642void JitCodeCache::RemoveUnusedAndUnmarkedCode(Thread* self) {
643 MutexLock mu(self, lock_);
644 ScopedCodeCacheWrite scc(code_map_.get());
645 // Iterate over all compiled code and remove entries that are not marked and not
646 // the entrypoint of their corresponding ArtMethod.
647 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
648 const void* code_ptr = it->first;
649 ArtMethod* method = it->second;
650 uintptr_t allocation = FromCodeToAllocation(code_ptr);
651 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
652 const void* entrypoint = method->GetEntryPointFromQuickCompiledCode();
653 if ((entrypoint == method_header->GetEntryPoint()) || GetLiveBitmap()->Test(allocation)) {
654 ++it;
655 } else {
656 if (entrypoint == GetQuickToInterpreterBridge()) {
657 method->ClearCounter();
658 }
659 FreeCode(code_ptr, method);
660 it = method_code_map_.erase(it);
661 }
662 }
663}
664
665void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
666 {
667 MutexLock mu(self, lock_);
668 if (collect_profiling_info) {
669 // Clear the profiling info of methods that do not have compiled code as entrypoint.
670 // Also remove the saved entry point from the ProfilingInfo objects.
671 for (ProfilingInfo* info : profiling_infos_) {
672 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
673 if (!ContainsPc(ptr) && !info->IsMethodBeingCompiled()) {
674 info->GetMethod()->SetProfilingInfo(nullptr);
675 }
676 info->SetSavedEntryPoint(nullptr);
677 }
678 } else if (kIsDebugBuild) {
679 // Sanity check that the profiling infos do not have a dangling entry point.
680 for (ProfilingInfo* info : profiling_infos_) {
681 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100682 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000683 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000684
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000685 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000686 // on thread stacks).
687 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100688 }
689
690 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000691 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100692
Nicolas Geoffray35122442016-03-02 12:05:30 +0000693 // Remove compiled code that is not the entrypoint of their method and not in the call
694 // stack.
695 RemoveUnusedAndUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000696
Nicolas Geoffray35122442016-03-02 12:05:30 +0000697 if (collect_profiling_info) {
698 MutexLock mu(self, lock_);
699 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100700 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000701 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000702 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000703 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
704 // that the compiled code would not get revived. As mutator threads run concurrently,
705 // they may have revived the compiled code, and now we are in the situation where
706 // a method has compiled code but no ProfilingInfo.
707 // We make sure compiled methods have a ProfilingInfo object. It is needed for
708 // code cache collection.
Nicolas Geoffray35122442016-03-02 12:05:30 +0000709 if (ContainsPc(ptr) && info->GetMethod()->GetProfilingInfo(sizeof(void*)) == nullptr) {
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000710 // We clear the inline caches as classes in it might be stalled.
711 info->ClearInlineCaches();
712 // Do a fence to make sure the clearing is seen before attaching to the method.
713 QuasiAtomic::ThreadFenceRelease();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000714 info->GetMethod()->SetProfilingInfo(info);
715 } else if (info->GetMethod()->GetProfilingInfo(sizeof(void*)) != info) {
716 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000717 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100718 return true;
719 }
720 return false;
721 });
722 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +0000723 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100724 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800725}
726
Nicolas Geoffray35122442016-03-02 12:05:30 +0000727bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
728 // Check that methods we have compiled do have a ProfilingInfo object. We would
729 // have memory leaks of compiled code otherwise.
730 for (const auto& it : method_code_map_) {
731 ArtMethod* method = it.second;
732 if (method->GetProfilingInfo(sizeof(void*)) == nullptr) {
733 const void* code_ptr = it.first;
734 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
735 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
736 // If the code is not dead, then we have a problem. Note that this can even
737 // happen just after a collection, as mutator threads are running in parallel
738 // and could deoptimize an existing compiled code.
739 return false;
740 }
741 }
742 }
743 return true;
744}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100745
746OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
747 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
748 if (kRuntimeISA == kArm) {
749 // On Thumb-2, the pc is offset by one.
750 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800751 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100752 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
753 return nullptr;
754 }
755
756 MutexLock mu(Thread::Current(), lock_);
757 if (method_code_map_.empty()) {
758 return nullptr;
759 }
760 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
761 --it;
762
763 const void* code_ptr = it->first;
764 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
765 if (!method_header->Contains(pc)) {
766 return nullptr;
767 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000768 if (kIsDebugBuild && method != nullptr) {
769 DCHECK_EQ(it->second, method)
770 << PrettyMethod(method) << " " << PrettyMethod(it->second) << " " << std::hex << pc;
771 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100772 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800773}
774
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000775OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
776 MutexLock mu(Thread::Current(), lock_);
777 auto it = osr_code_map_.find(method);
778 if (it == osr_code_map_.end()) {
779 return nullptr;
780 }
781 return OatQuickMethodHeader::FromCodePointer(it->second);
782}
783
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000784ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
785 ArtMethod* method,
786 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000787 bool retry_allocation)
788 // No thread safety analysis as we are using TryLock/Unlock explicitly.
789 NO_THREAD_SAFETY_ANALYSIS {
790 ProfilingInfo* info = nullptr;
791 if (!retry_allocation) {
792 // If we are allocating for the interpreter, just try to lock, to avoid
793 // lock contention with the JIT.
794 if (lock_.ExclusiveTryLock(self)) {
795 info = AddProfilingInfoInternal(self, method, entries);
796 lock_.ExclusiveUnlock(self);
797 }
798 } else {
799 {
800 MutexLock mu(self, lock_);
801 info = AddProfilingInfoInternal(self, method, entries);
802 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000803
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000804 if (info == nullptr) {
805 GarbageCollectCache(self);
806 MutexLock mu(self, lock_);
807 info = AddProfilingInfoInternal(self, method, entries);
808 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000809 }
810 return info;
811}
812
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000813ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000814 ArtMethod* method,
815 const std::vector<uint32_t>& entries) {
816 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100817 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000818 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000819
820 // Check whether some other thread has concurrently created it.
821 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
822 if (info != nullptr) {
823 return info;
824 }
825
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000826 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000827 if (data == nullptr) {
828 return nullptr;
829 }
830 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +0000831
832 // Make sure other threads see the data in the profiling info object before the
833 // store in the ArtMethod's ProfilingInfo pointer.
834 QuasiAtomic::ThreadFenceRelease();
835
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000836 method->SetProfilingInfo(info);
837 profiling_infos_.push_back(info);
838 return info;
839}
840
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000841// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
842// is already held.
843void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
844 if (code_mspace_ == mspace) {
845 size_t result = code_end_;
846 code_end_ += increment;
847 return reinterpret_cast<void*>(result + code_map_->Begin());
848 } else {
849 DCHECK_EQ(data_mspace_, mspace);
850 size_t result = data_end_;
851 data_end_ += increment;
852 return reinterpret_cast<void*>(result + data_map_->Begin());
853 }
854}
855
Calin Juravleb4eddd22016-01-13 15:52:33 -0800856void JitCodeCache::GetCompiledArtMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000857 std::vector<ArtMethod*>& methods) {
Calin Juravle31f2c152015-10-23 17:56:15 +0100858 MutexLock mu(Thread::Current(), lock_);
859 for (auto it : method_code_map_) {
Calin Juravle66f55232015-12-08 15:09:10 +0000860 if (ContainsElement(dex_base_locations, it.second->GetDexFile()->GetBaseLocation())) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000861 methods.push_back(it.second);
Calin Juravle31f2c152015-10-23 17:56:15 +0100862 }
863 }
864}
865
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000866uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
867 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +0100868}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100869
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000870bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
871 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000872 VLOG(jit) << PrettyMethod(method) << " is already compiled";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100873 return false;
874 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000875
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000876 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000877 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000878 VLOG(jit) << PrettyMethod(method) << " is already osr compiled";
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000879 return false;
880 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000881
Nicolas Geoffrayc26f1282016-01-29 11:41:25 +0000882 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000883 if (info == nullptr) {
884 VLOG(jit) << PrettyMethod(method) << " needs a ProfilingInfo to be compiled";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100885 return false;
886 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000887
888 if (info->IsMethodBeingCompiled()) {
889 VLOG(jit) << PrettyMethod(method) << " is already being compiled";
890 return false;
891 }
892
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100893 info->SetIsMethodBeingCompiled(true);
894 return true;
895}
896
897void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED) {
898 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
899 DCHECK(info->IsMethodBeingCompiled());
900 info->SetIsMethodBeingCompiled(false);
901}
902
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000903size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
904 MutexLock mu(Thread::Current(), lock_);
905 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
906}
907
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000908void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
909 const OatQuickMethodHeader* header) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000910 ProfilingInfo* profiling_info = method->GetProfilingInfo(sizeof(void*));
911 if ((profiling_info != nullptr) &&
912 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
913 // Prevent future uses of the compiled code.
914 profiling_info->SetSavedEntryPoint(nullptr);
915 }
916
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000917 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
918 // The entrypoint is the one to invalidate, so we just update
919 // it to the interpreter entry point and clear the counter to get the method
920 // Jitted again.
921 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
922 method, GetQuickToInterpreterBridge());
923 method->ClearCounter();
924 } else {
925 MutexLock mu(Thread::Current(), lock_);
926 auto it = osr_code_map_.find(method);
927 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
928 // Remove the OSR method, to avoid using it again.
929 osr_code_map_.erase(it);
930 }
931 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000932 MutexLock mu(Thread::Current(), lock_);
933 number_of_deoptimizations_++;
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000934}
935
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000936uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
937 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
938 uint8_t* result = reinterpret_cast<uint8_t*>(
939 mspace_memalign(code_mspace_, alignment, code_size));
940 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
941 // Ensure the header ends up at expected instruction alignment.
942 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
943 used_memory_for_code_ += mspace_usable_size(result);
944 return result;
945}
946
947void JitCodeCache::FreeCode(uint8_t* code) {
948 used_memory_for_code_ -= mspace_usable_size(code);
949 mspace_free(code_mspace_, code);
950}
951
952uint8_t* JitCodeCache::AllocateData(size_t data_size) {
953 void* result = mspace_malloc(data_mspace_, data_size);
954 used_memory_for_data_ += mspace_usable_size(result);
955 return reinterpret_cast<uint8_t*>(result);
956}
957
958void JitCodeCache::FreeData(uint8_t* data) {
959 used_memory_for_data_ -= mspace_usable_size(data);
960 mspace_free(data_mspace_, data);
961}
962
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000963void JitCodeCache::Dump(std::ostream& os) {
964 MutexLock mu(Thread::Current(), lock_);
965 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
966 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
967 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
968 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
969 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
970 << "Total number of JIT compilations for on stack replacement: "
971 << number_of_osr_compilations_ << "\n"
972 << "Total number of deoptimizations: " << number_of_deoptimizations_ << "\n"
973 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
974}
975
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800976} // namespace jit
977} // namespace art