blob: f0ed237fe0d63cfbb4c4f6bd4e16b0534910ecc4 [file] [log] [blame]
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001/*
2 * Copyright 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "jit_code_cache.h"
18
19#include <sstream>
20
Mathieu Chartiere401d142015-04-22 13:56:20 -070021#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070022#include "base/enums.h"
Calin Juravle66f55232015-12-08 15:09:10 +000023#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080024#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010025#include "base/time_utils.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000026#include "debugger_interface.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010027#include "entrypoints/runtime_asm_entrypoints.h"
28#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010029#include "gc/scoped_gc_critical_section.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000030#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000031#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010032#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080033#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080034#include "oat_file-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070035#include "scoped_thread_state_change-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010036#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080037
38namespace art {
39namespace jit {
40
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010041static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
42static constexpr int kProtData = PROT_READ | PROT_WRITE;
43static constexpr int kProtCode = PROT_READ | PROT_EXEC;
44
Nicolas Geoffray933330a2016-03-16 14:20:06 +000045static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
46static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
47
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010048#define CHECKED_MPROTECT(memory, size, prot) \
49 do { \
50 int rc = mprotect(memory, size, prot); \
51 if (UNLIKELY(rc != 0)) { \
52 errno = rc; \
53 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
54 } \
55 } while (false) \
56
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000057JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
58 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000059 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000060 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080061 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000062 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000063
64 // Generating debug information is mostly for using the 'perf' tool, which does
65 // not work with ashmem.
66 bool use_ashmem = !generate_debug_info;
67 // With 'perf', we want a 1-1 mapping between an address and a method.
68 bool garbage_collect_code = !generate_debug_info;
69
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000070 // We need to have 32 bit offsets from method headers in code cache which point to things
71 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
72 // Ensure we're below 1 GB to be safe.
73 if (max_capacity > 1 * GB) {
74 std::ostringstream oss;
75 oss << "Maxium code cache capacity is limited to 1 GB, "
76 << PrettySize(max_capacity) << " is too big";
77 *error_msg = oss.str();
78 return nullptr;
79 }
80
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080081 std::string error_str;
82 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +000083 // Map in low 4gb to simplify accessing root tables for x86_64.
84 // We could do PC-relative addressing to avoid this problem, but that
85 // would require reserving code and data area before submitting, which
86 // means more windows for the code memory to be RWX.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010087 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +000088 "data-code-cache", nullptr,
89 max_capacity,
90 kProtAll,
91 /* low_4gb */ true,
92 /* reuse */ false,
93 &error_str,
94 use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010095 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080096 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000097 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080098 *error_msg = oss.str();
99 return nullptr;
100 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100101
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000102 // Align both capacities to page size, as that's the unit mspaces use.
103 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
104 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
105
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +0000106 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100107 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000108 size_t data_size = max_capacity / 2;
109 size_t code_size = max_capacity - data_size;
110 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100111 uint8_t* divider = data_map->Begin() + data_size;
112
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000113 MemMap* code_map =
114 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100115 if (code_map == nullptr) {
116 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000117 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100118 *error_msg = oss.str();
119 return nullptr;
120 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100121 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000122 data_size = initial_capacity / 2;
123 code_size = initial_capacity - data_size;
124 DCHECK_EQ(code_size + data_size, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000125 return new JitCodeCache(
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000126 code_map, data_map, code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800127}
128
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000129JitCodeCache::JitCodeCache(MemMap* code_map,
130 MemMap* data_map,
131 size_t initial_code_capacity,
132 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000133 size_t max_capacity,
134 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100135 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100136 lock_cond_("Jit code cache variable", lock_),
137 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100138 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000139 data_map_(data_map),
140 max_capacity_(max_capacity),
141 current_capacity_(initial_code_capacity + initial_data_capacity),
142 code_end_(initial_code_capacity),
143 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000144 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000145 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000146 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000147 used_memory_for_data_(0),
148 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000149 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000150 number_of_osr_compilations_(0),
151 number_of_deoptimizations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000152 number_of_collections_(0),
153 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
154 histogram_code_memory_use_("Memory used for compiled code", 16),
155 histogram_profiling_info_memory_use_("Memory used for profiling info", 16) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100156
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000157 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000158 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
159 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100160
161 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
162 PLOG(FATAL) << "create_mspace_with_base failed";
163 }
164
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000165 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100166
167 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
168 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100169
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000170 VLOG(jit) << "Created jit code cache: initial data size="
171 << PrettySize(initial_data_capacity)
172 << ", initial code size="
173 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800174}
175
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100176bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100177 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800178}
179
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000180bool JitCodeCache::ContainsMethod(ArtMethod* method) {
181 MutexLock mu(Thread::Current(), lock_);
182 for (auto& it : method_code_map_) {
183 if (it.second == method) {
184 return true;
185 }
186 }
187 return false;
188}
189
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800190class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100191 public:
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800192 explicit ScopedCodeCacheWrite(MemMap* code_map)
193 : ScopedTrace("ScopedCodeCacheWrite"),
194 code_map_(code_map) {
195 ScopedTrace trace("mprotect all");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100196 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800197 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100198 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800199 ScopedTrace trace("mprotect code");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100200 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
201 }
202 private:
203 MemMap* const code_map_;
204
205 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
206};
207
208uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100209 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000210 uint8_t* stack_map,
211 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100212 size_t frame_size_in_bytes,
213 size_t core_spill_mask,
214 size_t fp_spill_mask,
215 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000216 size_t code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000217 bool osr,
218 Handle<mirror::ObjectArray<mirror::Object>> roots) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100219 uint8_t* result = CommitCodeInternal(self,
220 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000221 stack_map,
222 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100223 frame_size_in_bytes,
224 core_spill_mask,
225 fp_spill_mask,
226 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000227 code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000228 osr,
229 roots);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100230 if (result == nullptr) {
231 // Retry.
232 GarbageCollectCache(self);
233 result = CommitCodeInternal(self,
234 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000235 stack_map,
236 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100237 frame_size_in_bytes,
238 core_spill_mask,
239 fp_spill_mask,
240 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000241 code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000242 osr,
243 roots);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100244 }
245 return result;
246}
247
248bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
249 bool in_collection = false;
250 while (collection_in_progress_) {
251 in_collection = true;
252 lock_cond_.Wait(self);
253 }
254 return in_collection;
255}
256
257static uintptr_t FromCodeToAllocation(const void* code) {
258 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
259 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
260}
261
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000262static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
263 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
264}
265
266static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
267 // The length of the table is stored just before the stack map (and therefore at the end of
268 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
269 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
270}
271
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800272static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
273 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
274 // pointer.
275 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
276}
277
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000278static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
279 REQUIRES_SHARED(Locks::mutator_lock_) {
280 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800281 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000282 // Put all roots in `roots_data`.
283 for (uint32_t i = 0; i < length; ++i) {
284 ObjPtr<mirror::Object> object = roots->Get(i);
285 if (kIsDebugBuild) {
286 // Ensure the string is strongly interned. b/32995596
287 CHECK(object->IsString());
288 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
289 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
290 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
291 }
292 gc_roots[i] = GcRoot<mirror::Object>(object);
293 }
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800294 FillRootTableLength(roots_data, length);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000295}
296
297static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
298 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
299 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
300 uint32_t roots = GetNumberOfRoots(data);
301 if (number_of_roots != nullptr) {
302 *number_of_roots = roots;
303 }
304 return data - ComputeRootTableSize(roots);
305}
306
307void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
308 MutexLock mu(Thread::Current(), lock_);
309 for (const auto& entry : method_code_map_) {
310 uint32_t number_of_roots = 0;
311 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
312 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
313 for (uint32_t i = 0; i < number_of_roots; ++i) {
314 // This does not need a read barrier because this is called by GC.
315 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
316 DCHECK(object != nullptr);
317 mirror::Object* new_object = visitor->IsMarked(object);
318 // We know the string is marked because it's a strongly-interned string that
319 // is always alive. The IsMarked implementation of the CMS collector returns
320 // null for newly allocated objects, but we know those haven't moved. Therefore,
321 // only update the entry if we get a different non-null string.
322 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
323 // out of the weak access/creation pause. b/32167580
324 if (new_object != nullptr && new_object != object) {
325 DCHECK(new_object->IsString());
326 roots[i] = GcRoot<mirror::Object>(new_object);
327 }
328 }
329 }
330}
331
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100332void JitCodeCache::FreeCode(const void* code_ptr, ArtMethod* method ATTRIBUTE_UNUSED) {
333 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000334 // Notify native debugger that we are about to remove the code.
335 // It does nothing if we are not using native debugger.
336 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000337 FreeData(GetRootTable(code_ptr));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000338 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100339}
340
341void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800342 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100343 MutexLock mu(self, lock_);
344 // We do not check if a code cache GC is in progress, as this method comes
345 // with the classlinker_classes_lock_ held, and suspending ourselves could
346 // lead to a deadlock.
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000347 {
348 ScopedCodeCacheWrite scc(code_map_.get());
349 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
350 if (alloc.ContainsUnsafe(it->second)) {
351 FreeCode(it->first, it->second);
352 it = method_code_map_.erase(it);
353 } else {
354 ++it;
355 }
356 }
357 }
Nicolas Geoffraya9b91312016-02-17 09:49:19 +0000358 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
359 if (alloc.ContainsUnsafe(it->first)) {
360 // Note that the code has already been removed in the loop above.
361 it = osr_code_map_.erase(it);
362 } else {
363 ++it;
364 }
365 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000366 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
367 ProfilingInfo* info = *it;
368 if (alloc.ContainsUnsafe(info->GetMethod())) {
369 info->GetMethod()->SetProfilingInfo(nullptr);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000370 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000371 it = profiling_infos_.erase(it);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100372 } else {
373 ++it;
374 }
375 }
376}
377
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000378void JitCodeCache::ClearGcRootsInInlineCaches(Thread* self) {
379 MutexLock mu(self, lock_);
380 for (ProfilingInfo* info : profiling_infos_) {
381 if (!info->IsInUseByCompiler()) {
382 info->ClearGcRootsInInlineCaches();
383 }
384 }
385}
386
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100387uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
388 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000389 uint8_t* stack_map,
390 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100391 size_t frame_size_in_bytes,
392 size_t core_spill_mask,
393 size_t fp_spill_mask,
394 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000395 size_t code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000396 bool osr,
397 Handle<mirror::ObjectArray<mirror::Object>> roots) {
398 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100399 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
400 // Ensure the header ends up at expected instruction alignment.
401 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
402 size_t total_size = header_size + code_size;
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800403 const uint32_t num_roots = roots->GetLength();
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100404
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100405 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100406 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000407 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100408 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000409 ScopedThreadSuspension sts(self, kSuspended);
410 MutexLock mu(self, lock_);
411 WaitForPotentialCollectionToComplete(self);
412 {
413 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000414 memory = AllocateCode(total_size);
415 if (memory == nullptr) {
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800416 // Fill root table length so that ClearData works correctly in case of failure. Otherwise
417 // the length will be 0 and cause incorrect DCHECK failure.
418 FillRootTableLength(roots_data, num_roots);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000419 return nullptr;
420 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000421 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000422
423 std::copy(code, code + code_size, code_ptr);
424 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
425 new (method_header) OatQuickMethodHeader(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000426 code_ptr - stack_map,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000427 frame_size_in_bytes,
428 core_spill_mask,
429 fp_spill_mask,
430 code_size);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100431 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100432
Roland Levillain32430262016-02-01 15:23:20 +0000433 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
434 reinterpret_cast<char*>(code_ptr + code_size));
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000435 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100436 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000437 // We need to update the entry point in the runnable state for the instrumentation.
438 {
439 MutexLock mu(self, lock_);
440 method_code_map_.Put(code_ptr, method);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000441 // Fill the root table before updating the entry point.
442 FillRootTable(roots_data, roots);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000443 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000444 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000445 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100446 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000447 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
448 method, method_header->GetEntryPoint());
449 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000450 if (collection_in_progress_) {
451 // We need to update the live bitmap if there is a GC to ensure it sees this new
452 // code.
453 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
454 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000455 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000456 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100457 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700458 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000459 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
460 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
461 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
462 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000463 histogram_code_memory_use_.AddValue(code_size);
464 if (code_size > kCodeSizeLogThreshold) {
465 LOG(INFO) << "JIT allocated "
466 << PrettySize(code_size)
467 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700468 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000469 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000470 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100471
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100472 return reinterpret_cast<uint8_t*>(method_header);
473}
474
475size_t JitCodeCache::CodeCacheSize() {
476 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000477 return CodeCacheSizeLocked();
478}
479
480size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000481 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100482}
483
484size_t JitCodeCache::DataCacheSize() {
485 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000486 return DataCacheSizeLocked();
487}
488
489size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000490 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800491}
492
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000493static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
494 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
495}
496
497void JitCodeCache::ClearData(Thread* self,
498 uint8_t* stack_map_data,
499 uint8_t* roots_data) {
500 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000501 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000502 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000503}
504
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000505void JitCodeCache::ReserveData(Thread* self,
506 size_t stack_map_size,
507 size_t number_of_roots,
508 ArtMethod* method,
509 uint8_t** stack_map_data,
510 uint8_t** roots_data) {
511 size_t table_size = ComputeRootTableSize(number_of_roots);
512 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100513 uint8_t* result = nullptr;
514
515 {
516 ScopedThreadSuspension sts(self, kSuspended);
517 MutexLock mu(self, lock_);
518 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000519 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100520 }
521
522 if (result == nullptr) {
523 // Retry.
524 GarbageCollectCache(self);
525 ScopedThreadSuspension sts(self, kSuspended);
526 MutexLock mu(self, lock_);
527 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000528 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100529 }
530
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000531 MutexLock mu(self, lock_);
532 histogram_stack_map_memory_use_.AddValue(size);
533 if (size > kStackMapSizeLogThreshold) {
534 LOG(INFO) << "JIT allocated "
535 << PrettySize(size)
536 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700537 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800538 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000539 *roots_data = result;
540 *stack_map_data = result + table_size;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800541}
542
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100543class MarkCodeVisitor FINAL : public StackVisitor {
544 public:
545 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
546 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
547 code_cache_(code_cache_in),
548 bitmap_(code_cache_->GetLiveBitmap()) {}
549
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700550 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100551 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
552 if (method_header == nullptr) {
553 return true;
554 }
555 const void* code = method_header->GetCode();
556 if (code_cache_->ContainsPc(code)) {
557 // Use the atomic set version, as multiple threads are executing this code.
558 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
559 }
560 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800561 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100562
563 private:
564 JitCodeCache* const code_cache_;
565 CodeCacheBitmap* const bitmap_;
566};
567
568class MarkCodeClosure FINAL : public Closure {
569 public:
570 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
571 : code_cache_(code_cache), barrier_(barrier) {}
572
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700573 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800574 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100575 DCHECK(thread == Thread::Current() || thread->IsSuspended());
576 MarkCodeVisitor visitor(thread, code_cache_);
577 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000578 if (kIsDebugBuild) {
579 // The stack walking code queries the side instrumentation stack if it
580 // sees an instrumentation exit pc, so the JIT code of methods in that stack
581 // must have been seen. We sanity check this below.
582 for (const instrumentation::InstrumentationStackFrame& frame
583 : *thread->GetInstrumentationStack()) {
584 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
585 // its stack frame, it is not the method owning return_pc_. We just pass null to
586 // LookupMethodHeader: the method is only checked against in debug builds.
587 OatQuickMethodHeader* method_header =
588 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
589 if (method_header != nullptr) {
590 const void* code = method_header->GetCode();
591 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
592 }
593 }
594 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700595 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800596 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100597
598 private:
599 JitCodeCache* const code_cache_;
600 Barrier* const barrier_;
601};
602
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000603void JitCodeCache::NotifyCollectionDone(Thread* self) {
604 collection_in_progress_ = false;
605 lock_cond_.Broadcast(self);
606}
607
608void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
609 size_t per_space_footprint = new_footprint / 2;
610 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
611 DCHECK_EQ(per_space_footprint * 2, new_footprint);
612 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
613 {
614 ScopedCodeCacheWrite scc(code_map_.get());
615 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
616 }
617}
618
619bool JitCodeCache::IncreaseCodeCacheCapacity() {
620 if (current_capacity_ == max_capacity_) {
621 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100622 }
623
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000624 // Double the capacity if we're below 1MB, or increase it by 1MB if
625 // we're above.
626 if (current_capacity_ < 1 * MB) {
627 current_capacity_ *= 2;
628 } else {
629 current_capacity_ += 1 * MB;
630 }
631 if (current_capacity_ > max_capacity_) {
632 current_capacity_ = max_capacity_;
633 }
634
635 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
636 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
637 }
638
639 SetFootprintLimit(current_capacity_);
640
641 return true;
642}
643
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000644void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
645 Barrier barrier(0);
646 size_t threads_running_checkpoint = 0;
647 MarkCodeClosure closure(this, &barrier);
648 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
649 // Now that we have run our checkpoint, move to a suspended state and wait
650 // for other threads to run the checkpoint.
651 ScopedThreadSuspension sts(self, kSuspended);
652 if (threads_running_checkpoint != 0) {
653 barrier.Increment(self, threads_running_checkpoint);
654 }
655}
656
Nicolas Geoffray35122442016-03-02 12:05:30 +0000657bool JitCodeCache::ShouldDoFullCollection() {
658 if (current_capacity_ == max_capacity_) {
659 // Always do a full collection when the code cache is full.
660 return true;
661 } else if (current_capacity_ < kReservedCapacity) {
662 // Always do partial collection when the code cache size is below the reserved
663 // capacity.
664 return false;
665 } else if (last_collection_increased_code_cache_) {
666 // This time do a full collection.
667 return true;
668 } else {
669 // This time do a partial collection.
670 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000671 }
672}
673
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000674void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800675 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000676 if (!garbage_collect_code_) {
677 MutexLock mu(self, lock_);
678 IncreaseCodeCacheCapacity();
679 return;
680 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100681
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000682 // Wait for an existing collection, or let everyone know we are starting one.
683 {
684 ScopedThreadSuspension sts(self, kSuspended);
685 MutexLock mu(self, lock_);
686 if (WaitForPotentialCollectionToComplete(self)) {
687 return;
688 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000689 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000690 live_bitmap_.reset(CodeCacheBitmap::Create(
691 "code-cache-bitmap",
692 reinterpret_cast<uintptr_t>(code_map_->Begin()),
693 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000694 collection_in_progress_ = true;
695 }
696 }
697
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000698 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000699 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000700 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000701
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000702 bool do_full_collection = false;
703 {
704 MutexLock mu(self, lock_);
705 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000706 }
707
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000708 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
709 LOG(INFO) << "Do "
710 << (do_full_collection ? "full" : "partial")
711 << " code cache collection, code="
712 << PrettySize(CodeCacheSize())
713 << ", data=" << PrettySize(DataCacheSize());
714 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000715
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000716 DoCollection(self, /* collect_profiling_info */ do_full_collection);
717
718 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
719 LOG(INFO) << "After code cache collection, code="
720 << PrettySize(CodeCacheSize())
721 << ", data=" << PrettySize(DataCacheSize());
722 }
723
724 {
725 MutexLock mu(self, lock_);
726
727 // Increase the code cache only when we do partial collections.
728 // TODO: base this strategy on how full the code cache is?
729 if (do_full_collection) {
730 last_collection_increased_code_cache_ = false;
731 } else {
732 last_collection_increased_code_cache_ = true;
733 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000734 }
735
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000736 bool next_collection_will_be_full = ShouldDoFullCollection();
737
738 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100739 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000740 // Save the entry point of methods we have compiled, and update the entry
741 // point of those methods to the interpreter. If the method is invoked, the
742 // interpreter will update its entry point to the compiled code and call it.
743 for (ProfilingInfo* info : profiling_infos_) {
744 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
745 if (ContainsPc(entry_point)) {
746 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100747 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
748 info->GetMethod(), GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000749 }
750 }
751
752 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
753 }
754 live_bitmap_.reset(nullptr);
755 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000756 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000757 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000758 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000759}
760
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000761void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800762 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000763 MutexLock mu(self, lock_);
764 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000765 // Iterate over all compiled code and remove entries that are not marked.
Nicolas Geoffray35122442016-03-02 12:05:30 +0000766 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
767 const void* code_ptr = it->first;
768 ArtMethod* method = it->second;
769 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000770 if (GetLiveBitmap()->Test(allocation)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000771 ++it;
772 } else {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000773 FreeCode(code_ptr, method);
774 it = method_code_map_.erase(it);
775 }
776 }
777}
778
779void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800780 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000781 {
782 MutexLock mu(self, lock_);
783 if (collect_profiling_info) {
784 // Clear the profiling info of methods that do not have compiled code as entrypoint.
785 // Also remove the saved entry point from the ProfilingInfo objects.
786 for (ProfilingInfo* info : profiling_infos_) {
787 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000788 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000789 info->GetMethod()->SetProfilingInfo(nullptr);
790 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +0000791
792 if (info->GetSavedEntryPoint() != nullptr) {
793 info->SetSavedEntryPoint(nullptr);
794 // We are going to move this method back to interpreter. Clear the counter now to
795 // give it a chance to be hot again.
796 info->GetMethod()->ClearCounter();
797 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000798 }
799 } else if (kIsDebugBuild) {
800 // Sanity check that the profiling infos do not have a dangling entry point.
801 for (ProfilingInfo* info : profiling_infos_) {
802 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100803 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000804 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000805
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000806 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
807 // an entry point is either:
808 // - an osr compiled code, that will be removed if not in a thread call stack.
809 // - discarded compiled code, that will be removed if not in a thread call stack.
810 for (const auto& it : method_code_map_) {
811 ArtMethod* method = it.second;
812 const void* code_ptr = it.first;
813 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
814 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
815 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
816 }
817 }
818
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000819 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000820 // on thread stacks).
821 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100822 }
823
824 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000825 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100826
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000827 // At this point, mutator threads are still running, and entrypoints of methods can
828 // change. We do know they cannot change to a code cache entry that is not marked,
829 // therefore we can safely remove those entries.
830 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000831
Nicolas Geoffray35122442016-03-02 12:05:30 +0000832 if (collect_profiling_info) {
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +0100833 ScopedThreadSuspension sts(self, kSuspended);
834 gc::ScopedGCCriticalSection gcs(
835 self, gc::kGcCauseJitCodeCache, gc::kCollectorTypeJitCodeCache);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000836 MutexLock mu(self, lock_);
837 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100838 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000839 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000840 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000841 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
842 // that the compiled code would not get revived. As mutator threads run concurrently,
843 // they may have revived the compiled code, and now we are in the situation where
844 // a method has compiled code but no ProfilingInfo.
845 // We make sure compiled methods have a ProfilingInfo object. It is needed for
846 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -0700847 if (ContainsPc(ptr) &&
848 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000849 // We clear the inline caches as classes in it might be stalled.
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000850 info->ClearGcRootsInInlineCaches();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000851 // Do a fence to make sure the clearing is seen before attaching to the method.
852 QuasiAtomic::ThreadFenceRelease();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000853 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -0700854 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000855 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000856 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100857 return true;
858 }
859 return false;
860 });
861 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +0000862 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100863 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800864}
865
Nicolas Geoffray35122442016-03-02 12:05:30 +0000866bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800867 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000868 // Check that methods we have compiled do have a ProfilingInfo object. We would
869 // have memory leaks of compiled code otherwise.
870 for (const auto& it : method_code_map_) {
871 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -0700872 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000873 const void* code_ptr = it.first;
874 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
875 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
876 // If the code is not dead, then we have a problem. Note that this can even
877 // happen just after a collection, as mutator threads are running in parallel
878 // and could deoptimize an existing compiled code.
879 return false;
880 }
881 }
882 }
883 return true;
884}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100885
886OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
887 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
888 if (kRuntimeISA == kArm) {
889 // On Thumb-2, the pc is offset by one.
890 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800891 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100892 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
893 return nullptr;
894 }
895
896 MutexLock mu(Thread::Current(), lock_);
897 if (method_code_map_.empty()) {
898 return nullptr;
899 }
900 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
901 --it;
902
903 const void* code_ptr = it->first;
904 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
905 if (!method_header->Contains(pc)) {
906 return nullptr;
907 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000908 if (kIsDebugBuild && method != nullptr) {
909 DCHECK_EQ(it->second, method)
David Sehr709b0702016-10-13 09:12:37 -0700910 << ArtMethod::PrettyMethod(method) << " " << ArtMethod::PrettyMethod(it->second) << " "
911 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000912 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100913 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800914}
915
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000916OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
917 MutexLock mu(Thread::Current(), lock_);
918 auto it = osr_code_map_.find(method);
919 if (it == osr_code_map_.end()) {
920 return nullptr;
921 }
922 return OatQuickMethodHeader::FromCodePointer(it->second);
923}
924
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000925ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
926 ArtMethod* method,
927 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000928 bool retry_allocation)
929 // No thread safety analysis as we are using TryLock/Unlock explicitly.
930 NO_THREAD_SAFETY_ANALYSIS {
931 ProfilingInfo* info = nullptr;
932 if (!retry_allocation) {
933 // If we are allocating for the interpreter, just try to lock, to avoid
934 // lock contention with the JIT.
935 if (lock_.ExclusiveTryLock(self)) {
936 info = AddProfilingInfoInternal(self, method, entries);
937 lock_.ExclusiveUnlock(self);
938 }
939 } else {
940 {
941 MutexLock mu(self, lock_);
942 info = AddProfilingInfoInternal(self, method, entries);
943 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000944
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000945 if (info == nullptr) {
946 GarbageCollectCache(self);
947 MutexLock mu(self, lock_);
948 info = AddProfilingInfoInternal(self, method, entries);
949 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000950 }
951 return info;
952}
953
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000954ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000955 ArtMethod* method,
956 const std::vector<uint32_t>& entries) {
957 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100958 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000959 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000960
961 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -0700962 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000963 if (info != nullptr) {
964 return info;
965 }
966
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000967 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000968 if (data == nullptr) {
969 return nullptr;
970 }
971 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +0000972
973 // Make sure other threads see the data in the profiling info object before the
974 // store in the ArtMethod's ProfilingInfo pointer.
975 QuasiAtomic::ThreadFenceRelease();
976
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000977 method->SetProfilingInfo(info);
978 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000979 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000980 return info;
981}
982
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000983// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
984// is already held.
985void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
986 if (code_mspace_ == mspace) {
987 size_t result = code_end_;
988 code_end_ += increment;
989 return reinterpret_cast<void*>(result + code_map_->Begin());
990 } else {
991 DCHECK_EQ(data_mspace_, mspace);
992 size_t result = data_end_;
993 data_end_ += increment;
994 return reinterpret_cast<void*>(result + data_map_->Begin());
995 }
996}
997
Calin Juravle99629622016-04-19 16:33:46 +0100998void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
999 std::vector<MethodReference>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001000 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001001 MutexLock mu(Thread::Current(), lock_);
Calin Juravle99629622016-04-19 16:33:46 +01001002 for (const ProfilingInfo* info : profiling_infos_) {
1003 ArtMethod* method = info->GetMethod();
1004 const DexFile* dex_file = method->GetDexFile();
1005 if (ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
1006 methods.emplace_back(dex_file, method->GetDexMethodIndex());
Calin Juravle31f2c152015-10-23 17:56:15 +01001007 }
1008 }
1009}
1010
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001011uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1012 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001013}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001014
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001015bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1016 MutexLock mu(Thread::Current(), lock_);
1017 return osr_code_map_.find(method) != osr_code_map_.end();
1018}
1019
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001020bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1021 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001022 return false;
1023 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001024
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001025 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001026 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1027 return false;
1028 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001029
Andreas Gampe542451c2016-07-26 09:02:02 -07001030 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001031 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001032 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001033 // Because the counter is not atomic, there are some rare cases where we may not
1034 // hit the threshold for creating the ProfilingInfo. Reset the counter now to
1035 // "correct" this.
1036 method->ClearCounter();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001037 return false;
1038 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001039
buzbee454b3b62016-04-07 14:42:47 -07001040 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001041 return false;
1042 }
1043
buzbee454b3b62016-04-07 14:42:47 -07001044 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001045 return true;
1046}
1047
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001048ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001049 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001050 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001051 if (info != nullptr) {
1052 info->IncrementInlineUse();
1053 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001054 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001055}
1056
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001057void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001058 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001059 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001060 DCHECK(info != nullptr);
1061 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001062}
1063
buzbee454b3b62016-04-07 14:42:47 -07001064void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001065 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001066 DCHECK(info->IsMethodBeingCompiled(osr));
1067 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001068}
1069
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001070size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1071 MutexLock mu(Thread::Current(), lock_);
1072 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1073}
1074
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001075void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1076 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001077 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001078 if ((profiling_info != nullptr) &&
1079 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1080 // Prevent future uses of the compiled code.
1081 profiling_info->SetSavedEntryPoint(nullptr);
1082 }
1083
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001084 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
1085 // The entrypoint is the one to invalidate, so we just update
1086 // it to the interpreter entry point and clear the counter to get the method
1087 // Jitted again.
1088 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1089 method, GetQuickToInterpreterBridge());
1090 method->ClearCounter();
1091 } else {
1092 MutexLock mu(Thread::Current(), lock_);
1093 auto it = osr_code_map_.find(method);
1094 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1095 // Remove the OSR method, to avoid using it again.
1096 osr_code_map_.erase(it);
1097 }
1098 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001099 MutexLock mu(Thread::Current(), lock_);
1100 number_of_deoptimizations_++;
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001101}
1102
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001103uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1104 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1105 uint8_t* result = reinterpret_cast<uint8_t*>(
1106 mspace_memalign(code_mspace_, alignment, code_size));
1107 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1108 // Ensure the header ends up at expected instruction alignment.
1109 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1110 used_memory_for_code_ += mspace_usable_size(result);
1111 return result;
1112}
1113
1114void JitCodeCache::FreeCode(uint8_t* code) {
1115 used_memory_for_code_ -= mspace_usable_size(code);
1116 mspace_free(code_mspace_, code);
1117}
1118
1119uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1120 void* result = mspace_malloc(data_mspace_, data_size);
1121 used_memory_for_data_ += mspace_usable_size(result);
1122 return reinterpret_cast<uint8_t*>(result);
1123}
1124
1125void JitCodeCache::FreeData(uint8_t* data) {
1126 used_memory_for_data_ -= mspace_usable_size(data);
1127 mspace_free(data_mspace_, data);
1128}
1129
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001130void JitCodeCache::Dump(std::ostream& os) {
1131 MutexLock mu(Thread::Current(), lock_);
1132 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1133 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1134 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1135 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1136 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1137 << "Total number of JIT compilations for on stack replacement: "
1138 << number_of_osr_compilations_ << "\n"
1139 << "Total number of deoptimizations: " << number_of_deoptimizations_ << "\n"
1140 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001141 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1142 histogram_code_memory_use_.PrintMemoryUse(os);
1143 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001144}
1145
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001146} // namespace jit
1147} // namespace art