blob: af47da63c4a5df9de9fdba01f8e9d741161f653c [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
43#define CHECKED_MPROTECT(memory, size, prot) \
44 do { \
45 int rc = mprotect(memory, size, prot); \
46 if (UNLIKELY(rc != 0)) { \
47 errno = rc; \
48 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
49 } \
50 } while (false) \
51
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000052JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
53 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000054 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000055 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080056 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000057 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000058
59 // Generating debug information is mostly for using the 'perf' tool, which does
60 // not work with ashmem.
61 bool use_ashmem = !generate_debug_info;
62 // With 'perf', we want a 1-1 mapping between an address and a method.
63 bool garbage_collect_code = !generate_debug_info;
64
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000065 // We need to have 32 bit offsets from method headers in code cache which point to things
66 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
67 // Ensure we're below 1 GB to be safe.
68 if (max_capacity > 1 * GB) {
69 std::ostringstream oss;
70 oss << "Maxium code cache capacity is limited to 1 GB, "
71 << PrettySize(max_capacity) << " is too big";
72 *error_msg = oss.str();
73 return nullptr;
74 }
75
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080076 std::string error_str;
77 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010078 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000079 "data-code-cache", nullptr, max_capacity, kProtAll, false, false, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010080 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080081 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000082 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080083 *error_msg = oss.str();
84 return nullptr;
85 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010086
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000087 // Align both capacities to page size, as that's the unit mspaces use.
88 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
89 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
90
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +000091 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010092 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000093 size_t data_size = max_capacity / 2;
94 size_t code_size = max_capacity - data_size;
95 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010096 uint8_t* divider = data_map->Begin() + data_size;
97
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000098 MemMap* code_map =
99 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100100 if (code_map == nullptr) {
101 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000102 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100103 *error_msg = oss.str();
104 return nullptr;
105 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100106 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000107 data_size = initial_capacity / 2;
108 code_size = initial_capacity - data_size;
109 DCHECK_EQ(code_size + data_size, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000110 return new JitCodeCache(
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000111 code_map, data_map, code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800112}
113
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000114JitCodeCache::JitCodeCache(MemMap* code_map,
115 MemMap* data_map,
116 size_t initial_code_capacity,
117 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000118 size_t max_capacity,
119 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100120 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100121 lock_cond_("Jit code cache variable", lock_),
122 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100123 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000124 data_map_(data_map),
125 max_capacity_(max_capacity),
126 current_capacity_(initial_code_capacity + initial_data_capacity),
127 code_end_(initial_code_capacity),
128 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000129 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000130 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000131 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000132 used_memory_for_data_(0),
133 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000134 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000135 number_of_osr_compilations_(0),
136 number_of_deoptimizations_(0),
137 number_of_collections_(0) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100138
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000139 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000140 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
141 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100142
143 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
144 PLOG(FATAL) << "create_mspace_with_base failed";
145 }
146
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000147 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100148
149 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
150 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100151
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000152 VLOG(jit) << "Created jit code cache: initial data size="
153 << PrettySize(initial_data_capacity)
154 << ", initial code size="
155 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800156}
157
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100158bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100159 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800160}
161
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000162bool JitCodeCache::ContainsMethod(ArtMethod* method) {
163 MutexLock mu(Thread::Current(), lock_);
164 for (auto& it : method_code_map_) {
165 if (it.second == method) {
166 return true;
167 }
168 }
169 return false;
170}
171
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800172class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100173 public:
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800174 explicit ScopedCodeCacheWrite(MemMap* code_map)
175 : ScopedTrace("ScopedCodeCacheWrite"),
176 code_map_(code_map) {
177 ScopedTrace trace("mprotect all");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100178 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800179 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100180 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800181 ScopedTrace trace("mprotect code");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100182 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
183 }
184 private:
185 MemMap* const code_map_;
186
187 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
188};
189
190uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100191 ArtMethod* method,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100192 const uint8_t* mapping_table,
193 const uint8_t* vmap_table,
194 const uint8_t* gc_map,
195 size_t frame_size_in_bytes,
196 size_t core_spill_mask,
197 size_t fp_spill_mask,
198 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000199 size_t code_size,
200 bool osr) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100201 uint8_t* result = CommitCodeInternal(self,
202 method,
203 mapping_table,
204 vmap_table,
205 gc_map,
206 frame_size_in_bytes,
207 core_spill_mask,
208 fp_spill_mask,
209 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000210 code_size,
211 osr);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100212 if (result == nullptr) {
213 // Retry.
214 GarbageCollectCache(self);
215 result = CommitCodeInternal(self,
216 method,
217 mapping_table,
218 vmap_table,
219 gc_map,
220 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
251 FreeData(const_cast<uint8_t*>(method_header->GetNativeGcMap()));
252 FreeData(const_cast<uint8_t*>(method_header->GetMappingTable()));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100253 // Use the offset directly to prevent sanity check that the method is
254 // compiled with optimizing.
255 // TODO(ngeoffray): Clean up.
256 if (method_header->vmap_table_offset_ != 0) {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000257 const uint8_t* data = method_header->code_ - method_header->vmap_table_offset_;
258 FreeData(const_cast<uint8_t*>(data));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100259 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000260 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100261}
262
263void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800264 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100265 MutexLock mu(self, lock_);
266 // We do not check if a code cache GC is in progress, as this method comes
267 // with the classlinker_classes_lock_ held, and suspending ourselves could
268 // lead to a deadlock.
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000269 {
270 ScopedCodeCacheWrite scc(code_map_.get());
271 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
272 if (alloc.ContainsUnsafe(it->second)) {
273 FreeCode(it->first, it->second);
274 it = method_code_map_.erase(it);
275 } else {
276 ++it;
277 }
278 }
279 }
Nicolas Geoffraya9b91312016-02-17 09:49:19 +0000280 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
281 if (alloc.ContainsUnsafe(it->first)) {
282 // Note that the code has already been removed in the loop above.
283 it = osr_code_map_.erase(it);
284 } else {
285 ++it;
286 }
287 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000288 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
289 ProfilingInfo* info = *it;
290 if (alloc.ContainsUnsafe(info->GetMethod())) {
291 info->GetMethod()->SetProfilingInfo(nullptr);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000292 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000293 it = profiling_infos_.erase(it);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100294 } else {
295 ++it;
296 }
297 }
298}
299
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000300void JitCodeCache::ClearGcRootsInInlineCaches(Thread* self) {
301 MutexLock mu(self, lock_);
302 for (ProfilingInfo* info : profiling_infos_) {
303 if (!info->IsInUseByCompiler()) {
304 info->ClearGcRootsInInlineCaches();
305 }
306 }
307}
308
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100309uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
310 ArtMethod* method,
311 const uint8_t* mapping_table,
312 const uint8_t* vmap_table,
313 const uint8_t* gc_map,
314 size_t frame_size_in_bytes,
315 size_t core_spill_mask,
316 size_t fp_spill_mask,
317 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000318 size_t code_size,
319 bool osr) {
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100320 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
321 // Ensure the header ends up at expected instruction alignment.
322 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
323 size_t total_size = header_size + code_size;
324
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100325 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100326 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000327 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100328 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000329 ScopedThreadSuspension sts(self, kSuspended);
330 MutexLock mu(self, lock_);
331 WaitForPotentialCollectionToComplete(self);
332 {
333 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000334 memory = AllocateCode(total_size);
335 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000336 return nullptr;
337 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000338 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000339
340 std::copy(code, code + code_size, code_ptr);
341 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
342 new (method_header) OatQuickMethodHeader(
343 (mapping_table == nullptr) ? 0 : code_ptr - mapping_table,
344 (vmap_table == nullptr) ? 0 : code_ptr - vmap_table,
345 (gc_map == nullptr) ? 0 : code_ptr - gc_map,
346 frame_size_in_bytes,
347 core_spill_mask,
348 fp_spill_mask,
349 code_size);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100350 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100351
Roland Levillain32430262016-02-01 15:23:20 +0000352 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
353 reinterpret_cast<char*>(code_ptr + code_size));
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000354 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100355 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000356 // We need to update the entry point in the runnable state for the instrumentation.
357 {
358 MutexLock mu(self, lock_);
359 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000360 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000361 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000362 osr_code_map_.Put(method, code_ptr);
363 } else {
364 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
365 method, method_header->GetEntryPoint());
366 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000367 if (collection_in_progress_) {
368 // We need to update the live bitmap if there is a GC to ensure it sees this new
369 // code.
370 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
371 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000372 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000373 VLOG(jit)
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000374 << "JIT added (osr = " << std::boolalpha << osr << std::noboolalpha << ") "
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000375 << PrettyMethod(method) << "@" << method
376 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
377 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
378 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
379 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
380 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100381
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100382 return reinterpret_cast<uint8_t*>(method_header);
383}
384
385size_t JitCodeCache::CodeCacheSize() {
386 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000387 return CodeCacheSizeLocked();
388}
389
390size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000391 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100392}
393
394size_t JitCodeCache::DataCacheSize() {
395 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000396 return DataCacheSizeLocked();
397}
398
399size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000400 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800401}
402
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000403void JitCodeCache::ClearData(Thread* self, void* data) {
404 MutexLock mu(self, lock_);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000405 FreeData(reinterpret_cast<uint8_t*>(data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000406}
407
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100408uint8_t* JitCodeCache::ReserveData(Thread* self, size_t size) {
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100409 size = RoundUp(size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100410 uint8_t* result = nullptr;
411
412 {
413 ScopedThreadSuspension sts(self, kSuspended);
414 MutexLock mu(self, lock_);
415 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000416 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100417 }
418
419 if (result == nullptr) {
420 // Retry.
421 GarbageCollectCache(self);
422 ScopedThreadSuspension sts(self, kSuspended);
423 MutexLock mu(self, lock_);
424 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000425 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100426 }
427
428 return result;
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100429}
430
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800431uint8_t* JitCodeCache::AddDataArray(Thread* self, const uint8_t* begin, const uint8_t* end) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100432 uint8_t* result = ReserveData(self, end - begin);
433 if (result == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800434 return nullptr; // Out of space in the data cache.
435 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100436 std::copy(begin, end, result);
437 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.
636 // We avoid doing this if exit stubs are installed to not mess with the instrumentation.
637 // TODO(ngeoffray): Clean up instrumentation and code cache interactions.
638 if (!Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled() &&
639 next_collection_will_be_full) {
640 // Save the entry point of methods we have compiled, and update the entry
641 // point of those methods to the interpreter. If the method is invoked, the
642 // interpreter will update its entry point to the compiled code and call it.
643 for (ProfilingInfo* info : profiling_infos_) {
644 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
645 if (ContainsPc(entry_point)) {
646 info->SetSavedEntryPoint(entry_point);
647 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
648 }
649 }
650
651 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
652 }
653 live_bitmap_.reset(nullptr);
654 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000655 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000656 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000657 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000658}
659
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000660void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800661 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000662 MutexLock mu(self, lock_);
663 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000664 // Iterate over all compiled code and remove entries that are not marked.
Nicolas Geoffray35122442016-03-02 12:05:30 +0000665 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
666 const void* code_ptr = it->first;
667 ArtMethod* method = it->second;
668 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000669 if (GetLiveBitmap()->Test(allocation)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000670 ++it;
671 } else {
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000672 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
673 if (method_header->GetEntryPoint() == GetQuickToInterpreterBridge()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000674 method->ClearCounter();
675 }
676 FreeCode(code_ptr, method);
677 it = method_code_map_.erase(it);
678 }
679 }
680}
681
682void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800683 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000684 {
685 MutexLock mu(self, lock_);
686 if (collect_profiling_info) {
687 // Clear the profiling info of methods that do not have compiled code as entrypoint.
688 // Also remove the saved entry point from the ProfilingInfo objects.
689 for (ProfilingInfo* info : profiling_infos_) {
690 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000691 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000692 info->GetMethod()->SetProfilingInfo(nullptr);
693 }
694 info->SetSavedEntryPoint(nullptr);
695 }
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);
871 return info;
872}
873
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000874// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
875// is already held.
876void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
877 if (code_mspace_ == mspace) {
878 size_t result = code_end_;
879 code_end_ += increment;
880 return reinterpret_cast<void*>(result + code_map_->Begin());
881 } else {
882 DCHECK_EQ(data_mspace_, mspace);
883 size_t result = data_end_;
884 data_end_ += increment;
885 return reinterpret_cast<void*>(result + data_map_->Begin());
886 }
887}
888
Calin Juravleb4eddd22016-01-13 15:52:33 -0800889void JitCodeCache::GetCompiledArtMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000890 std::vector<ArtMethod*>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800891 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +0100892 MutexLock mu(Thread::Current(), lock_);
893 for (auto it : method_code_map_) {
Calin Juravle66f55232015-12-08 15:09:10 +0000894 if (ContainsElement(dex_base_locations, it.second->GetDexFile()->GetBaseLocation())) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000895 methods.push_back(it.second);
Calin Juravle31f2c152015-10-23 17:56:15 +0100896 }
897 }
898}
899
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000900uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
901 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +0100902}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100903
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000904bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
905 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000906 VLOG(jit) << PrettyMethod(method) << " is already compiled";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100907 return false;
908 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000909
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000910 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000911 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000912 VLOG(jit) << PrettyMethod(method) << " is already osr compiled";
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000913 return false;
914 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000915
Nicolas Geoffrayc26f1282016-01-29 11:41:25 +0000916 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000917 if (info == nullptr) {
918 VLOG(jit) << PrettyMethod(method) << " needs a ProfilingInfo to be compiled";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100919 return false;
920 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000921
922 if (info->IsMethodBeingCompiled()) {
923 VLOG(jit) << PrettyMethod(method) << " is already being compiled";
924 return false;
925 }
926
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100927 info->SetIsMethodBeingCompiled(true);
928 return true;
929}
930
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000931ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000932 MutexLock mu(self, lock_);
933 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
934 if (info != nullptr) {
935 info->IncrementInlineUse();
936 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000937 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000938}
939
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000940void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000941 MutexLock mu(self, lock_);
942 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000943 DCHECK(info != nullptr);
944 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000945}
946
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100947void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED) {
948 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
949 DCHECK(info->IsMethodBeingCompiled());
950 info->SetIsMethodBeingCompiled(false);
951}
952
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000953size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
954 MutexLock mu(Thread::Current(), lock_);
955 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
956}
957
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000958void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
959 const OatQuickMethodHeader* header) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000960 ProfilingInfo* profiling_info = method->GetProfilingInfo(sizeof(void*));
961 if ((profiling_info != nullptr) &&
962 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
963 // Prevent future uses of the compiled code.
964 profiling_info->SetSavedEntryPoint(nullptr);
965 }
966
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000967 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
968 // The entrypoint is the one to invalidate, so we just update
969 // it to the interpreter entry point and clear the counter to get the method
970 // Jitted again.
971 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
972 method, GetQuickToInterpreterBridge());
973 method->ClearCounter();
974 } else {
975 MutexLock mu(Thread::Current(), lock_);
976 auto it = osr_code_map_.find(method);
977 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
978 // Remove the OSR method, to avoid using it again.
979 osr_code_map_.erase(it);
980 }
981 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000982 MutexLock mu(Thread::Current(), lock_);
983 number_of_deoptimizations_++;
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000984}
985
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000986uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
987 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
988 uint8_t* result = reinterpret_cast<uint8_t*>(
989 mspace_memalign(code_mspace_, alignment, code_size));
990 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
991 // Ensure the header ends up at expected instruction alignment.
992 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
993 used_memory_for_code_ += mspace_usable_size(result);
994 return result;
995}
996
997void JitCodeCache::FreeCode(uint8_t* code) {
998 used_memory_for_code_ -= mspace_usable_size(code);
999 mspace_free(code_mspace_, code);
1000}
1001
1002uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1003 void* result = mspace_malloc(data_mspace_, data_size);
1004 used_memory_for_data_ += mspace_usable_size(result);
1005 return reinterpret_cast<uint8_t*>(result);
1006}
1007
1008void JitCodeCache::FreeData(uint8_t* data) {
1009 used_memory_for_data_ -= mspace_usable_size(data);
1010 mspace_free(data_mspace_, data);
1011}
1012
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001013void JitCodeCache::Dump(std::ostream& os) {
1014 MutexLock mu(Thread::Current(), lock_);
1015 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1016 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1017 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1018 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1019 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1020 << "Total number of JIT compilations for on stack replacement: "
1021 << number_of_osr_compilations_ << "\n"
1022 << "Total number of deoptimizations: " << number_of_deoptimizations_ << "\n"
1023 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
1024}
1025
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001026} // namespace jit
1027} // namespace art