blob: 1244bd79974545fdfefcae8046f6d069b9a6b111 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 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 "compiler_driver.h"
18
Andreas Gampeb0f370e2014-09-25 22:51:40 -070019#include <unordered_set>
Anwar Ghuloum67f99412013-08-12 14:19:48 -070020#include <vector>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021#include <unistd.h>
22
Mathieu Chartierab972ef2014-12-03 17:38:22 -080023#ifndef __APPLE__
24#include <malloc.h> // For mallinfo
25#endif
26
Mathieu Chartierc7853442015-03-27 14:35:38 -070027#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070028#include "art_method-inl.h"
David Brazdild9c90372016-09-14 16:53:55 +010029#include "base/array_ref.h"
Vladimir Marko492a7fa2016-06-01 18:38:43 +010030#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070031#include "base/enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080033#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010034#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070035#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010036#include "class_linker-inl.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070037#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000038#include "compiled_method.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000039#include "compiler.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000040#include "compiler_driver-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "dex_compilation_unit.h"
42#include "dex_file-inl.h"
Andreas Gampeace0dc12016-01-20 13:33:13 -080043#include "dex_instruction-inl.h"
Andreas Gampe5eb0d382015-07-23 01:19:26 -070044#include "dex/dex_to_dex_compiler.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000045#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000046#include "dex/verified_method.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000047#include "dex/quick/dex_file_method_inliner.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080048#include "dex/quick/dex_file_to_method_inliner_map.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080049#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "jni_internal.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070051#include "object_lock.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070052#include "runtime.h"
53#include "gc/accounting/card_table-inl.h"
54#include "gc/accounting/heap_bitmap.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070055#include "gc/space/image_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "gc/space/space.h"
57#include "mirror/class_loader.h"
58#include "mirror/class-inl.h"
59#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "mirror/object-inl.h"
61#include "mirror/object_array-inl.h"
62#include "mirror/throwable.h"
63#include "scoped_thread_state_change.h"
64#include "ScopedLocalRef.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070065#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "thread.h"
Andreas Gampeb0f370e2014-09-25 22:51:40 -070067#include "thread_list.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070069#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010070#include "transaction.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000071#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampee21dc3d2014-12-08 16:59:43 -080072#include "utils/swap_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "verifier/method_verifier.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000074#include "verifier/method_verifier-inl.h"
Andreas Gampe5fd66d02016-09-12 20:22:19 -070075#include "verifier/verifier_log_mode.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070076
Brian Carlstrom7940e442013-07-12 13:46:57 -070077namespace art {
78
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070079static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
80
Calin Juravle226501b2015-12-11 14:41:31 +000081// Print additional info during profile guided compilation.
82static constexpr bool kDebugProfileGuidedCompilation = false;
83
Brian Carlstrom7940e442013-07-12 13:46:57 -070084static double Percentage(size_t x, size_t y) {
85 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
86}
87
88static void DumpStat(size_t x, size_t y, const char* str) {
89 if (x == 0 && y == 0) {
90 return;
91 }
Ian Rogerse732ef12013-10-09 15:22:24 -070092 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -070093}
94
Vladimir Markof096aad2014-01-23 15:51:58 +000095class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -070096 public:
97 AOTCompilationStats()
98 : stats_lock_("AOT compilation statistics lock"),
99 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
100 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
101 resolved_types_(0), unresolved_types_(0),
102 resolved_instance_fields_(0), unresolved_instance_fields_(0),
103 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
104 type_based_devirtualization_(0),
105 safe_casts_(0), not_safe_casts_(0) {
106 for (size_t i = 0; i <= kMaxInvokeType; i++) {
107 resolved_methods_[i] = 0;
108 unresolved_methods_[i] = 0;
109 virtual_made_direct_[i] = 0;
110 direct_calls_to_boot_[i] = 0;
111 direct_methods_to_boot_[i] = 0;
112 }
113 }
114
115 void Dump() {
116 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
117 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
118 DumpStat(resolved_types_, unresolved_types_, "types resolved");
119 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
120 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
121 "static fields resolved");
122 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
123 "static fields local to a class");
124 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
125 // Note, the code below subtracts the stat value so that when added to the stat value we have
126 // 100% of samples. TODO: clean this up.
127 DumpStat(type_based_devirtualization_,
128 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
129 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
130 type_based_devirtualization_,
131 "virtual/interface calls made direct based on type information");
132
133 for (size_t i = 0; i <= kMaxInvokeType; i++) {
134 std::ostringstream oss;
135 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
136 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
137 if (virtual_made_direct_[i] > 0) {
138 std::ostringstream oss2;
139 oss2 << static_cast<InvokeType>(i) << " methods made direct";
140 DumpStat(virtual_made_direct_[i],
141 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
142 oss2.str().c_str());
143 }
144 if (direct_calls_to_boot_[i] > 0) {
145 std::ostringstream oss2;
146 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
147 DumpStat(direct_calls_to_boot_[i],
148 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
149 oss2.str().c_str());
150 }
151 if (direct_methods_to_boot_[i] > 0) {
152 std::ostringstream oss2;
153 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
154 DumpStat(direct_methods_to_boot_[i],
155 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
156 oss2.str().c_str());
157 }
158 }
159 }
160
161// Allow lossy statistics in non-debug builds.
162#ifndef NDEBUG
163#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
164#else
165#define STATS_LOCK()
166#endif
167
Mathieu Chartier90443472015-07-16 20:32:27 -0700168 void TypeInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700169 STATS_LOCK();
170 types_in_dex_cache_++;
171 }
172
Mathieu Chartier90443472015-07-16 20:32:27 -0700173 void TypeNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700174 STATS_LOCK();
175 types_not_in_dex_cache_++;
176 }
177
Mathieu Chartier90443472015-07-16 20:32:27 -0700178 void StringInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 STATS_LOCK();
180 strings_in_dex_cache_++;
181 }
182
Mathieu Chartier90443472015-07-16 20:32:27 -0700183 void StringNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700184 STATS_LOCK();
185 strings_not_in_dex_cache_++;
186 }
187
Mathieu Chartier90443472015-07-16 20:32:27 -0700188 void TypeDoesntNeedAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700189 STATS_LOCK();
190 resolved_types_++;
191 }
192
Mathieu Chartier90443472015-07-16 20:32:27 -0700193 void TypeNeedsAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700194 STATS_LOCK();
195 unresolved_types_++;
196 }
197
Mathieu Chartier90443472015-07-16 20:32:27 -0700198 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700199 STATS_LOCK();
200 resolved_instance_fields_++;
201 }
202
Mathieu Chartier90443472015-07-16 20:32:27 -0700203 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700204 STATS_LOCK();
205 unresolved_instance_fields_++;
206 }
207
Mathieu Chartier90443472015-07-16 20:32:27 -0700208 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700209 STATS_LOCK();
210 resolved_local_static_fields_++;
211 }
212
Mathieu Chartier90443472015-07-16 20:32:27 -0700213 void ResolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700214 STATS_LOCK();
215 resolved_static_fields_++;
216 }
217
Mathieu Chartier90443472015-07-16 20:32:27 -0700218 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700219 STATS_LOCK();
220 unresolved_static_fields_++;
221 }
222
223 // Indicate that type information from the verifier led to devirtualization.
Mathieu Chartier90443472015-07-16 20:32:27 -0700224 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700225 STATS_LOCK();
226 type_based_devirtualization_++;
227 }
228
229 // Indicate that a method of the given type was resolved at compile time.
Mathieu Chartier90443472015-07-16 20:32:27 -0700230 void ResolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700231 DCHECK_LE(type, kMaxInvokeType);
232 STATS_LOCK();
233 resolved_methods_[type]++;
234 }
235
236 // Indicate that a method of the given type was unresolved at compile time as it was in an
237 // unknown dex file.
Mathieu Chartier90443472015-07-16 20:32:27 -0700238 void UnresolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700239 DCHECK_LE(type, kMaxInvokeType);
240 STATS_LOCK();
241 unresolved_methods_[type]++;
242 }
243
244 // Indicate that a type of virtual method dispatch has been converted into a direct method
245 // dispatch.
Mathieu Chartier90443472015-07-16 20:32:27 -0700246 void VirtualMadeDirect(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700247 DCHECK(type == kVirtual || type == kInterface || type == kSuper);
248 STATS_LOCK();
249 virtual_made_direct_[type]++;
250 }
251
252 // Indicate that a method of the given type was able to call directly into boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700253 void DirectCallsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700254 DCHECK_LE(type, kMaxInvokeType);
255 STATS_LOCK();
256 direct_calls_to_boot_[type]++;
257 }
258
259 // Indicate that a method of the given type was able to be resolved directly from boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700260 void DirectMethodsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700261 DCHECK_LE(type, kMaxInvokeType);
262 STATS_LOCK();
263 direct_methods_to_boot_[type]++;
264 }
265
Mathieu Chartier90443472015-07-16 20:32:27 -0700266 void ProcessedInvoke(InvokeType type, int flags) REQUIRES(!stats_lock_) {
Vladimir Markof096aad2014-01-23 15:51:58 +0000267 STATS_LOCK();
268 if (flags == 0) {
269 unresolved_methods_[type]++;
270 } else {
271 DCHECK_NE((flags & kFlagMethodResolved), 0);
272 resolved_methods_[type]++;
273 if ((flags & kFlagVirtualMadeDirect) != 0) {
274 virtual_made_direct_[type]++;
275 if ((flags & kFlagPreciseTypeDevirtualization) != 0) {
276 type_based_devirtualization_++;
277 }
278 } else {
279 DCHECK_EQ((flags & kFlagPreciseTypeDevirtualization), 0);
280 }
281 if ((flags & kFlagDirectCallToBoot) != 0) {
282 direct_calls_to_boot_[type]++;
283 }
284 if ((flags & kFlagDirectMethodToBoot) != 0) {
285 direct_methods_to_boot_[type]++;
286 }
287 }
288 }
289
Brian Carlstrom7940e442013-07-12 13:46:57 -0700290 // A check-cast could be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700291 void SafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700292 STATS_LOCK();
293 safe_casts_++;
294 }
295
296 // A check-cast couldn't be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700297 void NotASafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700298 STATS_LOCK();
299 not_safe_casts_++;
300 }
301
302 private:
303 Mutex stats_lock_;
304
305 size_t types_in_dex_cache_;
306 size_t types_not_in_dex_cache_;
307
308 size_t strings_in_dex_cache_;
309 size_t strings_not_in_dex_cache_;
310
311 size_t resolved_types_;
312 size_t unresolved_types_;
313
314 size_t resolved_instance_fields_;
315 size_t unresolved_instance_fields_;
316
317 size_t resolved_local_static_fields_;
318 size_t resolved_static_fields_;
319 size_t unresolved_static_fields_;
320 // Type based devirtualization for invoke interface and virtual.
321 size_t type_based_devirtualization_;
322
323 size_t resolved_methods_[kMaxInvokeType + 1];
324 size_t unresolved_methods_[kMaxInvokeType + 1];
325 size_t virtual_made_direct_[kMaxInvokeType + 1];
326 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
327 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
328
329 size_t safe_casts_;
330 size_t not_safe_casts_;
331
332 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
333};
334
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100335class CompilerDriver::DexFileMethodSet {
336 public:
337 explicit DexFileMethodSet(const DexFile& dex_file)
338 : dex_file_(dex_file),
339 method_indexes_(dex_file.NumMethodIds(), false, Allocator::GetMallocAllocator()) {
340 }
341 DexFileMethodSet(DexFileMethodSet&& other) = default;
342
343 const DexFile& GetDexFile() const { return dex_file_; }
344
345 BitVector& GetMethodIndexes() { return method_indexes_; }
346 const BitVector& GetMethodIndexes() const { return method_indexes_; }
347
348 private:
349 const DexFile& dex_file_;
350 BitVector method_indexes_;
351};
352
Jeff Haodcdc85b2015-12-04 14:06:18 -0800353CompilerDriver::CompilerDriver(
354 const CompilerOptions* compiler_options,
355 VerificationResults* verification_results,
356 DexFileToMethodInlinerMap* method_inliner_map,
357 Compiler::Kind compiler_kind,
358 InstructionSet instruction_set,
359 const InstructionSetFeatures* instruction_set_features,
Vladimir Marko944da602016-02-19 12:27:55 +0000360 std::unordered_set<std::string>* image_classes,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800361 std::unordered_set<std::string>* compiled_classes,
362 std::unordered_set<std::string>* compiled_methods,
Vladimir Marko944da602016-02-19 12:27:55 +0000363 size_t thread_count,
364 bool dump_stats,
365 bool dump_passes,
366 CumulativeLogger* timer,
367 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200368 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000369 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800370 verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000371 method_inliner_map_(method_inliner_map),
Ian Rogers72d32622014-05-06 16:20:11 -0700372 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700373 compiler_kind_(compiler_kind),
Artem Serovba6b6792016-08-15 14:22:07 +0100374 instruction_set_(instruction_set == kArm ? kThumb2: instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700375 instruction_set_features_(instruction_set_features),
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700376 requires_constructor_barrier_lock_("constructor barrier lock"),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700377 compiled_classes_lock_("compiled classes lock"),
378 compiled_methods_lock_("compiled method lock"),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800379 compiled_methods_(MethodTable::key_compare()),
Vladimir Markof4da6752014-08-01 19:04:18 +0100380 non_relative_linker_patch_count_(0u),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700381 image_classes_(image_classes),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800382 classes_to_compile_(compiled_classes),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700383 methods_to_compile_(compiled_methods),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800384 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800385 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700386 stats_(new AOTCompilationStats),
387 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000388 dump_passes_(dump_passes),
389 timings_logger_(timer),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700390 compiler_context_(nullptr),
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700391 support_boot_image_fixup_(instruction_set != kMips64),
Vladimir Markod1eaf0d2015-10-29 12:18:29 +0000392 dex_files_for_oat_file_(nullptr),
Calin Juravle998c2162015-12-21 15:39:33 +0200393 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000394 profile_compilation_info_(profile_compilation_info),
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100395 max_arena_alloc_(0),
396 dex_to_dex_references_lock_("dex-to-dex references lock"),
397 dex_to_dex_references_(),
398 current_dex_to_dex_methods_(nullptr) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800399 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom6449c622014-02-10 23:48:36 -0800400 DCHECK(method_inliner_map_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700401
Ian Rogers72d32622014-05-06 16:20:11 -0700402 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700403
Mathieu Chartiera8077802016-03-16 19:08:31 -0700404 if (compiler_options->VerifyOnlyProfile()) {
405 CHECK(profile_compilation_info_ != nullptr) << "Requires profile";
406 }
Vladimir Marko63dccbbe2016-09-21 13:51:10 +0100407 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800408 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image";
409 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700410}
411
412CompilerDriver::~CompilerDriver() {
413 Thread* self = Thread::Current();
414 {
415 MutexLock mu(self, compiled_classes_lock_);
416 STLDeleteValues(&compiled_classes_);
417 }
418 {
419 MutexLock mu(self, compiled_methods_lock_);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800420 for (auto& pair : compiled_methods_) {
421 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, pair.second);
422 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700423 }
Ian Rogers72d32622014-05-06 16:20:11 -0700424 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700425}
426
Vladimir Marko35831e82015-09-11 11:59:18 +0100427
Ian Rogersdd7624d2014-03-14 17:43:00 -0700428#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700429 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700430 return CreateTrampoline64(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700431 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700432 } else { \
433 return CreateTrampoline32(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700434 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700435 }
436
Vladimir Marko93205e32016-04-13 11:59:46 +0100437std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700438 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700439}
440
Vladimir Marko93205e32016-04-13 11:59:46 +0100441std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
442 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700443 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800444}
445
Vladimir Marko93205e32016-04-13 11:59:46 +0100446std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
447 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700448 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700449}
450
Vladimir Marko93205e32016-04-13 11:59:46 +0100451std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
452 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700453 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700454}
455
Vladimir Marko93205e32016-04-13 11:59:46 +0100456std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
457 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700458 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700459}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700460#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700461
462void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700463 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800464 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700465 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800466
467 InitializeThreadPools();
468
Andreas Gampe8d295f82015-01-20 14:50:21 -0800469 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
Andreas Gampe740667a2015-09-15 17:55:06 -0700470 // Precompile:
471 // 1) Load image classes
472 // 2) Resolve all classes
473 // 3) Attempt to verify all classes
474 // 4) Attempt to initialize image classes, and trivially initialized classes
Andreas Gampeace0dc12016-01-20 13:33:13 -0800475 PreCompile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700476 // Compile:
477 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
478 // compilation.
479 if (!GetCompilerOptions().VerifyAtRuntime()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800480 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700481 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700482 if (dump_stats_) {
483 stats_->Dump();
484 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800485
486 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700487}
488
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700489static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
490 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
491 const DexFile& dex_file, const DexFile::ClassDef& class_def)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700492 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800493 auto* const runtime = Runtime::Current();
Calin Juravleffc87072016-04-20 14:22:09 +0100494 if (runtime->UseJitCompilation() || driver.GetCompilerOptions().VerifyAtRuntime()) {
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700495 // Verify at runtime shouldn't dex to dex since we didn't resolve of verify.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700496 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800497 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700498 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800499 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800500 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700501 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700502 CHECK(self->IsExceptionPending());
503 self->ClearException();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700504 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700505 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700506 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
507 // references with actual offsets. We cannot re-verify such instructions.
508 //
509 // We store the verification information in the class status in the oat file, which the linker
510 // can validate (checksums) and use to skip load-time verification. It is thus safe to
511 // optimize when a class has been fully verified before.
512 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200513 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700514 return optimizer::DexToDexCompilationLevel::kOptimize;
Sebastien Hertz75021222013-07-16 18:34:50 +0200515 } else if (klass->IsCompileTimeVerified()) {
516 // Class verification has soft-failed. Anyway, ensure at least correctness.
517 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700518 return optimizer::DexToDexCompilationLevel::kRequired;
Sebastien Hertz75021222013-07-16 18:34:50 +0200519 } else {
520 // Class verification has failed: do not run DEX-to-DEX compilation.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700521 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
522 }
523}
524
525static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
526 Thread* self,
527 const CompilerDriver& driver,
528 jobject jclass_loader,
529 const DexFile& dex_file,
530 const DexFile::ClassDef& class_def) {
531 ScopedObjectAccess soa(self);
532 StackHandleScope<1> hs(soa.Self());
533 Handle<mirror::ClassLoader> class_loader(
534 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
535 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
536}
537
538// Does the runtime for the InstructionSet provide an implementation returned by
539// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
540static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
541 switch (isa) {
542 case kArm:
543 case kArm64:
544 case kThumb2:
545 case kMips:
546 case kMips64:
547 case kX86:
548 case kX86_64: return true;
549 default: return false;
550 }
551}
552
553static void CompileMethod(Thread* self,
554 CompilerDriver* driver,
555 const DexFile::CodeItem* code_item,
556 uint32_t access_flags,
557 InvokeType invoke_type,
558 uint16_t class_def_idx,
559 uint32_t method_idx,
560 jobject class_loader,
561 const DexFile& dex_file,
562 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700563 bool compilation_enabled,
564 Handle<mirror::DexCache> dex_cache)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700565 REQUIRES(!driver->compiled_methods_lock_) {
566 DCHECK(driver != nullptr);
567 CompiledMethod* compiled_method = nullptr;
568 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
569 MethodReference method_ref(&dex_file, method_idx);
570
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100571 if (driver->GetCurrentDexToDexMethods() != nullptr) {
572 // This is the second pass when we dex-to-dex compile previously marked methods.
573 // TODO: Refactor the compilation to avoid having to distinguish the two passes
574 // here. That should be done on a higher level. http://b/29089975
575 if (driver->GetCurrentDexToDexMethods()->IsBitSet(method_idx)) {
576 const VerifiedMethod* verified_method =
577 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
578 // Do not optimize if a VerifiedMethod is missing. SafeCast elision,
579 // for example, relies on it.
580 compiled_method = optimizer::ArtCompileDEX(
581 driver,
582 code_item,
583 access_flags,
584 invoke_type,
585 class_def_idx,
586 method_idx,
587 class_loader,
588 dex_file,
589 (verified_method != nullptr)
590 ? dex_to_dex_compilation_level
591 : optimizer::DexToDexCompilationLevel::kRequired);
592 }
593 } else if ((access_flags & kAccNative) != 0) {
Igor Murashkin9aa9fa22016-09-26 10:10:17 -0700594 const InstructionSet instruction_set = driver->GetInstructionSet();
595 const bool use_generic_jni =
596 // Are we extracting only and have support for generic JNI down calls?
597 (!driver->GetCompilerOptions().IsJniCompilationEnabled() &&
598 InstructionSetHasGenericJniStub(instruction_set)) ||
599 // Always punt to generic JNI for MIPS because of no support for @CriticalNative. b/31743474
600 (instruction_set == kMips || instruction_set == kMips64);
601 if (use_generic_jni) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700602 // Leaving this empty will trigger the generic JNI version
603 } else {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700604 // Look-up the ArtMethod associated with this code_item (if any)
605 // -- It is later used to lookup any [optimization] annotations for this method.
606 ScopedObjectAccess soa(self);
607 StackHandleScope<1> hs(soa.Self());
608 Handle<mirror::ClassLoader> class_loader_handle(hs.NewHandle(
609 soa.Decode<mirror::ClassLoader*>(class_loader)));
610
611 // TODO: Lookup annotation from DexFile directly without resolving method.
612 ArtMethod* method =
613 Runtime::Current()->GetClassLinker()->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
614 dex_file,
615 method_idx,
616 dex_cache,
617 class_loader_handle,
618 /* referrer */ nullptr,
619 invoke_type);
620
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700621 // Query any JNI optimization annotations such as @FastNative or @CriticalNative.
622 Compiler::JniOptimizationFlags optimization_flags = Compiler::kNone;
623 if (UNLIKELY(method == nullptr)) {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700624 // Failed method resolutions happen very rarely, e.g. ancestor class cannot be resolved.
625 DCHECK(self->IsExceptionPending());
626 self->ClearException();
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700627 } else if (method->IsAnnotatedWithFastNative()) {
628 // TODO: Will no longer need this CHECK once we have verifier checking this.
629 CHECK(!method->IsAnnotatedWithCriticalNative());
630 optimization_flags = Compiler::kFastNative;
631 } else if (method->IsAnnotatedWithCriticalNative()) {
632 // TODO: Will no longer need this CHECK once we have verifier checking this.
633 CHECK(!method->IsAnnotatedWithFastNative());
634 optimization_flags = Compiler::kCriticalNative;
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700635 }
636
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700637 compiled_method = driver->GetCompiler()->JniCompile(access_flags,
638 method_idx,
639 dex_file,
640 optimization_flags);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700641 CHECK(compiled_method != nullptr);
642 }
643 } else if ((access_flags & kAccAbstract) != 0) {
644 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000645 } else {
Andreas Gampe0760a812015-08-26 17:12:51 -0700646 const VerifiedMethod* verified_method =
647 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700648 bool compile = compilation_enabled &&
649 // Basic checks, e.g., not <clinit>.
650 driver->GetVerificationResults()
651 ->IsCandidateForCompilation(method_ref, access_flags) &&
652 // Did not fail to create VerifiedMethod metadata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700653 verified_method != nullptr &&
654 // Do not have failures that should punt to the interpreter.
655 !verified_method->HasRuntimeThrow() &&
656 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700657 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700658 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000659 driver->IsMethodToCompile(method_ref) &&
660 driver->ShouldCompileBasedOnProfile(method_ref);
661
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700662 if (compile) {
663 // NOTE: if compiler declines to compile this method, it will return null.
664 compiled_method = driver->GetCompiler()->Compile(code_item, access_flags, invoke_type,
665 class_def_idx, method_idx, class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700666 dex_file, dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700667 }
668 if (compiled_method == nullptr &&
669 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100670 DCHECK(!Runtime::Current()->UseJitCompilation());
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700671 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100672 driver->MarkForDexToDexCompilation(self, method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700673 }
674 }
675 if (kTimeCompileMethod) {
676 uint64_t duration_ns = NanoTime() - start_ns;
677 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
678 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
679 << " took " << PrettyDuration(duration_ns);
680 }
681 }
682
683 if (compiled_method != nullptr) {
684 // Count non-relative linker patches.
685 size_t non_relative_linker_patch_count = 0u;
686 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
687 if (!patch.IsPcRelative()) {
688 ++non_relative_linker_patch_count;
689 }
690 }
691 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
692 // When compiling with PIC, there should be zero non-relative linker patches
693 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
694
695 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
696 }
697
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700698 if (self->IsExceptionPending()) {
699 ScopedObjectAccess soa(self);
700 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
701 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200702 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700703}
704
Mathieu Chartiere401d142015-04-22 13:56:20 -0700705void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700706 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700707 jobject jclass_loader;
708 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700709 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800710 uint32_t method_idx = method->GetDexMethodIndex();
711 uint32_t access_flags = method->GetAccessFlags();
712 InvokeType invoke_type = method->GetInvokeType();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700713 StackHandleScope<1> hs(self);
714 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700715 {
716 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800717 ScopedLocalRef<jobject> local_class_loader(
718 soa.Env(), soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700719 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
720 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700721 dex_file = method->GetDexFile();
722 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700723 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800724 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700725
726 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700727 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700728
729 std::vector<const DexFile*> dex_files;
730 dex_files.push_back(dex_file);
731
Andreas Gampeace0dc12016-01-20 13:33:13 -0800732 InitializeThreadPools();
733
734 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700735
Brian Carlstrom7940e442013-07-12 13:46:57 -0700736 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700737 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
738 GetDexToDexCompilationLevel(self,
739 *this,
740 jclass_loader,
741 *dex_file,
742 dex_file->GetClassDef(class_def_idx));
743
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100744 DCHECK(current_dex_to_dex_methods_ == nullptr);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700745 CompileMethod(self,
746 this,
747 code_item,
748 access_flags,
749 invoke_type,
750 class_def_idx,
751 method_idx,
752 jclass_loader,
753 *dex_file,
754 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700755 true,
756 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700757
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100758 ArrayRef<DexFileMethodSet> dex_to_dex_references;
759 {
760 // From this point on, we shall not modify dex_to_dex_references_, so
761 // just grab a reference to it that we use without holding the mutex.
762 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
763 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
764 }
765 if (!dex_to_dex_references.empty()) {
766 DCHECK_EQ(dex_to_dex_references.size(), 1u);
767 DCHECK(&dex_to_dex_references[0].GetDexFile() == dex_file);
768 current_dex_to_dex_methods_ = &dex_to_dex_references.front().GetMethodIndexes();
769 DCHECK(current_dex_to_dex_methods_->IsBitSet(method_idx));
770 DCHECK_EQ(current_dex_to_dex_methods_->NumSetBits(), 1u);
771 CompileMethod(self,
772 this,
773 code_item,
774 access_flags,
775 invoke_type,
776 class_def_idx,
777 method_idx,
778 jclass_loader,
779 *dex_file,
780 dex_to_dex_compilation_level,
781 true,
782 dex_cache);
783 current_dex_to_dex_methods_ = nullptr;
784 }
785
Andreas Gampeace0dc12016-01-20 13:33:13 -0800786 FreeThreadPools();
787
Brian Carlstrom7940e442013-07-12 13:46:57 -0700788 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800789}
790
Andreas Gampeace0dc12016-01-20 13:33:13 -0800791void CompilerDriver::Resolve(jobject class_loader,
792 const std::vector<const DexFile*>& dex_files,
793 TimingLogger* timings) {
794 // Resolution allocates classes and needs to run single-threaded to be deterministic.
795 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
796 ThreadPool* resolve_thread_pool = force_determinism
797 ? single_thread_pool_.get()
798 : parallel_thread_pool_.get();
799 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
800
Brian Carlstrom7940e442013-07-12 13:46:57 -0700801 for (size_t i = 0; i != dex_files.size(); ++i) {
802 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700803 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800804 ResolveDexFile(class_loader,
805 *dex_file,
806 dex_files,
807 resolve_thread_pool,
808 resolve_thread_count,
809 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700810 }
811}
812
Andreas Gampeace0dc12016-01-20 13:33:13 -0800813// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
814// this is single-threaded for simplicity.
815// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
816// stable order.
817
818static void ResolveConstStrings(CompilerDriver* driver,
819 const DexFile& dex_file,
820 const DexFile::CodeItem* code_item) {
821 if (code_item == nullptr) {
822 // Abstract or native method.
823 return;
824 }
825
826 const uint16_t* code_ptr = code_item->insns_;
827 const uint16_t* code_end = code_item->insns_ + code_item->insns_size_in_code_units_;
828
829 while (code_ptr < code_end) {
830 const Instruction* inst = Instruction::At(code_ptr);
831 switch (inst->Opcode()) {
832 case Instruction::CONST_STRING: {
833 uint32_t string_index = inst->VRegB_21c();
834 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
835 break;
836 }
837 case Instruction::CONST_STRING_JUMBO: {
838 uint32_t string_index = inst->VRegB_31c();
839 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
840 break;
841 }
842
843 default:
844 break;
845 }
846
847 code_ptr += inst->SizeInCodeUnits();
848 }
849}
850
851static void ResolveConstStrings(CompilerDriver* driver,
852 const std::vector<const DexFile*>& dex_files,
853 TimingLogger* timings) {
854 for (const DexFile* dex_file : dex_files) {
855 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
856
857 size_t class_def_count = dex_file->NumClassDefs();
858 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
859 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
860
861 const uint8_t* class_data = dex_file->GetClassData(class_def);
862 if (class_data == nullptr) {
863 // empty class, probably a marker interface
864 continue;
865 }
866
867 ClassDataItemIterator it(*dex_file, class_data);
868 // Skip fields
869 while (it.HasNextStaticField()) {
870 it.Next();
871 }
872 while (it.HasNextInstanceField()) {
873 it.Next();
874 }
875
876 bool compilation_enabled = driver->IsClassToCompile(
877 dex_file->StringByTypeIdx(class_def.class_idx_));
878 if (!compilation_enabled) {
879 // Compilation is skipped, do not resolve const-string in code of this class.
880 // TODO: Make sure that inlining honors this.
881 continue;
882 }
883
884 // Direct methods.
885 int64_t previous_direct_method_idx = -1;
886 while (it.HasNextDirectMethod()) {
887 uint32_t method_idx = it.GetMemberIndex();
888 if (method_idx == previous_direct_method_idx) {
889 // smali can create dex files with two encoded_methods sharing the same method_idx
890 // http://code.google.com/p/smali/issues/detail?id=119
891 it.Next();
892 continue;
893 }
894 previous_direct_method_idx = method_idx;
895 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
896 it.Next();
897 }
898 // Virtual methods.
899 int64_t previous_virtual_method_idx = -1;
900 while (it.HasNextVirtualMethod()) {
901 uint32_t method_idx = it.GetMemberIndex();
902 if (method_idx == previous_virtual_method_idx) {
903 // smali can create dex files with two encoded_methods sharing the same method_idx
904 // http://code.google.com/p/smali/issues/detail?id=119
905 it.Next();
906 continue;
907 }
908 previous_virtual_method_idx = method_idx;
909 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
910 it.Next();
911 }
912 DCHECK(!it.HasNext());
913 }
914 }
915}
916
917inline void CompilerDriver::CheckThreadPools() {
918 DCHECK(parallel_thread_pool_ != nullptr);
919 DCHECK(single_thread_pool_ != nullptr);
920}
921
922void CompilerDriver::PreCompile(jobject class_loader,
923 const std::vector<const DexFile*>& dex_files,
924 TimingLogger* timings) {
925 CheckThreadPools();
926
Brian Carlstrom7940e442013-07-12 13:46:57 -0700927 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800928 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700929
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700930 const bool verification_enabled = compiler_options_->IsVerificationEnabled();
931 const bool never_verify = compiler_options_->NeverVerify();
Mathieu Chartiera8077802016-03-16 19:08:31 -0700932 const bool verify_only_profile = compiler_options_->VerifyOnlyProfile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700933
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700934 // We need to resolve for never_verify since it needs to run dex to dex to add the
935 // RETURN_VOID_NO_BARRIER.
Mathieu Chartiera8077802016-03-16 19:08:31 -0700936 // Let the verifier resolve as needed for the verify_only_profile case.
937 if ((never_verify || verification_enabled) && !verify_only_profile) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800938 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700939 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
940 }
941
942 if (never_verify) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800943 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800944 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700945 }
946
947 if (!verification_enabled) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700948 return;
949 }
950
Vladimir Marko63dccbbe2016-09-21 13:51:10 +0100951 if (GetCompilerOptions().IsForceDeterminism() && GetCompilerOptions().IsBootImage()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800952 // Resolve strings from const-string. Do this now to have a deterministic image.
953 ResolveConstStrings(this, dex_files, timings);
954 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
955 }
956
957 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800958 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700959
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800960 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
961 LOG(FATAL) << "Had a hard failure verifying all classes, and was asked to abort in such "
962 << "situations. Please check the log.";
963 }
964
Andreas Gampeace0dc12016-01-20 13:33:13 -0800965 InitializeClasses(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800966 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700967
968 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800969 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700970}
971
Ian Rogersdfb325e2013-10-30 01:00:44 -0700972bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800973 if (image_classes_ != nullptr) {
974 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -0700975 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700976 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800977 // No set of image classes, assume we include all the classes.
978 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
Vladimir Marko63dccbbe2016-09-21 13:51:10 +0100979 return !GetCompilerOptions().IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700980}
981
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800982bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700983 if (classes_to_compile_ == nullptr) {
984 return true;
985 }
986 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800987}
988
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700989bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700990 if (methods_to_compile_ == nullptr) {
991 return true;
992 }
993
994 std::string tmp = PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
995 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
996}
997
Calin Juravle226501b2015-12-11 14:41:31 +0000998bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
999 if (profile_compilation_info_ == nullptr) {
1000 // If we miss profile information it means that we don't do a profile guided compilation.
1001 // Return true, and let the other filters decide if the method should be compiled.
1002 return true;
1003 }
1004 bool result = profile_compilation_info_->ContainsMethod(method_ref);
1005
1006 if (kDebugProfileGuidedCompilation) {
1007 LOG(INFO) << "[ProfileGuidedCompilation] "
1008 << (result ? "Compiled" : "Skipped") << " method:"
1009 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
1010 }
1011 return result;
1012}
1013
Mathieu Chartiera8077802016-03-16 19:08:31 -07001014bool CompilerDriver::ShouldVerifyClassBasedOnProfile(const DexFile& dex_file,
1015 uint16_t class_idx) const {
1016 if (!compiler_options_->VerifyOnlyProfile()) {
1017 // No profile, verify everything.
1018 return true;
1019 }
1020 DCHECK(profile_compilation_info_ != nullptr);
1021 bool result = profile_compilation_info_->ContainsClass(dex_file, class_idx);
1022 if (kDebugProfileGuidedCompilation) {
1023 LOG(INFO) << "[ProfileGuidedCompilation] "
1024 << (result ? "Verified" : "Skipped") << " method:"
1025 << dex_file.GetClassDescriptor(dex_file.GetClassDef(class_idx));
1026 }
1027 return result;
1028}
1029
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001030class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
1031 public:
Chih-Hung Hsieh471118e2016-04-29 14:27:41 -07001032 explicit ResolveCatchBlockExceptionsClassVisitor(
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001033 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve)
1034 : exceptions_to_resolve_(exceptions_to_resolve) {}
1035
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001036 virtual bool operator()(mirror::Class* c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001037 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Alex Lighte64300b2015-12-15 15:02:47 -08001038 for (auto& m : c->GetMethods(pointer_size)) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001039 ResolveExceptionsForMethod(&m, pointer_size);
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001040 }
1041 return true;
1042 }
1043
1044 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001045 void ResolveExceptionsForMethod(ArtMethod* method_handle, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001046 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001047 const DexFile::CodeItem* code_item = method_handle->GetCodeItem();
1048 if (code_item == nullptr) {
1049 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -07001050 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001051 if (code_item->tries_size_ == 0) {
1052 return; // nothing to process
1053 }
1054 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
1055 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
1056 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1057 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
1058 bool has_catch_all = false;
1059 if (encoded_catch_handler_size <= 0) {
1060 encoded_catch_handler_size = -encoded_catch_handler_size;
1061 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001062 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001063 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
1064 uint16_t encoded_catch_handler_handlers_type_idx =
1065 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1066 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko05792b92015-08-03 11:56:49 +01001067 if (!method_handle->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx,
1068 pointer_size)) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001069 exceptions_to_resolve_.emplace(encoded_catch_handler_handlers_type_idx,
1070 method_handle->GetDexFile());
1071 }
1072 // ignore address associated with catch handler
1073 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1074 }
1075 if (has_catch_all) {
1076 // ignore catch all address
1077 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1078 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001079 }
1080 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001081
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001082 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve_;
1083};
1084
1085class RecordImageClassesVisitor : public ClassVisitor {
1086 public:
1087 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
1088 : image_classes_(image_classes) {}
1089
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001090 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001091 std::string temp;
1092 image_classes_->insert(klass->GetDescriptor(&temp));
1093 return true;
1094 }
1095
1096 private:
1097 std::unordered_set<std::string>* const image_classes_;
1098};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001099
1100// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001101void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001102 CHECK(timings != nullptr);
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01001103 if (!GetCompilerOptions().IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001104 return;
1105 }
1106
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001107 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001108 // Make a first class to load all classes explicitly listed in the file
1109 Thread* self = Thread::Current();
1110 ScopedObjectAccess soa(self);
1111 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001112 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001113 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001114 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001115 StackHandleScope<1> hs(self);
1116 Handle<mirror::Class> klass(
1117 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001118 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001119 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001120 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001121 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001122 } else {
1123 ++it;
1124 }
1125 }
1126
1127 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1128 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1129 // Do this here so that exception classes appear to have been specified image classes.
Ian Rogers700a4022014-05-19 16:49:03 -07001130 std::set<std::pair<uint16_t, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001131 StackHandleScope<1> hs(self);
1132 Handle<mirror::Class> java_lang_Throwable(
1133 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001134 do {
1135 unresolved_exception_types.clear();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001136 ResolveCatchBlockExceptionsClassVisitor visitor(unresolved_exception_types);
1137 class_linker->VisitClasses(&visitor);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001138 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
1139 uint16_t exception_type_idx = exception_type.first;
1140 const DexFile* dex_file = exception_type.second;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001141 StackHandleScope<2> hs2(self);
Mathieu Chartierf284d442016-06-02 11:48:30 -07001142 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file,
1143 nullptr)));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001144 Handle<mirror::Class> klass(hs2.NewHandle(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001145 class_linker->ResolveType(*dex_file,
1146 exception_type_idx,
1147 dex_cache,
1148 ScopedNullHandle<mirror::ClassLoader>())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001149 if (klass.Get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001150 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1151 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1152 LOG(FATAL) << "Failed to resolve class " << descriptor;
1153 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001154 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001155 }
1156 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1157 // more are found
1158 } while (!unresolved_exception_types.empty());
1159
1160 // We walk the roots looking for classes so that we'll pick up the
1161 // above classes plus any classes them depend on such super
1162 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001163 RecordImageClassesVisitor visitor(image_classes_.get());
1164 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001165
1166 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001167}
1168
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001169static void MaybeAddToImageClasses(Handle<mirror::Class> c,
1170 std::unordered_set<std::string>* image_classes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001171 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001172 Thread* self = Thread::Current();
1173 StackHandleScope<1> hs(self);
1174 // Make a copy of the handle so that we don't clobber it doing Assign.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001175 MutableHandle<mirror::Class> klass(hs.NewHandle(c.Get()));
Ian Rogers1ff3c982014-08-12 02:30:58 -07001176 std::string temp;
Andreas Gampe542451c2016-07-26 09:02:02 -07001177 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001178 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001179 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001180 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1181 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001182 if (!result.second) { // Previously inserted.
1183 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001184 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001185 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Mathieu Chartierf8322842014-05-16 10:59:25 -07001186 for (size_t i = 0; i < klass->NumDirectInterfaces(); ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001187 StackHandleScope<1> hs2(self);
1188 MaybeAddToImageClasses(hs2.NewHandle(mirror::Class::GetDirectInterface(self, klass, i)),
Mathieu Chartierf8322842014-05-16 10:59:25 -07001189 image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001190 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001191 for (auto& m : c->GetVirtualMethods(pointer_size)) {
Alex Light36121492016-02-22 13:43:29 -08001192 StackHandleScope<1> hs2(self);
1193 MaybeAddToImageClasses(hs2.NewHandle(m.GetDeclaringClass()), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001194 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001195 if (klass->IsArrayClass()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001196 StackHandleScope<1> hs2(self);
1197 MaybeAddToImageClasses(hs2.NewHandle(klass->GetComponentType()), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001198 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001199 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001200 }
1201}
1202
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001203// Keeps all the data for the update together. Also doubles as the reference visitor.
1204// Note: we can use object pointers because we suspend all threads.
1205class ClinitImageUpdate {
1206 public:
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001207 static ClinitImageUpdate* Create(std::unordered_set<std::string>* image_class_descriptors,
1208 Thread* self, ClassLinker* linker, std::string* error_msg) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001209 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(image_class_descriptors, self,
1210 linker));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001211 if (res->dex_cache_class_ == nullptr) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001212 *error_msg = "Could not find DexCache class.";
1213 return nullptr;
1214 }
1215
1216 return res.release();
1217 }
1218
1219 ~ClinitImageUpdate() {
1220 // Allow others to suspend again.
1221 self_->EndAssertNoThreadSuspension(old_cause_);
1222 }
1223
1224 // Visitor for VisitReferences.
1225 void operator()(mirror::Object* object, MemberOffset field_offset, bool /* is_static */) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001226 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001227 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1228 if (ref != nullptr) {
1229 VisitClinitClassesObject(ref);
1230 }
1231 }
1232
1233 // java.lang.Reference visitor for VisitReferences.
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001234 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref ATTRIBUTE_UNUSED)
1235 const {}
1236
1237 // Ignore class native roots.
1238 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1239 const {}
1240 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001241
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001242 void Walk() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001243 // Use the initial classes as roots for a search.
1244 for (mirror::Class* klass_root : image_classes_) {
1245 VisitClinitClassesObject(klass_root);
1246 }
1247 }
1248
1249 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001250 class FindImageClassesVisitor : public ClassVisitor {
1251 public:
1252 explicit FindImageClassesVisitor(ClinitImageUpdate* data) : data_(data) {}
1253
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001254 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001255 std::string temp;
1256 const char* name = klass->GetDescriptor(&temp);
1257 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
1258 data_->image_classes_.push_back(klass);
1259 } else {
1260 // Check whether it is initialized and has a clinit. They must be kept, too.
1261 if (klass->IsInitialized() && klass->FindClassInitializer(
1262 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
1263 data_->image_classes_.push_back(klass);
1264 }
1265 }
1266 return true;
1267 }
1268
1269 private:
1270 ClinitImageUpdate* const data_;
1271 };
1272
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001273 ClinitImageUpdate(std::unordered_set<std::string>* image_class_descriptors, Thread* self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001274 ClassLinker* linker)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001275 REQUIRES_SHARED(Locks::mutator_lock_) :
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001276 image_class_descriptors_(image_class_descriptors), self_(self) {
1277 CHECK(linker != nullptr);
1278 CHECK(image_class_descriptors != nullptr);
1279
1280 // Make sure nobody interferes with us.
1281 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1282
1283 // Find the interesting classes.
Andreas Gampedc8b63c2014-12-02 14:39:52 -08001284 dex_cache_class_ = linker->LookupClass(self, "Ljava/lang/DexCache;",
1285 ComputeModifiedUtf8Hash("Ljava/lang/DexCache;"), nullptr);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001286
1287 // Find all the already-marked classes.
1288 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001289 FindImageClassesVisitor visitor(this);
1290 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001291 }
1292
1293 void VisitClinitClassesObject(mirror::Object* object) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001294 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001295 DCHECK(object != nullptr);
1296 if (marked_objects_.find(object) != marked_objects_.end()) {
1297 // Already processed.
1298 return;
1299 }
1300
1301 // Mark it.
1302 marked_objects_.insert(object);
1303
1304 if (object->IsClass()) {
1305 // If it is a class, add it.
1306 StackHandleScope<1> hs(self_);
1307 MaybeAddToImageClasses(hs.NewHandle(object->AsClass()), image_class_descriptors_);
1308 } else {
1309 // Else visit the object's class.
1310 VisitClinitClassesObject(object->GetClass());
1311 }
1312
Mathieu Chartiere401d142015-04-22 13:56:20 -07001313 // If it is not a DexCache, visit all references.
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001314 mirror::Class* klass = object->GetClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001315 if (klass != dex_cache_class_) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001316 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001317 }
1318 }
1319
1320 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001321 std::unordered_set<std::string>* const image_class_descriptors_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001322 std::vector<mirror::Class*> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001323 const mirror::Class* dex_cache_class_;
1324 Thread* const self_;
1325 const char* old_cause_;
1326
1327 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1328};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001329
Ian Rogers3d504072014-03-01 09:16:49 -08001330void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01001331 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001332 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001333
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001334 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001335
1336 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001337 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001338
1339 std::string error_msg;
1340 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(image_classes_.get(),
1341 Thread::Current(),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001342 runtime->GetClassLinker(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001343 &error_msg));
1344 CHECK(update.get() != nullptr) << error_msg; // TODO: Soft failure?
1345
1346 // Do the marking.
1347 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001348 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001349}
1350
Vladimir Marko07785bb2015-06-15 18:52:54 +01001351bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1352 Runtime* runtime = Runtime::Current();
1353 if (!runtime->IsAotCompiler()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001354 DCHECK(runtime->UseJitCompilation());
Vladimir Marko07785bb2015-06-15 18:52:54 +01001355 // Having the klass reference here implies that the klass is already loaded.
1356 return true;
1357 }
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01001358 if (!GetCompilerOptions().IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001359 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1360 // loaded because we don't even know what class loader will be used to load them.
1361 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1362 return class_in_image;
1363 }
1364 std::string temp;
1365 const char* descriptor = klass->GetDescriptor(&temp);
1366 return IsImageClass(descriptor);
1367}
1368
Vladimir Marko492a7fa2016-06-01 18:38:43 +01001369void CompilerDriver::MarkForDexToDexCompilation(Thread* self, const MethodReference& method_ref) {
1370 MutexLock lock(self, dex_to_dex_references_lock_);
1371 // Since we're compiling one dex file at a time, we need to look for the
1372 // current dex file entry only at the end of dex_to_dex_references_.
1373 if (dex_to_dex_references_.empty() ||
1374 &dex_to_dex_references_.back().GetDexFile() != method_ref.dex_file) {
1375 dex_to_dex_references_.emplace_back(*method_ref.dex_file);
1376 }
1377 dex_to_dex_references_.back().GetMethodIndexes().SetBit(method_ref.dex_method_index);
1378}
1379
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001380bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(Handle<mirror::DexCache> dex_cache,
1381 uint32_t type_idx) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001382 bool result = false;
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01001383 if ((GetCompilerOptions().IsBootImage() &&
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001384 IsImageClass(dex_cache->GetDexFile()->StringDataByIdx(
1385 dex_cache->GetDexFile()->GetTypeId(type_idx).descriptor_idx_))) ||
Calin Juravleffc87072016-04-20 14:22:09 +01001386 Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001387 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1388 result = (resolved_class != nullptr);
1389 }
1390
1391 if (result) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001392 stats_->TypeInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001393 } else {
1394 stats_->TypeNotInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001395 }
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001396 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001397}
1398
1399bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
1400 uint32_t string_idx) {
1401 // See also Compiler::ResolveDexFile
1402
1403 bool result = false;
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01001404 if (GetCompilerOptions().IsBootImage() || Runtime::Current()->UseJitCompilation()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001405 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001406 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001407 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1408 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1409 soa.Self(), dex_file, false)));
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01001410 if (GetCompilerOptions().IsBootImage()) {
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001411 // We resolve all const-string strings when building for the image.
1412 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1413 result = true;
1414 } else {
1415 // Just check whether the dex cache already has the string.
Calin Juravleffc87072016-04-20 14:22:09 +01001416 DCHECK(Runtime::Current()->UseJitCompilation());
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001417 result = (dex_cache->GetResolvedString(string_idx) != nullptr);
1418 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001419 }
1420 if (result) {
1421 stats_->StringInDexCache();
1422 } else {
1423 stats_->StringNotInDexCache();
1424 }
1425 return result;
1426}
1427
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001428bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx,
1429 Handle<mirror::DexCache> dex_cache,
1430 uint32_t type_idx) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001431 // Get type from dex cache assuming it was populated by the verifier
1432 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001433 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001434 stats_->TypeNeedsAccessCheck();
1435 return false; // Unknown class needs access checks.
1436 }
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001437 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001438 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1439 if (!is_accessible) {
1440 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1441 if (referrer_class == nullptr) {
1442 stats_->TypeNeedsAccessCheck();
1443 return false; // Incomplete referrer knowledge needs access check.
1444 }
1445 // Perform access check, will return true if access is ok or false if we're going to have to
1446 // check this at runtime (for example for class loaders).
1447 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001448 }
David Brazdil38f64d32016-01-18 17:13:41 +00001449 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001450 stats_->TypeDoesntNeedAccessCheck();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001451 } else {
1452 stats_->TypeNeedsAccessCheck();
1453 }
David Brazdil38f64d32016-01-18 17:13:41 +00001454 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001455}
1456
1457bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001458 Handle<mirror::DexCache> dex_cache,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001459 uint32_t type_idx,
1460 bool* finalizable) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001461 // Get type from dex cache assuming it was populated by the verifier.
1462 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001463 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001464 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001465 // Be conservative.
1466 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001467 return false; // Unknown class needs access checks.
1468 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001469 *finalizable = resolved_class->IsFinalizable();
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001470 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001471 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1472 if (!is_accessible) {
1473 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1474 if (referrer_class == nullptr) {
1475 stats_->TypeNeedsAccessCheck();
1476 return false; // Incomplete referrer knowledge needs access check.
1477 }
1478 // Perform access and instantiable checks, will return true if access is ok or false if we're
1479 // going to have to check this at runtime (for example for class loaders).
1480 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001481 }
David Brazdil38f64d32016-01-18 17:13:41 +00001482 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001483 if (result) {
1484 stats_->TypeDoesntNeedAccessCheck();
1485 } else {
1486 stats_->TypeNeedsAccessCheck();
1487 }
1488 return result;
1489}
1490
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001491bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
1492 bool* is_type_initialized, bool* use_direct_type_ptr,
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001493 uintptr_t* direct_type_ptr, bool* out_is_finalizable) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001494 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001495 Runtime* runtime = Runtime::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001496 mirror::DexCache* dex_cache = runtime->GetClassLinker()->FindDexCache(
1497 soa.Self(), dex_file, false);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001498 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1499 if (resolved_class == nullptr) {
1500 return false;
1501 }
Igor Murashkind6dee672014-10-16 18:36:16 -07001502 if (GetCompilerOptions().GetCompilePic()) {
1503 // Do not allow a direct class pointer to be used when compiling for position-independent
1504 return false;
1505 }
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001506 *out_is_finalizable = resolved_class->IsFinalizable();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001507 gc::Heap* heap = runtime->GetHeap();
1508 const bool compiling_boot = heap->IsCompilingBoot();
Alex Light6e183f22014-07-18 14:57:04 -07001509 const bool support_boot_image_fixup = GetSupportBootImageFixup();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001510 if (compiling_boot) {
1511 // boot -> boot class pointers.
1512 // True if the class is in the image at boot compiling time.
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01001513 const bool is_image_class = GetCompilerOptions().IsBootImage() && IsImageClass(
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001514 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
1515 // True if pc relative load works.
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001516 if (is_image_class && support_boot_image_fixup) {
1517 *is_type_initialized = resolved_class->IsInitialized();
1518 *use_direct_type_ptr = false;
1519 *direct_type_ptr = 0;
1520 return true;
1521 } else {
1522 return false;
1523 }
Calin Juravleffc87072016-04-20 14:22:09 +01001524 } else if (runtime->UseJitCompilation() && !heap->IsMovableObject(resolved_class)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001525 *is_type_initialized = resolved_class->IsInitialized();
1526 // If the class may move around, then don't embed it as a direct pointer.
1527 *use_direct_type_ptr = true;
1528 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1529 return true;
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001530 } else {
1531 // True if the class is in the image at app compiling time.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001532 const bool class_in_image = heap->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
Alex Light6e183f22014-07-18 14:57:04 -07001533 if (class_in_image && support_boot_image_fixup) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001534 // boot -> app class pointers.
1535 *is_type_initialized = resolved_class->IsInitialized();
Alex Lighta59dd802014-07-02 16:28:08 -07001536 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1537 *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001538 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1539 return true;
1540 } else {
1541 // app -> app class pointers.
1542 // Give up because app does not have an image and class
1543 // isn't created at compile time. TODO: implement this
1544 // if/when each app gets an image.
1545 return false;
1546 }
1547 }
1548}
1549
Fred Shihe7f82e22014-08-06 10:46:37 -07001550bool CompilerDriver::CanEmbedReferenceTypeInCode(ClassReference* ref,
1551 bool* use_direct_ptr,
1552 uintptr_t* direct_type_ptr) {
1553 CHECK(ref != nullptr);
1554 CHECK(use_direct_ptr != nullptr);
1555 CHECK(direct_type_ptr != nullptr);
1556
1557 ScopedObjectAccess soa(Thread::Current());
1558 mirror::Class* reference_class = mirror::Reference::GetJavaLangRefReference();
Andreas Gampe928f72b2014-09-09 19:53:48 -07001559 bool is_initialized = false;
Fred Shihe7f82e22014-08-06 10:46:37 -07001560 bool unused_finalizable;
1561 // Make sure we have a finished Reference class object before attempting to use it.
1562 if (!CanEmbedTypeInCode(*reference_class->GetDexCache()->GetDexFile(),
1563 reference_class->GetDexTypeIndex(), &is_initialized,
1564 use_direct_ptr, direct_type_ptr, &unused_finalizable) ||
1565 !is_initialized) {
1566 return false;
1567 }
1568 ref->first = &reference_class->GetDexFile();
1569 ref->second = reference_class->GetDexClassDefIndex();
1570 return true;
1571}
1572
1573uint32_t CompilerDriver::GetReferenceSlowFlagOffset() const {
1574 ScopedObjectAccess soa(Thread::Current());
1575 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1576 DCHECK(klass->IsInitialized());
1577 return klass->GetSlowPathFlagOffset().Uint32Value();
1578}
1579
1580uint32_t CompilerDriver::GetReferenceDisableFlagOffset() const {
1581 ScopedObjectAccess soa(Thread::Current());
1582 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1583 DCHECK(klass->IsInitialized());
1584 return klass->GetDisableIntrinsicFlagOffset().Uint32Value();
1585}
1586
Vladimir Marko20f85592015-03-19 10:07:02 +00001587DexCacheArraysLayout CompilerDriver::GetDexCacheArraysLayout(const DexFile* dex_file) {
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001588 return ContainsElement(GetDexFilesForOatFile(), dex_file)
Mathieu Chartierc7853442015-03-27 14:35:38 -07001589 ? DexCacheArraysLayout(GetInstructionSetPointerSize(instruction_set_), dex_file)
Vladimir Marko20f85592015-03-19 10:07:02 +00001590 : DexCacheArraysLayout();
1591}
1592
Vladimir Markobe0e5462014-02-26 11:24:15 +00001593void CompilerDriver::ProcessedInstanceField(bool resolved) {
1594 if (!resolved) {
1595 stats_->UnresolvedInstanceField();
1596 } else {
1597 stats_->ResolvedInstanceField();
1598 }
1599}
1600
1601void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1602 if (!resolved) {
1603 stats_->UnresolvedStaticField();
1604 } else if (local) {
1605 stats_->ResolvedLocalStaticField();
1606 } else {
1607 stats_->ResolvedStaticField();
1608 }
1609}
1610
Vladimir Markof096aad2014-01-23 15:51:58 +00001611void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
1612 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001613}
1614
Mathieu Chartierc7853442015-03-27 14:35:38 -07001615ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1616 const DexCompilationUnit* mUnit, bool is_put,
1617 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001618 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001619 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001620 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001621 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001622 {
Mathieu Chartier736b5602015-09-02 14:54:11 -07001623 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001624 Handle<mirror::ClassLoader> class_loader_handle(
1625 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartier736b5602015-09-02 14:54:11 -07001626 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001627 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001628 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001629 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001630 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001631 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001632 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001633 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001634 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001635 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001636 ProcessedInstanceField(can_link);
1637 return can_link ? resolved_field : nullptr;
1638}
1639
1640bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1641 bool is_put, MemberOffset* field_offset,
1642 bool* is_volatile) {
1643 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001644 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001645
Mathieu Chartierc7853442015-03-27 14:35:38 -07001646 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001647 // Conservative defaults.
1648 *is_volatile = true;
1649 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001650 return false;
1651 } else {
1652 *is_volatile = resolved_field->IsVolatile();
1653 *field_offset = resolved_field->GetOffset();
1654 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001655 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001656}
1657
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001658void CompilerDriver::GetCodeAndMethodForDirectCall(const mirror::Class* referrer_class,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001659 ArtMethod* method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001660 uintptr_t* direct_code,
1661 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001662 // For direct and static methods compute possible direct_code and direct_method values, ie
1663 // an address for the Method* being invoked and an address of the code for that Method*.
1664 // For interface calls compute a value for direct_method that is the interface method being
1665 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001666 *direct_code = 0;
1667 *direct_method = 0;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001668 Runtime* const runtime = Runtime::Current();
1669 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001670 auto* cl = runtime->GetClassLinker();
Igor Murashkind6dee672014-10-16 18:36:16 -07001671 bool use_dex_cache = GetCompilerOptions().GetCompilePic(); // Off by default
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001672 const bool compiling_boot = heap->IsCompilingBoot();
Alex Lighta59dd802014-07-02 16:28:08 -07001673 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1674 const bool force_relocations = (compiling_boot ||
1675 GetCompilerOptions().GetIncludePatchInformation());
Elliott Hughes956af0f2014-12-11 14:34:28 -08001676 // TODO: support patching on all architectures.
1677 use_dex_cache = use_dex_cache || (force_relocations && !support_boot_image_fixup_);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001678 mirror::Class* declaring_class = method->GetDeclaringClass();
1679 bool method_code_in_boot = declaring_class->GetClassLoader() == nullptr;
Ian Rogers83883d72013-10-21 21:07:24 -07001680 if (!use_dex_cache) {
1681 if (!method_code_in_boot) {
1682 use_dex_cache = true;
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001683 } else if (method->IsStatic() &&
1684 declaring_class != referrer_class &&
1685 !declaring_class->IsInitialized()) {
1686 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1687 // class.
1688 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001689 }
Ian Rogers83883d72013-10-21 21:07:24 -07001690 }
Calin Juravleffc87072016-04-20 14:22:09 +01001691 if (runtime->UseJitCompilation()) {
Mathieu Chartier28a35882015-02-26 18:28:07 -08001692 // If we are the JIT, then don't allow a direct call to the interpreter bridge since this will
1693 // never be updated even after we compile the method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001694 if (cl->IsQuickToInterpreterBridge(
Mathieu Chartier28a35882015-02-26 18:28:07 -08001695 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)))) {
1696 use_dex_cache = true;
1697 }
1698 }
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001699
Alex Lighta59dd802014-07-02 16:28:08 -07001700 if (!use_dex_cache && force_relocations) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001701 bool is_in_image;
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01001702 if (GetCompilerOptions().IsBootImage()) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001703 is_in_image = IsImageClass(method->GetDeclaringClassDescriptor());
1704 } else {
1705 is_in_image = instruction_set_ != kX86 && instruction_set_ != kX86_64 &&
Vladimir Markoc08ab292015-06-22 14:35:42 +01001706 heap->FindSpaceFromObject(method->GetDeclaringClass(), false)->IsImageSpace() &&
1707 !cl->IsQuickToInterpreterBridge(
1708 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)));
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001709 }
1710 if (!is_in_image) {
Ian Rogers83883d72013-10-21 21:07:24 -07001711 // We can only branch directly to Methods that are resolved in the DexCache.
1712 // Otherwise we won't invoke the resolution trampoline.
1713 use_dex_cache = true;
1714 }
1715 }
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001716
1717 if (!use_dex_cache) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001718 bool method_in_image = false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001719 const std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
1720 for (gc::space::ImageSpace* image_space : image_spaces) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001721 const auto& method_section = image_space->GetImageHeader().GetMethodsSection();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001722 if (method_section.Contains(reinterpret_cast<uint8_t*>(method) - image_space->Begin())) {
1723 method_in_image = true;
1724 break;
1725 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001726 }
Calin Juravleffc87072016-04-20 14:22:09 +01001727 if (method_in_image || compiling_boot || runtime->UseJitCompilation()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001728 // We know we must be able to get to the method in the image, so use that pointer.
Mathieu Chartier6ced4092015-02-27 16:10:48 -08001729 // In the case where we are the JIT, we can always use direct pointers since we know where
1730 // the method and its code are / will be. We don't sharpen to interpreter bridge since we
1731 // check IsQuickToInterpreterBridge above.
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001732 CHECK(!method->IsAbstract());
Alex Lighta59dd802014-07-02 16:28:08 -07001733 *direct_method = force_relocations ? -1 : reinterpret_cast<uintptr_t>(method);
1734 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001735 } else {
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001736 // Set the code and rely on the dex cache for the method.
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001737 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001738 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001739 }
1740}
1741
Vladimir Marko2730db02014-01-27 11:15:17 +00001742const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1743 uint32_t method_idx) const {
1744 MethodReference ref(dex_file, method_idx);
1745 return verification_results_->GetVerifiedMethod(ref);
1746}
1747
1748bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001749 if (!compiler_options_->IsVerificationEnabled()) {
1750 // If we didn't verify, every cast has to be treated as non-safe.
1751 return false;
1752 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001753 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1754 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001755 if (result) {
1756 stats_->SafeCast();
1757 } else {
1758 stats_->NotASafeCast();
1759 }
1760 return result;
1761}
1762
Mathieu Chartier90443472015-07-16 20:32:27 -07001763class CompilationVisitor {
1764 public:
1765 virtual ~CompilationVisitor() {}
1766 virtual void Visit(size_t index) = 0;
1767};
1768
Brian Carlstrom7940e442013-07-12 13:46:57 -07001769class ParallelCompilationManager {
1770 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001771 ParallelCompilationManager(ClassLinker* class_linker,
1772 jobject class_loader,
1773 CompilerDriver* compiler,
1774 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001775 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001776 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001777 : index_(0),
1778 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001779 class_loader_(class_loader),
1780 compiler_(compiler),
1781 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001782 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001783 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001784
1785 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001786 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001787 return class_linker_;
1788 }
1789
1790 jobject GetClassLoader() const {
1791 return class_loader_;
1792 }
1793
1794 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001795 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001796 return compiler_;
1797 }
1798
1799 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001800 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001801 return dex_file_;
1802 }
1803
Andreas Gampede7b4362014-07-28 18:38:57 -07001804 const std::vector<const DexFile*>& GetDexFiles() const {
1805 return dex_files_;
1806 }
1807
Mathieu Chartier90443472015-07-16 20:32:27 -07001808 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1809 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001810 Thread* self = Thread::Current();
1811 self->AssertNoPendingException();
1812 CHECK_GT(work_units, 0U);
1813
Ian Rogers3e5cf302014-05-20 16:40:37 -07001814 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001815 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001816 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001817 }
1818 thread_pool_->StartWorkers(self);
1819
1820 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1821 // thread destructor's called below perform join).
1822 CHECK_NE(self->GetState(), kRunnable);
1823
1824 // Wait for all the worker threads to finish.
1825 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001826
1827 // And stop the workers accepting jobs.
1828 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001829 }
1830
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001831 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001832 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001833 }
1834
Brian Carlstrom7940e442013-07-12 13:46:57 -07001835 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001836 class ForAllClosure : public Task {
1837 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001838 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001839 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001840 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001841 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001842
1843 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001844 while (true) {
1845 const size_t index = manager_->NextIndex();
1846 if (UNLIKELY(index >= end_)) {
1847 break;
1848 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001849 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001850 self->AssertNoPendingException();
1851 }
1852 }
1853
1854 virtual void Finalize() {
1855 delete this;
1856 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001857
Brian Carlstrom7940e442013-07-12 13:46:57 -07001858 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001859 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001860 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001861 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001862 };
1863
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001864 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001865 ClassLinker* const class_linker_;
1866 const jobject class_loader_;
1867 CompilerDriver* const compiler_;
1868 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001869 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001870 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001871
1872 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001873};
1874
Jeff Hao0e49b422013-11-08 12:16:56 -08001875// A fast version of SkipClass above if the class pointer is available
1876// that avoids the expensive FindInClassPath search.
1877static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001878 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001879 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001880 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1881 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001882 if (class_loader == nullptr) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001883 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1884 << dex_file.GetLocation() << " previously found in "
1885 << original_dex_file.GetLocation();
1886 }
1887 return true;
1888 }
1889 return false;
1890}
1891
Mathieu Chartier70b63482014-06-27 17:19:04 -07001892static void CheckAndClearResolveException(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001893 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07001894 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001895 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001896 std::string temp;
1897 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1898 const char* expected_exceptions[] = {
1899 "Ljava/lang/IllegalAccessError;",
1900 "Ljava/lang/IncompatibleClassChangeError;",
1901 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001902 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07001903 "Ljava/lang/NoClassDefFoundError;",
1904 "Ljava/lang/NoSuchFieldError;",
1905 "Ljava/lang/NoSuchMethodError;"
1906 };
1907 bool found = false;
1908 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1909 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1910 found = true;
1911 }
1912 }
1913 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001914 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07001915 }
1916 self->ClearException();
1917}
1918
Mathieu Chartierb5d38612016-04-07 10:52:52 -07001919bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file,
1920 uint16_t class_def_idx) const {
1921 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
1922 const uint8_t* class_data = dex_file.GetClassData(class_def);
1923 if (class_data == nullptr) {
1924 // Empty class such as a marker interface.
1925 return false;
1926 }
1927 ClassDataItemIterator it(dex_file, class_data);
1928 while (it.HasNextStaticField()) {
1929 it.Next();
1930 }
1931 // We require a constructor barrier if there are final instance fields.
1932 while (it.HasNextInstanceField()) {
1933 if (it.MemberIsFinal()) {
1934 return true;
1935 }
1936 it.Next();
1937 }
1938 return false;
1939}
1940
Mathieu Chartier90443472015-07-16 20:32:27 -07001941class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
1942 public:
1943 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
1944 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001945
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001946 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001947 ATRACE_CALL();
1948 Thread* const self = Thread::Current();
1949 jobject jclass_loader = manager_->GetClassLoader();
1950 const DexFile& dex_file = *manager_->GetDexFile();
1951 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001952
Mathieu Chartier90443472015-07-16 20:32:27 -07001953 // If an instance field is final then we need to have a barrier on the return, static final
1954 // fields are assigned within the lock held for class initialization. Conservatively assume
1955 // constructor barriers are always required.
1956 bool requires_constructor_barrier = true;
1957
1958 // Method and Field are the worst. We can't resolve without either
1959 // context from the code use (to disambiguate virtual vs direct
1960 // method and instance vs static field) or from class
1961 // definitions. While the compiler will resolve what it can as it
1962 // needs it, here we try to resolve fields and methods used in class
1963 // definitions, since many of them many never be referenced by
1964 // generated code.
1965 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1966 ScopedObjectAccess soa(self);
1967 StackHandleScope<2> hs(soa.Self());
1968 Handle<mirror::ClassLoader> class_loader(
1969 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001970 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1971 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07001972 // Resolve the class.
1973 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
1974 class_loader);
1975 bool resolve_fields_and_methods;
1976 if (klass == nullptr) {
1977 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
1978 // attempt to resolve methods and fields when there is no declaring class.
1979 CheckAndClearResolveException(soa.Self());
1980 resolve_fields_and_methods = false;
1981 } else {
1982 // We successfully resolved a class, should we skip it?
1983 if (SkipClass(jclass_loader, dex_file, klass)) {
1984 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001985 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001986 // We want to resolve the methods and fields eagerly.
1987 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07001988 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001989 // Note the class_data pointer advances through the headers,
1990 // static fields, instance fields, direct methods, and virtual
1991 // methods.
1992 const uint8_t* class_data = dex_file.GetClassData(class_def);
1993 if (class_data == nullptr) {
1994 // Empty class such as a marker interface.
1995 requires_constructor_barrier = false;
1996 } else {
1997 ClassDataItemIterator it(dex_file, class_data);
1998 while (it.HasNextStaticField()) {
1999 if (resolve_fields_and_methods) {
2000 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2001 dex_cache, class_loader, true);
2002 if (field == nullptr) {
2003 CheckAndClearResolveException(soa.Self());
2004 }
Ian Rogers68b56852014-08-29 20:19:11 -07002005 }
2006 it.Next();
2007 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002008 // We require a constructor barrier if there are final instance fields.
2009 requires_constructor_barrier = false;
2010 while (it.HasNextInstanceField()) {
2011 if (it.MemberIsFinal()) {
2012 requires_constructor_barrier = true;
2013 }
2014 if (resolve_fields_and_methods) {
2015 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2016 dex_cache, class_loader, false);
2017 if (field == nullptr) {
2018 CheckAndClearResolveException(soa.Self());
2019 }
Ian Rogers68b56852014-08-29 20:19:11 -07002020 }
2021 it.Next();
2022 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002023 if (resolve_fields_and_methods) {
2024 while (it.HasNextDirectMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002025 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002026 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2027 it.GetMethodInvokeType(class_def));
2028 if (method == nullptr) {
2029 CheckAndClearResolveException(soa.Self());
2030 }
2031 it.Next();
2032 }
2033 while (it.HasNextVirtualMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002034 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002035 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2036 it.GetMethodInvokeType(class_def));
2037 if (method == nullptr) {
2038 CheckAndClearResolveException(soa.Self());
2039 }
2040 it.Next();
2041 }
2042 DCHECK(!it.HasNext());
2043 }
2044 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002045 manager_->GetCompiler()->SetRequiresConstructorBarrier(self,
2046 &dex_file,
2047 class_def_index,
2048 requires_constructor_barrier);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002049 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002050
Mathieu Chartier90443472015-07-16 20:32:27 -07002051 private:
2052 const ParallelCompilationManager* const manager_;
2053};
2054
2055class ResolveTypeVisitor : public CompilationVisitor {
2056 public:
2057 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
2058 }
2059 virtual void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002060 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07002061 ScopedObjectAccess soa(Thread::Current());
2062 ClassLinker* class_linker = manager_->GetClassLinker();
2063 const DexFile& dex_file = *manager_->GetDexFile();
2064 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07002065 Handle<mirror::ClassLoader> class_loader(
2066 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002067 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
2068 dex_file,
Mathieu Chartierf284d442016-06-02 11:48:30 -07002069 class_loader.Get())));
Mathieu Chartier90443472015-07-16 20:32:27 -07002070 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002071
Mathieu Chartier90443472015-07-16 20:32:27 -07002072 if (klass == nullptr) {
2073 soa.Self()->AssertPendingException();
2074 mirror::Throwable* exception = soa.Self()->GetException();
2075 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
2076 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
2077 // There's little point continuing compilation if the heap is exhausted.
2078 LOG(FATAL) << "Out of memory during type resolution for compilation";
2079 }
2080 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07002081 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002082 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002083
2084 private:
2085 const ParallelCompilationManager* const manager_;
2086};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002087
Andreas Gampeace0dc12016-01-20 13:33:13 -08002088void CompilerDriver::ResolveDexFile(jobject class_loader,
2089 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002090 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002091 ThreadPool* thread_pool,
2092 size_t thread_count,
2093 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002094 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2095
2096 // TODO: we could resolve strings here, although the string table is largely filled with class
2097 // and method names.
2098
Andreas Gampede7b4362014-07-28 18:38:57 -07002099 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2100 thread_pool);
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01002101 if (GetCompilerOptions().IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002102 // For images we resolve all types, such as array, whereas for applications just those with
2103 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002104 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002105 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002106 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002107 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002108
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002109 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002110 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002111 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002112}
2113
Andreas Gampeace0dc12016-01-20 13:33:13 -08002114void CompilerDriver::SetVerified(jobject class_loader,
2115 const std::vector<const DexFile*>& dex_files,
2116 TimingLogger* timings) {
2117 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07002118 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002119 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002120 SetVerifiedDexFile(class_loader,
2121 *dex_file,
2122 dex_files,
2123 parallel_thread_pool_.get(),
2124 parallel_thread_count_,
2125 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002126 }
2127}
2128
Andreas Gampeace0dc12016-01-20 13:33:13 -08002129void CompilerDriver::Verify(jobject class_loader,
2130 const std::vector<const DexFile*>& dex_files,
2131 TimingLogger* timings) {
2132 // Note: verification should not be pulling in classes anymore when compiling the boot image,
2133 // as all should have been resolved before. As such, doing this in parallel should still
2134 // be deterministic.
Mathieu Chartier90443472015-07-16 20:32:27 -07002135 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002136 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002137 VerifyDexFile(class_loader,
2138 *dex_file,
2139 dex_files,
2140 parallel_thread_pool_.get(),
2141 parallel_thread_count_,
2142 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002143 }
2144}
2145
Mathieu Chartier90443472015-07-16 20:32:27 -07002146class VerifyClassVisitor : public CompilationVisitor {
2147 public:
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002148 VerifyClassVisitor(const ParallelCompilationManager* manager, verifier::HardFailLogMode log_level)
Andreas Gampe7fe30232016-03-25 16:58:00 -07002149 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002150
Mathieu Chartier90443472015-07-16 20:32:27 -07002151 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2152 ATRACE_CALL();
2153 ScopedObjectAccess soa(Thread::Current());
2154 const DexFile& dex_file = *manager_->GetDexFile();
Mathieu Chartiera8077802016-03-16 19:08:31 -07002155 if (!manager_->GetCompiler()->ShouldVerifyClassBasedOnProfile(dex_file, class_def_index)) {
2156 // Skip verification since the class is not in the profile.
2157 return;
2158 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002159 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2160 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2161 ClassLinker* class_linker = manager_->GetClassLinker();
2162 jobject jclass_loader = manager_->GetClassLoader();
2163 StackHandleScope<3> hs(soa.Self());
2164 Handle<mirror::ClassLoader> class_loader(
2165 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2166 Handle<mirror::Class> klass(
2167 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2168 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002169 CHECK(soa.Self()->IsExceptionPending());
2170 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07002171
2172 /*
2173 * At compile time, we can still structurally verify the class even if FindClass fails.
2174 * This is to ensure the class is structurally sound for compilation. An unsound class
2175 * will be rejected by the verifier and later skipped during compilation in the compiler.
2176 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002177 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2178 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002179 std::string error_msg;
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002180 if (verifier::MethodVerifier::VerifyClass(soa.Self(),
2181 &dex_file,
2182 dex_cache,
2183 class_loader,
David Brazdil15fc7292016-09-02 14:13:18 +01002184 class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08002185 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002186 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07002187 log_level_,
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002188 &error_msg) ==
Mathieu Chartier90443472015-07-16 20:32:27 -07002189 verifier::MethodVerifier::kHardFailure) {
2190 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2191 << " because: " << error_msg;
2192 manager_->GetCompiler()->SetHadHardVerifierFailure();
2193 }
2194 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
2195 CHECK(klass->IsResolved()) << PrettyClass(klass.Get());
Andreas Gampe7fe30232016-03-25 16:58:00 -07002196 class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002197
2198 if (klass->IsErroneous()) {
2199 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2200 CHECK(soa.Self()->IsExceptionPending());
2201 soa.Self()->ClearException();
2202 manager_->GetCompiler()->SetHadHardVerifierFailure();
2203 }
2204
2205 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
2206 << PrettyDescriptor(klass.Get()) << ": state=" << klass->GetStatus();
2207
2208 // It is *very* problematic if there are verification errors in the boot classpath. For example,
2209 // we rely on things working OK without verification when the decryption dialog is brought up.
2210 // So abort in a debug build if we find this violated.
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01002211 DCHECK(!manager_->GetCompiler()->GetCompilerOptions().IsBootImage() || klass->IsVerified())
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002212 << "Boot classpath class " << PrettyClass(klass.Get()) << " failed to fully verify.";
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002213 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002214 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002215 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002216
2217 private:
2218 const ParallelCompilationManager* const manager_;
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002219 const verifier::HardFailLogMode log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002220};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002221
Andreas Gampeace0dc12016-01-20 13:33:13 -08002222void CompilerDriver::VerifyDexFile(jobject class_loader,
2223 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002224 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002225 ThreadPool* thread_pool,
2226 size_t thread_count,
2227 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002228 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002229 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002230 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2231 thread_pool);
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002232 verifier::HardFailLogMode log_level = GetCompilerOptions().AbortOnHardVerifierFailure()
2233 ? verifier::HardFailLogMode::kLogInternalFatal
2234 : verifier::HardFailLogMode::kLogWarning;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002235 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002236 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002237}
2238
Mathieu Chartier90443472015-07-16 20:32:27 -07002239class SetVerifiedClassVisitor : public CompilationVisitor {
2240 public:
2241 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2242
2243 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2244 ATRACE_CALL();
2245 ScopedObjectAccess soa(Thread::Current());
2246 const DexFile& dex_file = *manager_->GetDexFile();
2247 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2248 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2249 ClassLinker* class_linker = manager_->GetClassLinker();
2250 jobject jclass_loader = manager_->GetClassLoader();
2251 StackHandleScope<3> hs(soa.Self());
2252 Handle<mirror::ClassLoader> class_loader(
2253 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2254 Handle<mirror::Class> klass(
2255 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2256 // Class might have failed resolution. Then don't set it to verified.
2257 if (klass.Get() != nullptr) {
2258 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2259 // very wrong.
2260 if (klass->IsResolved()) {
2261 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
2262 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2263 // Set class status to verified.
2264 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self());
2265 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2266 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002267 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002268 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002269 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002270 }
2271 // Record the final class status if necessary.
2272 ClassReference ref(manager_->GetDexFile(), class_def_index);
2273 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002274 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002275 } else {
2276 Thread* self = soa.Self();
2277 DCHECK(self->IsExceptionPending());
2278 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002279 }
2280 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002281
2282 private:
2283 const ParallelCompilationManager* const manager_;
2284};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002285
Andreas Gampeace0dc12016-01-20 13:33:13 -08002286void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2287 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002288 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002289 ThreadPool* thread_pool,
2290 size_t thread_count,
2291 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002292 TimingLogger::ScopedTiming t("Verify Dex File", timings);
2293 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2294 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2295 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002296 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002297 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002298}
2299
Mathieu Chartier90443472015-07-16 20:32:27 -07002300class InitializeClassVisitor : public CompilationVisitor {
2301 public:
2302 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002303
Mathieu Chartier90443472015-07-16 20:32:27 -07002304 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2305 ATRACE_CALL();
2306 jobject jclass_loader = manager_->GetClassLoader();
2307 const DexFile& dex_file = *manager_->GetDexFile();
2308 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2309 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2310 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002311
Mathieu Chartier90443472015-07-16 20:32:27 -07002312 ScopedObjectAccess soa(Thread::Current());
2313 StackHandleScope<3> hs(soa.Self());
2314 Handle<mirror::ClassLoader> class_loader(
2315 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2316 Handle<mirror::Class> klass(
2317 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2318
2319 if (klass.Get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) {
2320 // Only try to initialize classes that were successfully verified.
2321 if (klass->IsVerified()) {
2322 // Attempt to initialize the class but bail if we either need to initialize the super-class
2323 // or static fields.
2324 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002325 if (!klass->IsInitialized()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002326 // We don't want non-trivial class initialization occurring on multiple threads due to
2327 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2328 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2329 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2330 // after first initializing its parents, whose locks are acquired. This leads to a
2331 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2332 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2333 // than use a special Object for the purpose we use the Class of java.lang.Class.
2334 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2335 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2336 // Attempt to initialize allowing initialization of parent classes but still not static
2337 // fields.
2338 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
2339 if (!klass->IsInitialized()) {
2340 // We need to initialize static fields, we only do this for image classes that aren't
2341 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01002342 bool can_init_static_fields =
2343 manager_->GetCompiler()->GetCompilerOptions().IsBootImage() &&
Mathieu Chartier90443472015-07-16 20:32:27 -07002344 manager_->GetCompiler()->IsImageClass(descriptor) &&
2345 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2346 if (can_init_static_fields) {
2347 VLOG(compiler) << "Initializing: " << descriptor;
2348 // TODO multithreading support. We should ensure the current compilation thread has
2349 // exclusive access to the runtime and the transaction. To achieve this, we could use
2350 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2351 // checks in Thread::AssertThreadSuspensionIsAllowable.
2352 Runtime* const runtime = Runtime::Current();
2353 Transaction transaction;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002354
Mathieu Chartier90443472015-07-16 20:32:27 -07002355 // Run the class initializer in transaction mode.
2356 runtime->EnterTransactionMode(&transaction);
2357 const mirror::Class::Status old_status = klass->GetStatus();
2358 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2359 true);
2360 // TODO we detach transaction from runtime to indicate we quit the transactional
2361 // mode which prevents the GC from visiting objects modified during the transaction.
2362 // Ensure GC is not run so don't access freed objects when aborting transaction.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002363
Mathieu Chartier268764d2016-09-13 12:09:38 -07002364 ScopedAssertNoThreadSuspension ants("Transaction end");
Mathieu Chartier90443472015-07-16 20:32:27 -07002365 runtime->ExitTransactionMode();
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002366
Mathieu Chartier90443472015-07-16 20:32:27 -07002367 if (!success) {
2368 CHECK(soa.Self()->IsExceptionPending());
2369 mirror::Throwable* exception = soa.Self()->GetException();
2370 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2371 << exception->Dump();
2372 std::ostream* file_log = manager_->GetCompiler()->
2373 GetCompilerOptions().GetInitFailureOutput();
2374 if (file_log != nullptr) {
2375 *file_log << descriptor << "\n";
2376 *file_log << exception->Dump() << "\n";
2377 }
2378 soa.Self()->ClearException();
2379 transaction.Rollback();
2380 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002381 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002382 }
2383 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002384 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002385 }
2386 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002387 // Record the final class status if necessary.
2388 ClassReference ref(manager_->GetDexFile(), class_def_index);
2389 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002390 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002391 // Clear any class not found or verification exceptions.
2392 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002393 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002394
2395 private:
2396 const ParallelCompilationManager* const manager_;
2397};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002398
Andreas Gampeace0dc12016-01-20 13:33:13 -08002399void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2400 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002401 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002402 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002403 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002404
2405 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2406 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2407 ThreadPool* init_thread_pool = force_determinism
2408 ? single_thread_pool_.get()
2409 : parallel_thread_pool_.get();
2410 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2411
Brian Carlstrom7940e442013-07-12 13:46:57 -07002412 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002413 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002414 init_thread_pool);
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01002415 if (GetCompilerOptions().IsBootImage()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002416 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002417 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002418 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002419 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002420 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002421}
2422
Mathieu Chartier91288d82016-04-28 09:44:54 -07002423class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002424 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002425 virtual bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier91288d82016-04-28 09:44:54 -07002426 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2427 return true;
2428 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002429 if (klass->IsArrayClass()) {
2430 StackHandleScope<1> hs(Thread::Current());
2431 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(),
2432 hs.NewHandle(klass),
2433 true,
2434 true);
2435 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002436 // Create the conflict tables.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002437 FillIMTAndConflictTables(klass);
Nicolas Geoffray88f288e2016-06-29 08:17:52 +00002438 return true;
Nelli Kimbadee982016-05-13 13:08:53 +03002439 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002440
2441 private:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002442 void FillIMTAndConflictTables(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002443 if (!klass->ShouldHaveImt()) {
2444 return;
2445 }
2446 if (visited_classes_.find(klass) != visited_classes_.end()) {
2447 return;
2448 }
2449 if (klass->HasSuperClass()) {
2450 FillIMTAndConflictTables(klass->GetSuperClass());
2451 }
2452 if (!klass->IsTemp()) {
2453 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
2454 }
2455 visited_classes_.insert(klass);
2456 }
2457
2458 std::set<mirror::Class*> visited_classes_;
Mathieu Chartier085a0722016-04-01 17:33:31 -07002459};
2460
Brian Carlstrom7940e442013-07-12 13:46:57 -07002461void CompilerDriver::InitializeClasses(jobject class_loader,
2462 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002463 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002464 for (size_t i = 0; i != dex_files.size(); ++i) {
2465 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002466 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002467 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002468 }
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01002469 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsAppImage()) {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002470 // Make sure that we call EnsureIntiailized on all the array classes to call
2471 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2472 // changed at runtime resulting in more dirty image pages.
Mathieu Chartier91288d82016-04-28 09:44:54 -07002473 // Also create conflict tables.
2474 // Only useful if we are compiling an image (image_classes_ is not null).
Mathieu Chartier085a0722016-04-01 17:33:31 -07002475 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier91288d82016-04-28 09:44:54 -07002476 InitializeArrayClassesAndCreateConflictTablesVisitor visitor;
2477 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
Mathieu Chartier085a0722016-04-01 17:33:31 -07002478 }
Vladimir Marko63dccbbe2016-09-21 13:51:10 +01002479 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002480 // Prune garbage objects created during aborted transactions.
2481 Runtime::Current()->GetHeap()->CollectGarbage(true);
2482 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002483}
2484
Andreas Gampeace0dc12016-01-20 13:33:13 -08002485void CompilerDriver::Compile(jobject class_loader,
2486 const std::vector<const DexFile*>& dex_files,
2487 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002488 if (kDebugProfileGuidedCompilation) {
2489 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2490 ((profile_compilation_info_ == nullptr)
2491 ? "null"
2492 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002493 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002494
2495 DCHECK(current_dex_to_dex_methods_ == nullptr);
2496 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002497 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002498 CompileDexFile(class_loader,
2499 *dex_file,
2500 dex_files,
2501 parallel_thread_pool_.get(),
2502 parallel_thread_count_,
2503 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002504 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2505 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2506 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002507 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002508 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002509
2510 ArrayRef<DexFileMethodSet> dex_to_dex_references;
2511 {
2512 // From this point on, we shall not modify dex_to_dex_references_, so
2513 // just grab a reference to it that we use without holding the mutex.
2514 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
2515 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
2516 }
2517 for (const auto& method_set : dex_to_dex_references) {
2518 current_dex_to_dex_methods_ = &method_set.GetMethodIndexes();
2519 CompileDexFile(class_loader,
2520 method_set.GetDexFile(),
2521 dex_files,
2522 parallel_thread_pool_.get(),
2523 parallel_thread_count_,
2524 timings);
2525 }
2526 current_dex_to_dex_methods_ = nullptr;
2527
Andreas Gampe8d295f82015-01-20 14:50:21 -08002528 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002529}
2530
Mathieu Chartier90443472015-07-16 20:32:27 -07002531class CompileClassVisitor : public CompilationVisitor {
2532 public:
2533 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2534
2535 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2536 ATRACE_CALL();
2537 const DexFile& dex_file = *manager_->GetDexFile();
2538 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2539 ClassLinker* class_linker = manager_->GetClassLinker();
2540 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002541 ClassReference ref(&dex_file, class_def_index);
2542 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2543 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002544 return;
2545 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002546 // Use a scoped object access to perform to the quick SkipClass check.
2547 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2548 ScopedObjectAccess soa(Thread::Current());
2549 StackHandleScope<3> hs(soa.Self());
2550 Handle<mirror::ClassLoader> class_loader(
2551 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2552 Handle<mirror::Class> klass(
2553 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2554 Handle<mirror::DexCache> dex_cache;
2555 if (klass.Get() == nullptr) {
2556 soa.Self()->AssertPendingException();
2557 soa.Self()->ClearException();
2558 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2559 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2560 return;
2561 } else {
2562 dex_cache = hs.NewHandle(klass->GetDexCache());
2563 }
2564
Mathieu Chartier90443472015-07-16 20:32:27 -07002565 const uint8_t* class_data = dex_file.GetClassData(class_def);
2566 if (class_data == nullptr) {
2567 // empty class, probably a marker interface
2568 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002569 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002570
Mathieu Chartier736b5602015-09-02 14:54:11 -07002571 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002572 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002573
Mathieu Chartier90443472015-07-16 20:32:27 -07002574 CompilerDriver* const driver = manager_->GetCompiler();
2575
2576 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002577 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002578 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002579
Mathieu Chartier90443472015-07-16 20:32:27 -07002580 ClassDataItemIterator it(dex_file, class_data);
2581 // Skip fields
2582 while (it.HasNextStaticField()) {
2583 it.Next();
2584 }
2585 while (it.HasNextInstanceField()) {
2586 it.Next();
2587 }
2588
2589 bool compilation_enabled = driver->IsClassToCompile(
2590 dex_file.StringByTypeIdx(class_def.class_idx_));
2591
2592 // Compile direct methods
2593 int64_t previous_direct_method_idx = -1;
2594 while (it.HasNextDirectMethod()) {
2595 uint32_t method_idx = it.GetMemberIndex();
2596 if (method_idx == previous_direct_method_idx) {
2597 // smali can create dex files with two encoded_methods sharing the same method_idx
2598 // http://code.google.com/p/smali/issues/detail?id=119
2599 it.Next();
2600 continue;
2601 }
2602 previous_direct_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002603 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002604 it.GetMethodInvokeType(class_def), class_def_index,
2605 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002606 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002607 it.Next();
2608 }
2609 // Compile virtual methods
2610 int64_t previous_virtual_method_idx = -1;
2611 while (it.HasNextVirtualMethod()) {
2612 uint32_t method_idx = it.GetMemberIndex();
2613 if (method_idx == previous_virtual_method_idx) {
2614 // smali can create dex files with two encoded_methods sharing the same method_idx
2615 // http://code.google.com/p/smali/issues/detail?id=119
2616 it.Next();
2617 continue;
2618 }
2619 previous_virtual_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002620 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002621 it.GetMethodInvokeType(class_def), class_def_index,
2622 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002623 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002624 it.Next();
2625 }
2626 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002627 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002628
2629 private:
2630 const ParallelCompilationManager* const manager_;
2631};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002632
Andreas Gampeace0dc12016-01-20 13:33:13 -08002633void CompilerDriver::CompileDexFile(jobject class_loader,
2634 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002635 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002636 ThreadPool* thread_pool,
2637 size_t thread_count,
2638 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002639 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002640 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002641 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002642 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002643 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002644}
2645
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002646void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2647 CompiledMethod* const compiled_method,
2648 size_t non_relative_linker_patch_count) {
2649 DCHECK(GetCompiledMethod(method_ref) == nullptr)
2650 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
2651 {
2652 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2653 compiled_methods_.Put(method_ref, compiled_method);
2654 non_relative_linker_patch_count_ += non_relative_linker_patch_count;
Ian Rogersa4a3f402014-10-20 18:10:34 -07002655 }
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002656 DCHECK(GetCompiledMethod(method_ref) != nullptr)
2657 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002658}
2659
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002660void CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2661 CompiledMethod* compiled_method = nullptr;
2662 {
2663 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2664 auto it = compiled_methods_.find(method_ref);
2665 if (it != compiled_methods_.end()) {
2666 compiled_method = it->second;
2667 compiled_methods_.erase(it);
2668 }
2669 }
2670 if (compiled_method != nullptr) {
2671 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, compiled_method);
2672 }
2673}
2674
Brian Carlstrom7940e442013-07-12 13:46:57 -07002675CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
2676 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2677 ClassTable::const_iterator it = compiled_classes_.find(ref);
2678 if (it == compiled_classes_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002679 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002680 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002681 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002682 return it->second;
2683}
2684
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002685void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2686 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2687 auto it = compiled_classes_.find(ref);
2688 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2689 // An entry doesn't exist or the status is lower than the new status.
2690 if (it != compiled_classes_.end()) {
2691 CHECK_GT(status, it->second->GetStatus());
2692 delete it->second;
2693 }
2694 switch (status) {
2695 case mirror::Class::kStatusNotReady:
2696 case mirror::Class::kStatusError:
2697 case mirror::Class::kStatusRetryVerificationAtRuntime:
2698 case mirror::Class::kStatusVerified:
2699 case mirror::Class::kStatusInitialized:
Mathieu Chartiera8077802016-03-16 19:08:31 -07002700 case mirror::Class::kStatusResolved:
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002701 break; // Expected states.
2702 default:
2703 LOG(FATAL) << "Unexpected class status for class "
2704 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2705 << " of " << status;
2706 }
2707 CompiledClass* compiled_class = new CompiledClass(status);
2708 compiled_classes_.Overwrite(ref, compiled_class);
2709 }
2710}
2711
Brian Carlstrom7940e442013-07-12 13:46:57 -07002712CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2713 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2714 MethodTable::const_iterator it = compiled_methods_.find(ref);
2715 if (it == compiled_methods_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002716 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002717 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002718 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002719 return it->second;
2720}
2721
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002722bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2723 uint16_t class_def_idx,
2724 const DexFile& dex_file) const {
2725 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2726 if (verified_method != nullptr) {
2727 return !verified_method->HasVerificationFailures();
2728 }
2729
2730 // If we can't find verification metadata, check if this is a system class (we trust that system
2731 // classes have their methods verified). If it's not, be conservative and assume the method
2732 // has not been verified successfully.
2733
2734 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2735 // even if methods are not found in the verification cache.
2736 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2737 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2738 Thread* self = Thread::Current();
2739 ScopedObjectAccess soa(self);
2740 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2741 if (!is_system_class) {
2742 self->ClearException();
2743 }
2744 return is_system_class;
2745}
2746
Vladimir Markof4da6752014-08-01 19:04:18 +01002747size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
2748 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2749 return non_relative_linker_patch_count_;
2750}
2751
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002752void CompilerDriver::SetRequiresConstructorBarrier(Thread* self,
2753 const DexFile* dex_file,
2754 uint16_t class_def_index,
2755 bool requires) {
2756 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2757 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002758}
2759
Mathieu Chartier371bd832016-04-07 10:19:48 -07002760bool CompilerDriver::RequiresConstructorBarrier(Thread* self,
2761 const DexFile* dex_file,
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002762 uint16_t class_def_index) {
2763 ClassReference class_ref(dex_file, class_def_index);
2764 {
2765 ReaderMutexLock mu(self, requires_constructor_barrier_lock_);
2766 auto it = requires_constructor_barrier_.find(class_ref);
2767 if (it != requires_constructor_barrier_.end()) {
2768 return it->second;
2769 }
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002770 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002771 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2772 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index);
2773 requires_constructor_barrier_.emplace(class_ref, requires);
2774 return requires;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002775}
2776
Andreas Gampe8d295f82015-01-20 14:50:21 -08002777std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002778 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002779 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002780 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002781 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002782 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002783#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002784 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002785 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2786 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002787 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2788 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002789#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002790 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002791 return oss.str();
2792}
2793
Jeff Haodcdc85b2015-12-04 14:06:18 -08002794bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
2795 const DexFile* inlined_into) const {
2796 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
2797 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00002798 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
2799 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002800 return false;
2801 }
2802
2803 return true;
2804}
2805
Andreas Gampeace0dc12016-01-20 13:33:13 -08002806void CompilerDriver::InitializeThreadPools() {
2807 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2808 parallel_thread_pool_.reset(
2809 new ThreadPool("Compiler driver thread pool", parallel_count));
2810 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2811}
2812
2813void CompilerDriver::FreeThreadPools() {
2814 parallel_thread_pool_.reset();
2815 single_thread_pool_.reset();
2816}
2817
Brian Carlstrom7940e442013-07-12 13:46:57 -07002818} // namespace art