blob: 2ead092714b684dc9a482d05e809a509b36f9db4 [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 bool boot_image,
Mathieu Chartier91288d82016-04-28 09:44:54 -0700361 bool app_image,
Vladimir Marko944da602016-02-19 12:27:55 +0000362 std::unordered_set<std::string>* image_classes,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800363 std::unordered_set<std::string>* compiled_classes,
364 std::unordered_set<std::string>* compiled_methods,
Vladimir Marko944da602016-02-19 12:27:55 +0000365 size_t thread_count,
366 bool dump_stats,
367 bool dump_passes,
368 CumulativeLogger* timer,
369 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200370 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000371 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800372 verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000373 method_inliner_map_(method_inliner_map),
Ian Rogers72d32622014-05-06 16:20:11 -0700374 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700375 compiler_kind_(compiler_kind),
Artem Serovba6b6792016-08-15 14:22:07 +0100376 instruction_set_(instruction_set == kArm ? kThumb2: instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700377 instruction_set_features_(instruction_set_features),
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700378 requires_constructor_barrier_lock_("constructor barrier lock"),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700379 compiled_classes_lock_("compiled classes lock"),
380 compiled_methods_lock_("compiled method lock"),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800381 compiled_methods_(MethodTable::key_compare()),
Vladimir Markof4da6752014-08-01 19:04:18 +0100382 non_relative_linker_patch_count_(0u),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800383 boot_image_(boot_image),
Mathieu Chartier91288d82016-04-28 09:44:54 -0700384 app_image_(app_image),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700385 image_classes_(image_classes),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800386 classes_to_compile_(compiled_classes),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700387 methods_to_compile_(compiled_methods),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800388 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800389 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700390 stats_(new AOTCompilationStats),
391 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000392 dump_passes_(dump_passes),
393 timings_logger_(timer),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700394 compiler_context_(nullptr),
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700395 support_boot_image_fixup_(instruction_set != kMips64),
Vladimir Markod1eaf0d2015-10-29 12:18:29 +0000396 dex_files_for_oat_file_(nullptr),
Calin Juravle998c2162015-12-21 15:39:33 +0200397 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000398 profile_compilation_info_(profile_compilation_info),
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100399 max_arena_alloc_(0),
400 dex_to_dex_references_lock_("dex-to-dex references lock"),
401 dex_to_dex_references_(),
402 current_dex_to_dex_methods_(nullptr) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800403 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom6449c622014-02-10 23:48:36 -0800404 DCHECK(method_inliner_map_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700405
Ian Rogers72d32622014-05-06 16:20:11 -0700406 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700407
Mathieu Chartiera8077802016-03-16 19:08:31 -0700408 if (compiler_options->VerifyOnlyProfile()) {
409 CHECK(profile_compilation_info_ != nullptr) << "Requires profile";
410 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800411 if (boot_image_) {
412 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image";
413 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700414}
415
416CompilerDriver::~CompilerDriver() {
417 Thread* self = Thread::Current();
418 {
419 MutexLock mu(self, compiled_classes_lock_);
420 STLDeleteValues(&compiled_classes_);
421 }
422 {
423 MutexLock mu(self, compiled_methods_lock_);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800424 for (auto& pair : compiled_methods_) {
425 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, pair.second);
426 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427 }
Ian Rogers72d32622014-05-06 16:20:11 -0700428 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700429}
430
Vladimir Marko35831e82015-09-11 11:59:18 +0100431
Ian Rogersdd7624d2014-03-14 17:43:00 -0700432#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700433 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700434 return CreateTrampoline64(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700435 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700436 } else { \
437 return CreateTrampoline32(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700438 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700439 }
440
Vladimir Marko93205e32016-04-13 11:59:46 +0100441std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700442 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700443}
444
Vladimir Marko93205e32016-04-13 11:59:46 +0100445std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
446 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700447 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800448}
449
Vladimir Marko93205e32016-04-13 11:59:46 +0100450std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
451 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700452 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700453}
454
Vladimir Marko93205e32016-04-13 11:59:46 +0100455std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
456 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700457 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700458}
459
Vladimir Marko93205e32016-04-13 11:59:46 +0100460std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
461 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700462 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700463}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700464#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700465
466void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700467 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800468 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700469 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800470
471 InitializeThreadPools();
472
Andreas Gampe8d295f82015-01-20 14:50:21 -0800473 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
Andreas Gampe740667a2015-09-15 17:55:06 -0700474 // Precompile:
475 // 1) Load image classes
476 // 2) Resolve all classes
477 // 3) Attempt to verify all classes
478 // 4) Attempt to initialize image classes, and trivially initialized classes
Andreas Gampeace0dc12016-01-20 13:33:13 -0800479 PreCompile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700480 // Compile:
481 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
482 // compilation.
483 if (!GetCompilerOptions().VerifyAtRuntime()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800484 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700485 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700486 if (dump_stats_) {
487 stats_->Dump();
488 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800489
490 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700491}
492
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700493static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
494 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
495 const DexFile& dex_file, const DexFile::ClassDef& class_def)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700496 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800497 auto* const runtime = Runtime::Current();
Calin Juravleffc87072016-04-20 14:22:09 +0100498 if (runtime->UseJitCompilation() || driver.GetCompilerOptions().VerifyAtRuntime()) {
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700499 // Verify at runtime shouldn't dex to dex since we didn't resolve of verify.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700500 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800501 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700502 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800503 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800504 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700505 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700506 CHECK(self->IsExceptionPending());
507 self->ClearException();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700508 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700509 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700510 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
511 // references with actual offsets. We cannot re-verify such instructions.
512 //
513 // We store the verification information in the class status in the oat file, which the linker
514 // can validate (checksums) and use to skip load-time verification. It is thus safe to
515 // optimize when a class has been fully verified before.
516 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200517 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700518 return optimizer::DexToDexCompilationLevel::kOptimize;
Sebastien Hertz75021222013-07-16 18:34:50 +0200519 } else if (klass->IsCompileTimeVerified()) {
520 // Class verification has soft-failed. Anyway, ensure at least correctness.
521 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700522 return optimizer::DexToDexCompilationLevel::kRequired;
Sebastien Hertz75021222013-07-16 18:34:50 +0200523 } else {
524 // Class verification has failed: do not run DEX-to-DEX compilation.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700525 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
526 }
527}
528
529static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
530 Thread* self,
531 const CompilerDriver& driver,
532 jobject jclass_loader,
533 const DexFile& dex_file,
534 const DexFile::ClassDef& class_def) {
535 ScopedObjectAccess soa(self);
536 StackHandleScope<1> hs(soa.Self());
537 Handle<mirror::ClassLoader> class_loader(
538 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
539 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
540}
541
542// Does the runtime for the InstructionSet provide an implementation returned by
543// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
544static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
545 switch (isa) {
546 case kArm:
547 case kArm64:
548 case kThumb2:
549 case kMips:
550 case kMips64:
551 case kX86:
552 case kX86_64: return true;
553 default: return false;
554 }
555}
556
557static void CompileMethod(Thread* self,
558 CompilerDriver* driver,
559 const DexFile::CodeItem* code_item,
560 uint32_t access_flags,
561 InvokeType invoke_type,
562 uint16_t class_def_idx,
563 uint32_t method_idx,
564 jobject class_loader,
565 const DexFile& dex_file,
566 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700567 bool compilation_enabled,
568 Handle<mirror::DexCache> dex_cache)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700569 REQUIRES(!driver->compiled_methods_lock_) {
570 DCHECK(driver != nullptr);
571 CompiledMethod* compiled_method = nullptr;
572 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
573 MethodReference method_ref(&dex_file, method_idx);
574
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100575 if (driver->GetCurrentDexToDexMethods() != nullptr) {
576 // This is the second pass when we dex-to-dex compile previously marked methods.
577 // TODO: Refactor the compilation to avoid having to distinguish the two passes
578 // here. That should be done on a higher level. http://b/29089975
579 if (driver->GetCurrentDexToDexMethods()->IsBitSet(method_idx)) {
580 const VerifiedMethod* verified_method =
581 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
582 // Do not optimize if a VerifiedMethod is missing. SafeCast elision,
583 // for example, relies on it.
584 compiled_method = optimizer::ArtCompileDEX(
585 driver,
586 code_item,
587 access_flags,
588 invoke_type,
589 class_def_idx,
590 method_idx,
591 class_loader,
592 dex_file,
593 (verified_method != nullptr)
594 ? dex_to_dex_compilation_level
595 : optimizer::DexToDexCompilationLevel::kRequired);
596 }
597 } else if ((access_flags & kAccNative) != 0) {
Igor Murashkin9aa9fa22016-09-26 10:10:17 -0700598 const InstructionSet instruction_set = driver->GetInstructionSet();
599 const bool use_generic_jni =
600 // Are we extracting only and have support for generic JNI down calls?
601 (!driver->GetCompilerOptions().IsJniCompilationEnabled() &&
602 InstructionSetHasGenericJniStub(instruction_set)) ||
603 // Always punt to generic JNI for MIPS because of no support for @CriticalNative. b/31743474
604 (instruction_set == kMips || instruction_set == kMips64);
605 if (use_generic_jni) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700606 // Leaving this empty will trigger the generic JNI version
607 } else {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700608 // Look-up the ArtMethod associated with this code_item (if any)
609 // -- It is later used to lookup any [optimization] annotations for this method.
610 ScopedObjectAccess soa(self);
611 StackHandleScope<1> hs(soa.Self());
612 Handle<mirror::ClassLoader> class_loader_handle(hs.NewHandle(
613 soa.Decode<mirror::ClassLoader*>(class_loader)));
614
615 // TODO: Lookup annotation from DexFile directly without resolving method.
616 ArtMethod* method =
617 Runtime::Current()->GetClassLinker()->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
618 dex_file,
619 method_idx,
620 dex_cache,
621 class_loader_handle,
622 /* referrer */ nullptr,
623 invoke_type);
624
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700625 // Query any JNI optimization annotations such as @FastNative or @CriticalNative.
626 Compiler::JniOptimizationFlags optimization_flags = Compiler::kNone;
627 if (UNLIKELY(method == nullptr)) {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700628 // Failed method resolutions happen very rarely, e.g. ancestor class cannot be resolved.
629 DCHECK(self->IsExceptionPending());
630 self->ClearException();
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700631 } else if (method->IsAnnotatedWithFastNative()) {
632 // TODO: Will no longer need this CHECK once we have verifier checking this.
633 CHECK(!method->IsAnnotatedWithCriticalNative());
634 optimization_flags = Compiler::kFastNative;
635 } else if (method->IsAnnotatedWithCriticalNative()) {
636 // TODO: Will no longer need this CHECK once we have verifier checking this.
637 CHECK(!method->IsAnnotatedWithFastNative());
638 optimization_flags = Compiler::kCriticalNative;
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700639 }
640
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700641 compiled_method = driver->GetCompiler()->JniCompile(access_flags,
642 method_idx,
643 dex_file,
644 optimization_flags);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700645 CHECK(compiled_method != nullptr);
646 }
647 } else if ((access_flags & kAccAbstract) != 0) {
648 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000649 } else {
Andreas Gampe0760a812015-08-26 17:12:51 -0700650 const VerifiedMethod* verified_method =
651 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700652 bool compile = compilation_enabled &&
653 // Basic checks, e.g., not <clinit>.
654 driver->GetVerificationResults()
655 ->IsCandidateForCompilation(method_ref, access_flags) &&
656 // Did not fail to create VerifiedMethod metadata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700657 verified_method != nullptr &&
658 // Do not have failures that should punt to the interpreter.
659 !verified_method->HasRuntimeThrow() &&
660 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700661 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700662 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000663 driver->IsMethodToCompile(method_ref) &&
664 driver->ShouldCompileBasedOnProfile(method_ref);
665
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700666 if (compile) {
667 // NOTE: if compiler declines to compile this method, it will return null.
668 compiled_method = driver->GetCompiler()->Compile(code_item, access_flags, invoke_type,
669 class_def_idx, method_idx, class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700670 dex_file, dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700671 }
672 if (compiled_method == nullptr &&
673 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100674 DCHECK(!Runtime::Current()->UseJitCompilation());
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700675 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100676 driver->MarkForDexToDexCompilation(self, method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700677 }
678 }
679 if (kTimeCompileMethod) {
680 uint64_t duration_ns = NanoTime() - start_ns;
681 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
682 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
683 << " took " << PrettyDuration(duration_ns);
684 }
685 }
686
687 if (compiled_method != nullptr) {
688 // Count non-relative linker patches.
689 size_t non_relative_linker_patch_count = 0u;
690 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
691 if (!patch.IsPcRelative()) {
692 ++non_relative_linker_patch_count;
693 }
694 }
695 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
696 // When compiling with PIC, there should be zero non-relative linker patches
697 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
698
699 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
700 }
701
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700702 if (self->IsExceptionPending()) {
703 ScopedObjectAccess soa(self);
704 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
705 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200706 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700707}
708
Mathieu Chartiere401d142015-04-22 13:56:20 -0700709void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700710 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700711 jobject jclass_loader;
712 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700713 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800714 uint32_t method_idx = method->GetDexMethodIndex();
715 uint32_t access_flags = method->GetAccessFlags();
716 InvokeType invoke_type = method->GetInvokeType();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700717 StackHandleScope<1> hs(self);
718 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700719 {
720 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800721 ScopedLocalRef<jobject> local_class_loader(
722 soa.Env(), soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700723 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
724 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700725 dex_file = method->GetDexFile();
726 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700727 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800728 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700729
730 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700731 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700732
733 std::vector<const DexFile*> dex_files;
734 dex_files.push_back(dex_file);
735
Andreas Gampeace0dc12016-01-20 13:33:13 -0800736 InitializeThreadPools();
737
738 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700739
Brian Carlstrom7940e442013-07-12 13:46:57 -0700740 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700741 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
742 GetDexToDexCompilationLevel(self,
743 *this,
744 jclass_loader,
745 *dex_file,
746 dex_file->GetClassDef(class_def_idx));
747
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100748 DCHECK(current_dex_to_dex_methods_ == nullptr);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700749 CompileMethod(self,
750 this,
751 code_item,
752 access_flags,
753 invoke_type,
754 class_def_idx,
755 method_idx,
756 jclass_loader,
757 *dex_file,
758 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700759 true,
760 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700761
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100762 ArrayRef<DexFileMethodSet> dex_to_dex_references;
763 {
764 // From this point on, we shall not modify dex_to_dex_references_, so
765 // just grab a reference to it that we use without holding the mutex.
766 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
767 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
768 }
769 if (!dex_to_dex_references.empty()) {
770 DCHECK_EQ(dex_to_dex_references.size(), 1u);
771 DCHECK(&dex_to_dex_references[0].GetDexFile() == dex_file);
772 current_dex_to_dex_methods_ = &dex_to_dex_references.front().GetMethodIndexes();
773 DCHECK(current_dex_to_dex_methods_->IsBitSet(method_idx));
774 DCHECK_EQ(current_dex_to_dex_methods_->NumSetBits(), 1u);
775 CompileMethod(self,
776 this,
777 code_item,
778 access_flags,
779 invoke_type,
780 class_def_idx,
781 method_idx,
782 jclass_loader,
783 *dex_file,
784 dex_to_dex_compilation_level,
785 true,
786 dex_cache);
787 current_dex_to_dex_methods_ = nullptr;
788 }
789
Andreas Gampeace0dc12016-01-20 13:33:13 -0800790 FreeThreadPools();
791
Brian Carlstrom7940e442013-07-12 13:46:57 -0700792 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800793}
794
Andreas Gampeace0dc12016-01-20 13:33:13 -0800795void CompilerDriver::Resolve(jobject class_loader,
796 const std::vector<const DexFile*>& dex_files,
797 TimingLogger* timings) {
798 // Resolution allocates classes and needs to run single-threaded to be deterministic.
799 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
800 ThreadPool* resolve_thread_pool = force_determinism
801 ? single_thread_pool_.get()
802 : parallel_thread_pool_.get();
803 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
804
Brian Carlstrom7940e442013-07-12 13:46:57 -0700805 for (size_t i = 0; i != dex_files.size(); ++i) {
806 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700807 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800808 ResolveDexFile(class_loader,
809 *dex_file,
810 dex_files,
811 resolve_thread_pool,
812 resolve_thread_count,
813 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700814 }
815}
816
Andreas Gampeace0dc12016-01-20 13:33:13 -0800817// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
818// this is single-threaded for simplicity.
819// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
820// stable order.
821
822static void ResolveConstStrings(CompilerDriver* driver,
823 const DexFile& dex_file,
824 const DexFile::CodeItem* code_item) {
825 if (code_item == nullptr) {
826 // Abstract or native method.
827 return;
828 }
829
830 const uint16_t* code_ptr = code_item->insns_;
831 const uint16_t* code_end = code_item->insns_ + code_item->insns_size_in_code_units_;
832
833 while (code_ptr < code_end) {
834 const Instruction* inst = Instruction::At(code_ptr);
835 switch (inst->Opcode()) {
836 case Instruction::CONST_STRING: {
837 uint32_t string_index = inst->VRegB_21c();
838 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
839 break;
840 }
841 case Instruction::CONST_STRING_JUMBO: {
842 uint32_t string_index = inst->VRegB_31c();
843 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
844 break;
845 }
846
847 default:
848 break;
849 }
850
851 code_ptr += inst->SizeInCodeUnits();
852 }
853}
854
855static void ResolveConstStrings(CompilerDriver* driver,
856 const std::vector<const DexFile*>& dex_files,
857 TimingLogger* timings) {
858 for (const DexFile* dex_file : dex_files) {
859 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
860
861 size_t class_def_count = dex_file->NumClassDefs();
862 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
863 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
864
865 const uint8_t* class_data = dex_file->GetClassData(class_def);
866 if (class_data == nullptr) {
867 // empty class, probably a marker interface
868 continue;
869 }
870
871 ClassDataItemIterator it(*dex_file, class_data);
872 // Skip fields
873 while (it.HasNextStaticField()) {
874 it.Next();
875 }
876 while (it.HasNextInstanceField()) {
877 it.Next();
878 }
879
880 bool compilation_enabled = driver->IsClassToCompile(
881 dex_file->StringByTypeIdx(class_def.class_idx_));
882 if (!compilation_enabled) {
883 // Compilation is skipped, do not resolve const-string in code of this class.
884 // TODO: Make sure that inlining honors this.
885 continue;
886 }
887
888 // Direct methods.
889 int64_t previous_direct_method_idx = -1;
890 while (it.HasNextDirectMethod()) {
891 uint32_t method_idx = it.GetMemberIndex();
892 if (method_idx == previous_direct_method_idx) {
893 // smali can create dex files with two encoded_methods sharing the same method_idx
894 // http://code.google.com/p/smali/issues/detail?id=119
895 it.Next();
896 continue;
897 }
898 previous_direct_method_idx = method_idx;
899 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
900 it.Next();
901 }
902 // Virtual methods.
903 int64_t previous_virtual_method_idx = -1;
904 while (it.HasNextVirtualMethod()) {
905 uint32_t method_idx = it.GetMemberIndex();
906 if (method_idx == previous_virtual_method_idx) {
907 // smali can create dex files with two encoded_methods sharing the same method_idx
908 // http://code.google.com/p/smali/issues/detail?id=119
909 it.Next();
910 continue;
911 }
912 previous_virtual_method_idx = method_idx;
913 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
914 it.Next();
915 }
916 DCHECK(!it.HasNext());
917 }
918 }
919}
920
921inline void CompilerDriver::CheckThreadPools() {
922 DCHECK(parallel_thread_pool_ != nullptr);
923 DCHECK(single_thread_pool_ != nullptr);
924}
925
926void CompilerDriver::PreCompile(jobject class_loader,
927 const std::vector<const DexFile*>& dex_files,
928 TimingLogger* timings) {
929 CheckThreadPools();
930
Brian Carlstrom7940e442013-07-12 13:46:57 -0700931 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800932 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700933
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700934 const bool verification_enabled = compiler_options_->IsVerificationEnabled();
935 const bool never_verify = compiler_options_->NeverVerify();
Mathieu Chartiera8077802016-03-16 19:08:31 -0700936 const bool verify_only_profile = compiler_options_->VerifyOnlyProfile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700937
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700938 // We need to resolve for never_verify since it needs to run dex to dex to add the
939 // RETURN_VOID_NO_BARRIER.
Mathieu Chartiera8077802016-03-16 19:08:31 -0700940 // Let the verifier resolve as needed for the verify_only_profile case.
941 if ((never_verify || verification_enabled) && !verify_only_profile) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800942 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700943 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
944 }
945
946 if (never_verify) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800947 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800948 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700949 }
950
951 if (!verification_enabled) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700952 return;
953 }
954
Andreas Gampeace0dc12016-01-20 13:33:13 -0800955 if (GetCompilerOptions().IsForceDeterminism() && IsBootImage()) {
956 // Resolve strings from const-string. Do this now to have a deterministic image.
957 ResolveConstStrings(this, dex_files, timings);
958 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
959 }
960
961 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800962 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700963
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800964 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
965 LOG(FATAL) << "Had a hard failure verifying all classes, and was asked to abort in such "
966 << "situations. Please check the log.";
967 }
968
Andreas Gampeace0dc12016-01-20 13:33:13 -0800969 InitializeClasses(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800970 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700971
972 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800973 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700974}
975
Ian Rogersdfb325e2013-10-30 01:00:44 -0700976bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800977 if (image_classes_ != nullptr) {
978 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -0700979 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700980 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800981 // No set of image classes, assume we include all the classes.
982 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
983 return !IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700984}
985
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800986bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700987 if (classes_to_compile_ == nullptr) {
988 return true;
989 }
990 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800991}
992
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700993bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700994 if (methods_to_compile_ == nullptr) {
995 return true;
996 }
997
998 std::string tmp = PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
999 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
1000}
1001
Calin Juravle226501b2015-12-11 14:41:31 +00001002bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
1003 if (profile_compilation_info_ == nullptr) {
1004 // If we miss profile information it means that we don't do a profile guided compilation.
1005 // Return true, and let the other filters decide if the method should be compiled.
1006 return true;
1007 }
1008 bool result = profile_compilation_info_->ContainsMethod(method_ref);
1009
1010 if (kDebugProfileGuidedCompilation) {
1011 LOG(INFO) << "[ProfileGuidedCompilation] "
1012 << (result ? "Compiled" : "Skipped") << " method:"
1013 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
1014 }
1015 return result;
1016}
1017
Mathieu Chartiera8077802016-03-16 19:08:31 -07001018bool CompilerDriver::ShouldVerifyClassBasedOnProfile(const DexFile& dex_file,
1019 uint16_t class_idx) const {
1020 if (!compiler_options_->VerifyOnlyProfile()) {
1021 // No profile, verify everything.
1022 return true;
1023 }
1024 DCHECK(profile_compilation_info_ != nullptr);
1025 bool result = profile_compilation_info_->ContainsClass(dex_file, class_idx);
1026 if (kDebugProfileGuidedCompilation) {
1027 LOG(INFO) << "[ProfileGuidedCompilation] "
1028 << (result ? "Verified" : "Skipped") << " method:"
1029 << dex_file.GetClassDescriptor(dex_file.GetClassDef(class_idx));
1030 }
1031 return result;
1032}
1033
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001034class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
1035 public:
Chih-Hung Hsieh471118e2016-04-29 14:27:41 -07001036 explicit ResolveCatchBlockExceptionsClassVisitor(
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001037 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve)
1038 : exceptions_to_resolve_(exceptions_to_resolve) {}
1039
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001040 virtual bool operator()(mirror::Class* c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001041 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Alex Lighte64300b2015-12-15 15:02:47 -08001042 for (auto& m : c->GetMethods(pointer_size)) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001043 ResolveExceptionsForMethod(&m, pointer_size);
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001044 }
1045 return true;
1046 }
1047
1048 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001049 void ResolveExceptionsForMethod(ArtMethod* method_handle, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001050 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001051 const DexFile::CodeItem* code_item = method_handle->GetCodeItem();
1052 if (code_item == nullptr) {
1053 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -07001054 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001055 if (code_item->tries_size_ == 0) {
1056 return; // nothing to process
1057 }
1058 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
1059 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
1060 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1061 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
1062 bool has_catch_all = false;
1063 if (encoded_catch_handler_size <= 0) {
1064 encoded_catch_handler_size = -encoded_catch_handler_size;
1065 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001066 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001067 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
1068 uint16_t encoded_catch_handler_handlers_type_idx =
1069 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1070 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko05792b92015-08-03 11:56:49 +01001071 if (!method_handle->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx,
1072 pointer_size)) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001073 exceptions_to_resolve_.emplace(encoded_catch_handler_handlers_type_idx,
1074 method_handle->GetDexFile());
1075 }
1076 // ignore address associated with catch handler
1077 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1078 }
1079 if (has_catch_all) {
1080 // ignore catch all address
1081 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1082 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001083 }
1084 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001085
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001086 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve_;
1087};
1088
1089class RecordImageClassesVisitor : public ClassVisitor {
1090 public:
1091 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
1092 : image_classes_(image_classes) {}
1093
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001094 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001095 std::string temp;
1096 image_classes_->insert(klass->GetDescriptor(&temp));
1097 return true;
1098 }
1099
1100 private:
1101 std::unordered_set<std::string>* const image_classes_;
1102};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001103
1104// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001105void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001106 CHECK(timings != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001107 if (!IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001108 return;
1109 }
1110
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001111 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001112 // Make a first class to load all classes explicitly listed in the file
1113 Thread* self = Thread::Current();
1114 ScopedObjectAccess soa(self);
1115 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001116 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001117 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001118 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001119 StackHandleScope<1> hs(self);
1120 Handle<mirror::Class> klass(
1121 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001122 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001123 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001124 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001125 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001126 } else {
1127 ++it;
1128 }
1129 }
1130
1131 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1132 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1133 // Do this here so that exception classes appear to have been specified image classes.
Ian Rogers700a4022014-05-19 16:49:03 -07001134 std::set<std::pair<uint16_t, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001135 StackHandleScope<1> hs(self);
1136 Handle<mirror::Class> java_lang_Throwable(
1137 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001138 do {
1139 unresolved_exception_types.clear();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001140 ResolveCatchBlockExceptionsClassVisitor visitor(unresolved_exception_types);
1141 class_linker->VisitClasses(&visitor);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001142 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
1143 uint16_t exception_type_idx = exception_type.first;
1144 const DexFile* dex_file = exception_type.second;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001145 StackHandleScope<2> hs2(self);
Mathieu Chartierf284d442016-06-02 11:48:30 -07001146 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file,
1147 nullptr)));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001148 Handle<mirror::Class> klass(hs2.NewHandle(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001149 class_linker->ResolveType(*dex_file,
1150 exception_type_idx,
1151 dex_cache,
1152 ScopedNullHandle<mirror::ClassLoader>())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001153 if (klass.Get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001154 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1155 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1156 LOG(FATAL) << "Failed to resolve class " << descriptor;
1157 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001158 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001159 }
1160 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1161 // more are found
1162 } while (!unresolved_exception_types.empty());
1163
1164 // We walk the roots looking for classes so that we'll pick up the
1165 // above classes plus any classes them depend on such super
1166 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001167 RecordImageClassesVisitor visitor(image_classes_.get());
1168 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001169
1170 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001171}
1172
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001173static void MaybeAddToImageClasses(Handle<mirror::Class> c,
1174 std::unordered_set<std::string>* image_classes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001175 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001176 Thread* self = Thread::Current();
1177 StackHandleScope<1> hs(self);
1178 // Make a copy of the handle so that we don't clobber it doing Assign.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001179 MutableHandle<mirror::Class> klass(hs.NewHandle(c.Get()));
Ian Rogers1ff3c982014-08-12 02:30:58 -07001180 std::string temp;
Andreas Gampe542451c2016-07-26 09:02:02 -07001181 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001182 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001183 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001184 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1185 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001186 if (!result.second) { // Previously inserted.
1187 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001188 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001189 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Mathieu Chartierf8322842014-05-16 10:59:25 -07001190 for (size_t i = 0; i < klass->NumDirectInterfaces(); ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001191 StackHandleScope<1> hs2(self);
1192 MaybeAddToImageClasses(hs2.NewHandle(mirror::Class::GetDirectInterface(self, klass, i)),
Mathieu Chartierf8322842014-05-16 10:59:25 -07001193 image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001194 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001195 for (auto& m : c->GetVirtualMethods(pointer_size)) {
Alex Light36121492016-02-22 13:43:29 -08001196 StackHandleScope<1> hs2(self);
1197 MaybeAddToImageClasses(hs2.NewHandle(m.GetDeclaringClass()), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001198 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001199 if (klass->IsArrayClass()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001200 StackHandleScope<1> hs2(self);
1201 MaybeAddToImageClasses(hs2.NewHandle(klass->GetComponentType()), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001202 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001203 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001204 }
1205}
1206
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001207// Keeps all the data for the update together. Also doubles as the reference visitor.
1208// Note: we can use object pointers because we suspend all threads.
1209class ClinitImageUpdate {
1210 public:
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001211 static ClinitImageUpdate* Create(std::unordered_set<std::string>* image_class_descriptors,
1212 Thread* self, ClassLinker* linker, std::string* error_msg) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001213 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(image_class_descriptors, self,
1214 linker));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001215 if (res->dex_cache_class_ == nullptr) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001216 *error_msg = "Could not find DexCache class.";
1217 return nullptr;
1218 }
1219
1220 return res.release();
1221 }
1222
1223 ~ClinitImageUpdate() {
1224 // Allow others to suspend again.
1225 self_->EndAssertNoThreadSuspension(old_cause_);
1226 }
1227
1228 // Visitor for VisitReferences.
1229 void operator()(mirror::Object* object, MemberOffset field_offset, bool /* is_static */) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001230 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001231 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1232 if (ref != nullptr) {
1233 VisitClinitClassesObject(ref);
1234 }
1235 }
1236
1237 // java.lang.Reference visitor for VisitReferences.
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001238 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref ATTRIBUTE_UNUSED)
1239 const {}
1240
1241 // Ignore class native roots.
1242 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1243 const {}
1244 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001245
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001246 void Walk() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001247 // Use the initial classes as roots for a search.
1248 for (mirror::Class* klass_root : image_classes_) {
1249 VisitClinitClassesObject(klass_root);
1250 }
1251 }
1252
1253 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001254 class FindImageClassesVisitor : public ClassVisitor {
1255 public:
1256 explicit FindImageClassesVisitor(ClinitImageUpdate* data) : data_(data) {}
1257
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001258 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001259 std::string temp;
1260 const char* name = klass->GetDescriptor(&temp);
1261 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
1262 data_->image_classes_.push_back(klass);
1263 } else {
1264 // Check whether it is initialized and has a clinit. They must be kept, too.
1265 if (klass->IsInitialized() && klass->FindClassInitializer(
1266 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
1267 data_->image_classes_.push_back(klass);
1268 }
1269 }
1270 return true;
1271 }
1272
1273 private:
1274 ClinitImageUpdate* const data_;
1275 };
1276
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001277 ClinitImageUpdate(std::unordered_set<std::string>* image_class_descriptors, Thread* self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001278 ClassLinker* linker)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001279 REQUIRES_SHARED(Locks::mutator_lock_) :
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001280 image_class_descriptors_(image_class_descriptors), self_(self) {
1281 CHECK(linker != nullptr);
1282 CHECK(image_class_descriptors != nullptr);
1283
1284 // Make sure nobody interferes with us.
1285 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1286
1287 // Find the interesting classes.
Andreas Gampedc8b63c2014-12-02 14:39:52 -08001288 dex_cache_class_ = linker->LookupClass(self, "Ljava/lang/DexCache;",
1289 ComputeModifiedUtf8Hash("Ljava/lang/DexCache;"), nullptr);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001290
1291 // Find all the already-marked classes.
1292 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001293 FindImageClassesVisitor visitor(this);
1294 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001295 }
1296
1297 void VisitClinitClassesObject(mirror::Object* object) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001298 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001299 DCHECK(object != nullptr);
1300 if (marked_objects_.find(object) != marked_objects_.end()) {
1301 // Already processed.
1302 return;
1303 }
1304
1305 // Mark it.
1306 marked_objects_.insert(object);
1307
1308 if (object->IsClass()) {
1309 // If it is a class, add it.
1310 StackHandleScope<1> hs(self_);
1311 MaybeAddToImageClasses(hs.NewHandle(object->AsClass()), image_class_descriptors_);
1312 } else {
1313 // Else visit the object's class.
1314 VisitClinitClassesObject(object->GetClass());
1315 }
1316
Mathieu Chartiere401d142015-04-22 13:56:20 -07001317 // If it is not a DexCache, visit all references.
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001318 mirror::Class* klass = object->GetClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001319 if (klass != dex_cache_class_) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001320 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001321 }
1322 }
1323
1324 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001325 std::unordered_set<std::string>* const image_class_descriptors_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001326 std::vector<mirror::Class*> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001327 const mirror::Class* dex_cache_class_;
1328 Thread* const self_;
1329 const char* old_cause_;
1330
1331 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1332};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001333
Ian Rogers3d504072014-03-01 09:16:49 -08001334void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001335 if (IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001336 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001337
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001338 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001339
1340 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001341 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001342
1343 std::string error_msg;
1344 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(image_classes_.get(),
1345 Thread::Current(),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001346 runtime->GetClassLinker(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001347 &error_msg));
1348 CHECK(update.get() != nullptr) << error_msg; // TODO: Soft failure?
1349
1350 // Do the marking.
1351 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001352 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001353}
1354
Vladimir Marko07785bb2015-06-15 18:52:54 +01001355bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1356 Runtime* runtime = Runtime::Current();
1357 if (!runtime->IsAotCompiler()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001358 DCHECK(runtime->UseJitCompilation());
Vladimir Marko07785bb2015-06-15 18:52:54 +01001359 // Having the klass reference here implies that the klass is already loaded.
1360 return true;
1361 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001362 if (!IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001363 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1364 // loaded because we don't even know what class loader will be used to load them.
1365 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1366 return class_in_image;
1367 }
1368 std::string temp;
1369 const char* descriptor = klass->GetDescriptor(&temp);
1370 return IsImageClass(descriptor);
1371}
1372
Vladimir Marko492a7fa2016-06-01 18:38:43 +01001373void CompilerDriver::MarkForDexToDexCompilation(Thread* self, const MethodReference& method_ref) {
1374 MutexLock lock(self, dex_to_dex_references_lock_);
1375 // Since we're compiling one dex file at a time, we need to look for the
1376 // current dex file entry only at the end of dex_to_dex_references_.
1377 if (dex_to_dex_references_.empty() ||
1378 &dex_to_dex_references_.back().GetDexFile() != method_ref.dex_file) {
1379 dex_to_dex_references_.emplace_back(*method_ref.dex_file);
1380 }
1381 dex_to_dex_references_.back().GetMethodIndexes().SetBit(method_ref.dex_method_index);
1382}
1383
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001384bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(Handle<mirror::DexCache> dex_cache,
1385 uint32_t type_idx) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001386 bool result = false;
1387 if ((IsBootImage() &&
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001388 IsImageClass(dex_cache->GetDexFile()->StringDataByIdx(
1389 dex_cache->GetDexFile()->GetTypeId(type_idx).descriptor_idx_))) ||
Calin Juravleffc87072016-04-20 14:22:09 +01001390 Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001391 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1392 result = (resolved_class != nullptr);
1393 }
1394
1395 if (result) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001396 stats_->TypeInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001397 } else {
1398 stats_->TypeNotInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001399 }
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001400 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001401}
1402
1403bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
1404 uint32_t string_idx) {
1405 // See also Compiler::ResolveDexFile
1406
1407 bool result = false;
Calin Juravleffc87072016-04-20 14:22:09 +01001408 if (IsBootImage() || Runtime::Current()->UseJitCompilation()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001409 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001410 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001411 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1412 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1413 soa.Self(), dex_file, false)));
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001414 if (IsBootImage()) {
1415 // We resolve all const-string strings when building for the image.
1416 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1417 result = true;
1418 } else {
1419 // Just check whether the dex cache already has the string.
Calin Juravleffc87072016-04-20 14:22:09 +01001420 DCHECK(Runtime::Current()->UseJitCompilation());
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001421 result = (dex_cache->GetResolvedString(string_idx) != nullptr);
1422 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001423 }
1424 if (result) {
1425 stats_->StringInDexCache();
1426 } else {
1427 stats_->StringNotInDexCache();
1428 }
1429 return result;
1430}
1431
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001432bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx,
1433 Handle<mirror::DexCache> dex_cache,
1434 uint32_t type_idx) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001435 // Get type from dex cache assuming it was populated by the verifier
1436 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001437 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001438 stats_->TypeNeedsAccessCheck();
1439 return false; // Unknown class needs access checks.
1440 }
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001441 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001442 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1443 if (!is_accessible) {
1444 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1445 if (referrer_class == nullptr) {
1446 stats_->TypeNeedsAccessCheck();
1447 return false; // Incomplete referrer knowledge needs access check.
1448 }
1449 // Perform access check, will return true if access is ok or false if we're going to have to
1450 // check this at runtime (for example for class loaders).
1451 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001452 }
David Brazdil38f64d32016-01-18 17:13:41 +00001453 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001454 stats_->TypeDoesntNeedAccessCheck();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001455 } else {
1456 stats_->TypeNeedsAccessCheck();
1457 }
David Brazdil38f64d32016-01-18 17:13:41 +00001458 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001459}
1460
1461bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001462 Handle<mirror::DexCache> dex_cache,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001463 uint32_t type_idx,
1464 bool* finalizable) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001465 // Get type from dex cache assuming it was populated by the verifier.
1466 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001467 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001468 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001469 // Be conservative.
1470 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001471 return false; // Unknown class needs access checks.
1472 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001473 *finalizable = resolved_class->IsFinalizable();
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001474 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001475 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1476 if (!is_accessible) {
1477 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1478 if (referrer_class == nullptr) {
1479 stats_->TypeNeedsAccessCheck();
1480 return false; // Incomplete referrer knowledge needs access check.
1481 }
1482 // Perform access and instantiable checks, will return true if access is ok or false if we're
1483 // going to have to check this at runtime (for example for class loaders).
1484 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001485 }
David Brazdil38f64d32016-01-18 17:13:41 +00001486 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001487 if (result) {
1488 stats_->TypeDoesntNeedAccessCheck();
1489 } else {
1490 stats_->TypeNeedsAccessCheck();
1491 }
1492 return result;
1493}
1494
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001495bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
1496 bool* is_type_initialized, bool* use_direct_type_ptr,
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001497 uintptr_t* direct_type_ptr, bool* out_is_finalizable) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001498 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001499 Runtime* runtime = Runtime::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001500 mirror::DexCache* dex_cache = runtime->GetClassLinker()->FindDexCache(
1501 soa.Self(), dex_file, false);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001502 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1503 if (resolved_class == nullptr) {
1504 return false;
1505 }
Igor Murashkind6dee672014-10-16 18:36:16 -07001506 if (GetCompilerOptions().GetCompilePic()) {
1507 // Do not allow a direct class pointer to be used when compiling for position-independent
1508 return false;
1509 }
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001510 *out_is_finalizable = resolved_class->IsFinalizable();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001511 gc::Heap* heap = runtime->GetHeap();
1512 const bool compiling_boot = heap->IsCompilingBoot();
Alex Light6e183f22014-07-18 14:57:04 -07001513 const bool support_boot_image_fixup = GetSupportBootImageFixup();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001514 if (compiling_boot) {
1515 // boot -> boot class pointers.
1516 // True if the class is in the image at boot compiling time.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001517 const bool is_image_class = IsBootImage() && IsImageClass(
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001518 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
1519 // True if pc relative load works.
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001520 if (is_image_class && support_boot_image_fixup) {
1521 *is_type_initialized = resolved_class->IsInitialized();
1522 *use_direct_type_ptr = false;
1523 *direct_type_ptr = 0;
1524 return true;
1525 } else {
1526 return false;
1527 }
Calin Juravleffc87072016-04-20 14:22:09 +01001528 } else if (runtime->UseJitCompilation() && !heap->IsMovableObject(resolved_class)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001529 *is_type_initialized = resolved_class->IsInitialized();
1530 // If the class may move around, then don't embed it as a direct pointer.
1531 *use_direct_type_ptr = true;
1532 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1533 return true;
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001534 } else {
1535 // True if the class is in the image at app compiling time.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001536 const bool class_in_image = heap->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
Alex Light6e183f22014-07-18 14:57:04 -07001537 if (class_in_image && support_boot_image_fixup) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001538 // boot -> app class pointers.
1539 *is_type_initialized = resolved_class->IsInitialized();
Alex Lighta59dd802014-07-02 16:28:08 -07001540 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1541 *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001542 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1543 return true;
1544 } else {
1545 // app -> app class pointers.
1546 // Give up because app does not have an image and class
1547 // isn't created at compile time. TODO: implement this
1548 // if/when each app gets an image.
1549 return false;
1550 }
1551 }
1552}
1553
Fred Shihe7f82e22014-08-06 10:46:37 -07001554bool CompilerDriver::CanEmbedReferenceTypeInCode(ClassReference* ref,
1555 bool* use_direct_ptr,
1556 uintptr_t* direct_type_ptr) {
1557 CHECK(ref != nullptr);
1558 CHECK(use_direct_ptr != nullptr);
1559 CHECK(direct_type_ptr != nullptr);
1560
1561 ScopedObjectAccess soa(Thread::Current());
1562 mirror::Class* reference_class = mirror::Reference::GetJavaLangRefReference();
Andreas Gampe928f72b2014-09-09 19:53:48 -07001563 bool is_initialized = false;
Fred Shihe7f82e22014-08-06 10:46:37 -07001564 bool unused_finalizable;
1565 // Make sure we have a finished Reference class object before attempting to use it.
1566 if (!CanEmbedTypeInCode(*reference_class->GetDexCache()->GetDexFile(),
1567 reference_class->GetDexTypeIndex(), &is_initialized,
1568 use_direct_ptr, direct_type_ptr, &unused_finalizable) ||
1569 !is_initialized) {
1570 return false;
1571 }
1572 ref->first = &reference_class->GetDexFile();
1573 ref->second = reference_class->GetDexClassDefIndex();
1574 return true;
1575}
1576
1577uint32_t CompilerDriver::GetReferenceSlowFlagOffset() const {
1578 ScopedObjectAccess soa(Thread::Current());
1579 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1580 DCHECK(klass->IsInitialized());
1581 return klass->GetSlowPathFlagOffset().Uint32Value();
1582}
1583
1584uint32_t CompilerDriver::GetReferenceDisableFlagOffset() const {
1585 ScopedObjectAccess soa(Thread::Current());
1586 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1587 DCHECK(klass->IsInitialized());
1588 return klass->GetDisableIntrinsicFlagOffset().Uint32Value();
1589}
1590
Vladimir Marko20f85592015-03-19 10:07:02 +00001591DexCacheArraysLayout CompilerDriver::GetDexCacheArraysLayout(const DexFile* dex_file) {
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001592 return ContainsElement(GetDexFilesForOatFile(), dex_file)
Mathieu Chartierc7853442015-03-27 14:35:38 -07001593 ? DexCacheArraysLayout(GetInstructionSetPointerSize(instruction_set_), dex_file)
Vladimir Marko20f85592015-03-19 10:07:02 +00001594 : DexCacheArraysLayout();
1595}
1596
Vladimir Markobe0e5462014-02-26 11:24:15 +00001597void CompilerDriver::ProcessedInstanceField(bool resolved) {
1598 if (!resolved) {
1599 stats_->UnresolvedInstanceField();
1600 } else {
1601 stats_->ResolvedInstanceField();
1602 }
1603}
1604
1605void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1606 if (!resolved) {
1607 stats_->UnresolvedStaticField();
1608 } else if (local) {
1609 stats_->ResolvedLocalStaticField();
1610 } else {
1611 stats_->ResolvedStaticField();
1612 }
1613}
1614
Vladimir Markof096aad2014-01-23 15:51:58 +00001615void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
1616 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001617}
1618
Mathieu Chartierc7853442015-03-27 14:35:38 -07001619ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1620 const DexCompilationUnit* mUnit, bool is_put,
1621 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001622 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001623 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001624 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001625 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001626 {
Mathieu Chartier736b5602015-09-02 14:54:11 -07001627 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001628 Handle<mirror::ClassLoader> class_loader_handle(
1629 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartier736b5602015-09-02 14:54:11 -07001630 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001631 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001632 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001633 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001634 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001635 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001636 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001637 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001638 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001639 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001640 ProcessedInstanceField(can_link);
1641 return can_link ? resolved_field : nullptr;
1642}
1643
1644bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1645 bool is_put, MemberOffset* field_offset,
1646 bool* is_volatile) {
1647 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001648 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001649
Mathieu Chartierc7853442015-03-27 14:35:38 -07001650 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001651 // Conservative defaults.
1652 *is_volatile = true;
1653 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001654 return false;
1655 } else {
1656 *is_volatile = resolved_field->IsVolatile();
1657 *field_offset = resolved_field->GetOffset();
1658 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001659 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001660}
1661
Ian Rogers83883d72013-10-21 21:07:24 -07001662void CompilerDriver::GetCodeAndMethodForDirectCall(InvokeType* type, InvokeType sharp_type,
1663 bool no_guarantee_of_dex_cache_entry,
Igor Murashkind6dee672014-10-16 18:36:16 -07001664 const mirror::Class* referrer_class,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001665 ArtMethod* method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001666 int* stats_flags,
Ian Rogers83883d72013-10-21 21:07:24 -07001667 MethodReference* target_method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001668 uintptr_t* direct_code,
1669 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001670 // For direct and static methods compute possible direct_code and direct_method values, ie
1671 // an address for the Method* being invoked and an address of the code for that Method*.
1672 // For interface calls compute a value for direct_method that is the interface method being
1673 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001674 *direct_code = 0;
1675 *direct_method = 0;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001676 Runtime* const runtime = Runtime::Current();
1677 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001678 auto* cl = runtime->GetClassLinker();
1679 const auto pointer_size = cl->GetImagePointerSize();
Igor Murashkind6dee672014-10-16 18:36:16 -07001680 bool use_dex_cache = GetCompilerOptions().GetCompilePic(); // Off by default
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001681 const bool compiling_boot = heap->IsCompilingBoot();
Alex Lighta59dd802014-07-02 16:28:08 -07001682 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1683 const bool force_relocations = (compiling_boot ||
1684 GetCompilerOptions().GetIncludePatchInformation());
Elliott Hughes956af0f2014-12-11 14:34:28 -08001685 if (sharp_type != kStatic && sharp_type != kDirect) {
1686 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001687 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001688 // TODO: support patching on all architectures.
1689 use_dex_cache = use_dex_cache || (force_relocations && !support_boot_image_fixup_);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001690 mirror::Class* declaring_class = method->GetDeclaringClass();
1691 bool method_code_in_boot = declaring_class->GetClassLoader() == nullptr;
Ian Rogers83883d72013-10-21 21:07:24 -07001692 if (!use_dex_cache) {
1693 if (!method_code_in_boot) {
1694 use_dex_cache = true;
1695 } else {
Brian Carlstrom14247b62015-01-31 21:35:32 -08001696 bool has_clinit_trampoline =
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001697 method->IsStatic() && !declaring_class->IsInitialized();
1698 if (has_clinit_trampoline && declaring_class != referrer_class) {
Ian Rogers83883d72013-10-21 21:07:24 -07001699 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1700 // class.
1701 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001702 }
1703 }
Ian Rogers83883d72013-10-21 21:07:24 -07001704 }
Calin Juravleffc87072016-04-20 14:22:09 +01001705 if (runtime->UseJitCompilation()) {
Mathieu Chartier28a35882015-02-26 18:28:07 -08001706 // If we are the JIT, then don't allow a direct call to the interpreter bridge since this will
1707 // never be updated even after we compile the method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001708 if (cl->IsQuickToInterpreterBridge(
Mathieu Chartier28a35882015-02-26 18:28:07 -08001709 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)))) {
1710 use_dex_cache = true;
1711 }
1712 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001713 if (method_code_in_boot) {
1714 *stats_flags |= kFlagDirectCallToBoot | kFlagDirectMethodToBoot;
Ian Rogers83883d72013-10-21 21:07:24 -07001715 }
Alex Lighta59dd802014-07-02 16:28:08 -07001716 if (!use_dex_cache && force_relocations) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001717 bool is_in_image;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001718 if (IsBootImage()) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001719 is_in_image = IsImageClass(method->GetDeclaringClassDescriptor());
1720 } else {
1721 is_in_image = instruction_set_ != kX86 && instruction_set_ != kX86_64 &&
Vladimir Markoc08ab292015-06-22 14:35:42 +01001722 heap->FindSpaceFromObject(method->GetDeclaringClass(), false)->IsImageSpace() &&
1723 !cl->IsQuickToInterpreterBridge(
1724 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)));
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001725 }
1726 if (!is_in_image) {
Ian Rogers83883d72013-10-21 21:07:24 -07001727 // We can only branch directly to Methods that are resolved in the DexCache.
1728 // Otherwise we won't invoke the resolution trampoline.
1729 use_dex_cache = true;
1730 }
1731 }
1732 // The method is defined not within this dex file. We need a dex cache slot within the current
1733 // dex file or direct pointers.
1734 bool must_use_direct_pointers = false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001735 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
1736 if (target_method->dex_file == dex_cache->GetDexFile() &&
Calin Juravleffc87072016-04-20 14:22:09 +01001737 !(runtime->UseJitCompilation() && dex_cache->GetResolvedMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001738 method->GetDexMethodIndex(), pointer_size) == nullptr)) {
Ian Rogers83883d72013-10-21 21:07:24 -07001739 target_method->dex_method_index = method->GetDexMethodIndex();
1740 } else {
Ian Rogers83883d72013-10-21 21:07:24 -07001741 if (no_guarantee_of_dex_cache_entry) {
1742 // See if the method is also declared in this dex cache.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001743 uint32_t dex_method_idx = method->FindDexMethodIndexInOtherDexFile(
1744 *target_method->dex_file, target_method->dex_method_index);
Ian Rogers83883d72013-10-21 21:07:24 -07001745 if (dex_method_idx != DexFile::kDexNoIndex) {
1746 target_method->dex_method_index = dex_method_idx;
1747 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001748 if (force_relocations && !use_dex_cache) {
Jeff Hao49161ce2014-03-12 11:05:25 -07001749 target_method->dex_method_index = method->GetDexMethodIndex();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001750 target_method->dex_file = dex_cache->GetDexFile();
Jeff Hao49161ce2014-03-12 11:05:25 -07001751 }
Ian Rogers83883d72013-10-21 21:07:24 -07001752 must_use_direct_pointers = true;
1753 }
1754 }
1755 }
1756 if (use_dex_cache) {
1757 if (must_use_direct_pointers) {
1758 // Fail. Test above showed the only safe dispatch was via the dex cache, however, the direct
1759 // pointers are required as the dex cache lacks an appropriate entry.
1760 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1761 } else {
1762 *type = sharp_type;
1763 }
1764 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001765 bool method_in_image = false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001766 const std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
1767 for (gc::space::ImageSpace* image_space : image_spaces) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001768 const auto& method_section = image_space->GetImageHeader().GetMethodsSection();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001769 if (method_section.Contains(reinterpret_cast<uint8_t*>(method) - image_space->Begin())) {
1770 method_in_image = true;
1771 break;
1772 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001773 }
Calin Juravleffc87072016-04-20 14:22:09 +01001774 if (method_in_image || compiling_boot || runtime->UseJitCompilation()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001775 // 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 -08001776 // In the case where we are the JIT, we can always use direct pointers since we know where
1777 // the method and its code are / will be. We don't sharpen to interpreter bridge since we
1778 // check IsQuickToInterpreterBridge above.
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001779 CHECK(!method->IsAbstract());
Ian Rogers83883d72013-10-21 21:07:24 -07001780 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001781 *direct_method = force_relocations ? -1 : reinterpret_cast<uintptr_t>(method);
1782 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Brian Carlstrom14247b62015-01-31 21:35:32 -08001783 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001784 target_method->dex_method_index = method->GetDexMethodIndex();
1785 } else if (!must_use_direct_pointers) {
1786 // Set the code and rely on the dex cache for the method.
1787 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001788 if (force_relocations) {
1789 *direct_code = -1;
Brian Carlstrom14247b62015-01-31 21:35:32 -08001790 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Alex Lighta59dd802014-07-02 16:28:08 -07001791 target_method->dex_method_index = method->GetDexMethodIndex();
1792 } else {
1793 *direct_code = compiler_->GetEntryPointOf(method);
1794 }
Ian Rogers83883d72013-10-21 21:07:24 -07001795 } else {
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001796 // Direct pointers were required but none were available.
1797 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001798 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001799 }
1800}
1801
1802bool CompilerDriver::ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001803 bool update_stats, bool enable_devirtualization,
1804 InvokeType* invoke_type, MethodReference* target_method,
1805 int* vtable_idx, uintptr_t* direct_code,
1806 uintptr_t* direct_method) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001807 InvokeType orig_invoke_type = *invoke_type;
1808 int stats_flags = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001809 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof096aad2014-01-23 15:51:58 +00001810 // Try to resolve the method and compiling method's class.
Mathieu Chartier736b5602015-09-02 14:54:11 -07001811 StackHandleScope<2> hs(soa.Self());
1812 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001813 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1814 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001815 uint32_t method_idx = target_method->dex_method_index;
1816 ArtMethod* resolved_method = ResolveMethod(
1817 soa, dex_cache, class_loader, mUnit, method_idx, orig_invoke_type);
1818 auto h_referrer_class = hs.NewHandle(resolved_method != nullptr ?
1819 ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr);
Vladimir Markof096aad2014-01-23 15:51:58 +00001820 bool result = false;
1821 if (resolved_method != nullptr) {
1822 *vtable_idx = GetResolvedMethodVTableIndex(resolved_method, orig_invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001823
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001824 if (enable_devirtualization && mUnit->GetVerifiedMethod() != nullptr) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001825 const MethodReference* devirt_target = mUnit->GetVerifiedMethod()->GetDevirtTarget(dex_pc);
1826
1827 stats_flags = IsFastInvoke(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001828 soa, dex_cache, class_loader, mUnit, h_referrer_class.Get(), resolved_method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001829 invoke_type, target_method, devirt_target, direct_code, direct_method);
1830 result = stats_flags != 0;
1831 } else {
1832 // Devirtualization not enabled. Inline IsFastInvoke(), dropping the devirtualization parts.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001833 if (UNLIKELY(h_referrer_class.Get() == nullptr) ||
1834 UNLIKELY(!h_referrer_class->CanAccessResolvedMethod(resolved_method->GetDeclaringClass(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001835 resolved_method, dex_cache.Get(),
Vladimir Markof096aad2014-01-23 15:51:58 +00001836 target_method->dex_method_index)) ||
1837 *invoke_type == kSuper) {
1838 // Slow path. (Without devirtualization, all super calls go slow path as well.)
1839 } else {
1840 // Sharpening failed so generate a regular resolved method dispatch.
1841 stats_flags = kFlagMethodResolved;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001842 GetCodeAndMethodForDirectCall(
1843 invoke_type, *invoke_type, false, h_referrer_class.Get(), resolved_method, &stats_flags,
1844 target_method, direct_code, direct_method);
Vladimir Markof096aad2014-01-23 15:51:58 +00001845 result = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001846 }
1847 }
1848 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001849 if (!result) {
1850 // Conservative defaults.
1851 *vtable_idx = -1;
1852 *direct_code = 0u;
1853 *direct_method = 0u;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001854 }
1855 if (update_stats) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001856 ProcessedInvoke(orig_invoke_type, stats_flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001857 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001858 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001859}
1860
Vladimir Marko2730db02014-01-27 11:15:17 +00001861const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1862 uint32_t method_idx) const {
1863 MethodReference ref(dex_file, method_idx);
1864 return verification_results_->GetVerifiedMethod(ref);
1865}
1866
1867bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001868 if (!compiler_options_->IsVerificationEnabled()) {
1869 // If we didn't verify, every cast has to be treated as non-safe.
1870 return false;
1871 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001872 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1873 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001874 if (result) {
1875 stats_->SafeCast();
1876 } else {
1877 stats_->NotASafeCast();
1878 }
1879 return result;
1880}
1881
Mathieu Chartier90443472015-07-16 20:32:27 -07001882class CompilationVisitor {
1883 public:
1884 virtual ~CompilationVisitor() {}
1885 virtual void Visit(size_t index) = 0;
1886};
1887
Brian Carlstrom7940e442013-07-12 13:46:57 -07001888class ParallelCompilationManager {
1889 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001890 ParallelCompilationManager(ClassLinker* class_linker,
1891 jobject class_loader,
1892 CompilerDriver* compiler,
1893 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001894 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001895 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001896 : index_(0),
1897 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001898 class_loader_(class_loader),
1899 compiler_(compiler),
1900 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001901 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001902 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001903
1904 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001905 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001906 return class_linker_;
1907 }
1908
1909 jobject GetClassLoader() const {
1910 return class_loader_;
1911 }
1912
1913 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001914 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001915 return compiler_;
1916 }
1917
1918 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001919 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001920 return dex_file_;
1921 }
1922
Andreas Gampede7b4362014-07-28 18:38:57 -07001923 const std::vector<const DexFile*>& GetDexFiles() const {
1924 return dex_files_;
1925 }
1926
Mathieu Chartier90443472015-07-16 20:32:27 -07001927 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1928 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001929 Thread* self = Thread::Current();
1930 self->AssertNoPendingException();
1931 CHECK_GT(work_units, 0U);
1932
Ian Rogers3e5cf302014-05-20 16:40:37 -07001933 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001934 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001935 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001936 }
1937 thread_pool_->StartWorkers(self);
1938
1939 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1940 // thread destructor's called below perform join).
1941 CHECK_NE(self->GetState(), kRunnable);
1942
1943 // Wait for all the worker threads to finish.
1944 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001945
1946 // And stop the workers accepting jobs.
1947 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001948 }
1949
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001950 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001951 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001952 }
1953
Brian Carlstrom7940e442013-07-12 13:46:57 -07001954 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001955 class ForAllClosure : public Task {
1956 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001957 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001958 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001959 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001960 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001961
1962 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001963 while (true) {
1964 const size_t index = manager_->NextIndex();
1965 if (UNLIKELY(index >= end_)) {
1966 break;
1967 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001968 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001969 self->AssertNoPendingException();
1970 }
1971 }
1972
1973 virtual void Finalize() {
1974 delete this;
1975 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001976
Brian Carlstrom7940e442013-07-12 13:46:57 -07001977 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001978 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001979 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001980 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001981 };
1982
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001983 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001984 ClassLinker* const class_linker_;
1985 const jobject class_loader_;
1986 CompilerDriver* const compiler_;
1987 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001988 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001989 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001990
1991 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001992};
1993
Jeff Hao0e49b422013-11-08 12:16:56 -08001994// A fast version of SkipClass above if the class pointer is available
1995// that avoids the expensive FindInClassPath search.
1996static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001997 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001998 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001999 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
2000 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002001 if (class_loader == nullptr) {
Jeff Hao0e49b422013-11-08 12:16:56 -08002002 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
2003 << dex_file.GetLocation() << " previously found in "
2004 << original_dex_file.GetLocation();
2005 }
2006 return true;
2007 }
2008 return false;
2009}
2010
Mathieu Chartier70b63482014-06-27 17:19:04 -07002011static void CheckAndClearResolveException(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002012 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07002013 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002014 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002015 std::string temp;
2016 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
2017 const char* expected_exceptions[] = {
2018 "Ljava/lang/IllegalAccessError;",
2019 "Ljava/lang/IncompatibleClassChangeError;",
2020 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07002021 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07002022 "Ljava/lang/NoClassDefFoundError;",
2023 "Ljava/lang/NoSuchFieldError;",
2024 "Ljava/lang/NoSuchMethodError;"
2025 };
2026 bool found = false;
2027 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
2028 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
2029 found = true;
2030 }
2031 }
2032 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07002033 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07002034 }
2035 self->ClearException();
2036}
2037
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002038bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file,
2039 uint16_t class_def_idx) const {
2040 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2041 const uint8_t* class_data = dex_file.GetClassData(class_def);
2042 if (class_data == nullptr) {
2043 // Empty class such as a marker interface.
2044 return false;
2045 }
2046 ClassDataItemIterator it(dex_file, class_data);
2047 while (it.HasNextStaticField()) {
2048 it.Next();
2049 }
2050 // We require a constructor barrier if there are final instance fields.
2051 while (it.HasNextInstanceField()) {
2052 if (it.MemberIsFinal()) {
2053 return true;
2054 }
2055 it.Next();
2056 }
2057 return false;
2058}
2059
Mathieu Chartier90443472015-07-16 20:32:27 -07002060class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
2061 public:
2062 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
2063 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002064
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002065 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002066 ATRACE_CALL();
2067 Thread* const self = Thread::Current();
2068 jobject jclass_loader = manager_->GetClassLoader();
2069 const DexFile& dex_file = *manager_->GetDexFile();
2070 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002071
Mathieu Chartier90443472015-07-16 20:32:27 -07002072 // If an instance field is final then we need to have a barrier on the return, static final
2073 // fields are assigned within the lock held for class initialization. Conservatively assume
2074 // constructor barriers are always required.
2075 bool requires_constructor_barrier = true;
2076
2077 // Method and Field are the worst. We can't resolve without either
2078 // context from the code use (to disambiguate virtual vs direct
2079 // method and instance vs static field) or from class
2080 // definitions. While the compiler will resolve what it can as it
2081 // needs it, here we try to resolve fields and methods used in class
2082 // definitions, since many of them many never be referenced by
2083 // generated code.
2084 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2085 ScopedObjectAccess soa(self);
2086 StackHandleScope<2> hs(soa.Self());
2087 Handle<mirror::ClassLoader> class_loader(
2088 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002089 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2090 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002091 // Resolve the class.
2092 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
2093 class_loader);
2094 bool resolve_fields_and_methods;
2095 if (klass == nullptr) {
2096 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
2097 // attempt to resolve methods and fields when there is no declaring class.
2098 CheckAndClearResolveException(soa.Self());
2099 resolve_fields_and_methods = false;
2100 } else {
2101 // We successfully resolved a class, should we skip it?
2102 if (SkipClass(jclass_loader, dex_file, klass)) {
2103 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002104 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002105 // We want to resolve the methods and fields eagerly.
2106 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07002107 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002108 // Note the class_data pointer advances through the headers,
2109 // static fields, instance fields, direct methods, and virtual
2110 // methods.
2111 const uint8_t* class_data = dex_file.GetClassData(class_def);
2112 if (class_data == nullptr) {
2113 // Empty class such as a marker interface.
2114 requires_constructor_barrier = false;
2115 } else {
2116 ClassDataItemIterator it(dex_file, class_data);
2117 while (it.HasNextStaticField()) {
2118 if (resolve_fields_and_methods) {
2119 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2120 dex_cache, class_loader, true);
2121 if (field == nullptr) {
2122 CheckAndClearResolveException(soa.Self());
2123 }
Ian Rogers68b56852014-08-29 20:19:11 -07002124 }
2125 it.Next();
2126 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002127 // We require a constructor barrier if there are final instance fields.
2128 requires_constructor_barrier = false;
2129 while (it.HasNextInstanceField()) {
2130 if (it.MemberIsFinal()) {
2131 requires_constructor_barrier = true;
2132 }
2133 if (resolve_fields_and_methods) {
2134 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2135 dex_cache, class_loader, false);
2136 if (field == nullptr) {
2137 CheckAndClearResolveException(soa.Self());
2138 }
Ian Rogers68b56852014-08-29 20:19:11 -07002139 }
2140 it.Next();
2141 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002142 if (resolve_fields_and_methods) {
2143 while (it.HasNextDirectMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002144 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002145 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2146 it.GetMethodInvokeType(class_def));
2147 if (method == nullptr) {
2148 CheckAndClearResolveException(soa.Self());
2149 }
2150 it.Next();
2151 }
2152 while (it.HasNextVirtualMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002153 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002154 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2155 it.GetMethodInvokeType(class_def));
2156 if (method == nullptr) {
2157 CheckAndClearResolveException(soa.Self());
2158 }
2159 it.Next();
2160 }
2161 DCHECK(!it.HasNext());
2162 }
2163 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002164 manager_->GetCompiler()->SetRequiresConstructorBarrier(self,
2165 &dex_file,
2166 class_def_index,
2167 requires_constructor_barrier);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002168 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002169
Mathieu Chartier90443472015-07-16 20:32:27 -07002170 private:
2171 const ParallelCompilationManager* const manager_;
2172};
2173
2174class ResolveTypeVisitor : public CompilationVisitor {
2175 public:
2176 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
2177 }
2178 virtual void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002179 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07002180 ScopedObjectAccess soa(Thread::Current());
2181 ClassLinker* class_linker = manager_->GetClassLinker();
2182 const DexFile& dex_file = *manager_->GetDexFile();
2183 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07002184 Handle<mirror::ClassLoader> class_loader(
2185 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002186 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
2187 dex_file,
Mathieu Chartierf284d442016-06-02 11:48:30 -07002188 class_loader.Get())));
Mathieu Chartier90443472015-07-16 20:32:27 -07002189 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002190
Mathieu Chartier90443472015-07-16 20:32:27 -07002191 if (klass == nullptr) {
2192 soa.Self()->AssertPendingException();
2193 mirror::Throwable* exception = soa.Self()->GetException();
2194 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
2195 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
2196 // There's little point continuing compilation if the heap is exhausted.
2197 LOG(FATAL) << "Out of memory during type resolution for compilation";
2198 }
2199 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07002200 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002201 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002202
2203 private:
2204 const ParallelCompilationManager* const manager_;
2205};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002206
Andreas Gampeace0dc12016-01-20 13:33:13 -08002207void CompilerDriver::ResolveDexFile(jobject class_loader,
2208 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002209 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002210 ThreadPool* thread_pool,
2211 size_t thread_count,
2212 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002213 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2214
2215 // TODO: we could resolve strings here, although the string table is largely filled with class
2216 // and method names.
2217
Andreas Gampede7b4362014-07-28 18:38:57 -07002218 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2219 thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002220 if (IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002221 // For images we resolve all types, such as array, whereas for applications just those with
2222 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002223 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002224 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002225 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002226 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002227
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002228 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002229 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002230 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002231}
2232
Andreas Gampeace0dc12016-01-20 13:33:13 -08002233void CompilerDriver::SetVerified(jobject class_loader,
2234 const std::vector<const DexFile*>& dex_files,
2235 TimingLogger* timings) {
2236 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07002237 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002238 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002239 SetVerifiedDexFile(class_loader,
2240 *dex_file,
2241 dex_files,
2242 parallel_thread_pool_.get(),
2243 parallel_thread_count_,
2244 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002245 }
2246}
2247
Andreas Gampeace0dc12016-01-20 13:33:13 -08002248void CompilerDriver::Verify(jobject class_loader,
2249 const std::vector<const DexFile*>& dex_files,
2250 TimingLogger* timings) {
2251 // Note: verification should not be pulling in classes anymore when compiling the boot image,
2252 // as all should have been resolved before. As such, doing this in parallel should still
2253 // be deterministic.
Mathieu Chartier90443472015-07-16 20:32:27 -07002254 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002255 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002256 VerifyDexFile(class_loader,
2257 *dex_file,
2258 dex_files,
2259 parallel_thread_pool_.get(),
2260 parallel_thread_count_,
2261 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002262 }
2263}
2264
Mathieu Chartier90443472015-07-16 20:32:27 -07002265class VerifyClassVisitor : public CompilationVisitor {
2266 public:
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002267 VerifyClassVisitor(const ParallelCompilationManager* manager, verifier::HardFailLogMode log_level)
Andreas Gampe7fe30232016-03-25 16:58:00 -07002268 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002269
Mathieu Chartier90443472015-07-16 20:32:27 -07002270 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2271 ATRACE_CALL();
2272 ScopedObjectAccess soa(Thread::Current());
2273 const DexFile& dex_file = *manager_->GetDexFile();
Mathieu Chartiera8077802016-03-16 19:08:31 -07002274 if (!manager_->GetCompiler()->ShouldVerifyClassBasedOnProfile(dex_file, class_def_index)) {
2275 // Skip verification since the class is not in the profile.
2276 return;
2277 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002278 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2279 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2280 ClassLinker* class_linker = manager_->GetClassLinker();
2281 jobject jclass_loader = manager_->GetClassLoader();
2282 StackHandleScope<3> hs(soa.Self());
2283 Handle<mirror::ClassLoader> class_loader(
2284 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2285 Handle<mirror::Class> klass(
2286 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2287 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002288 CHECK(soa.Self()->IsExceptionPending());
2289 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07002290
2291 /*
2292 * At compile time, we can still structurally verify the class even if FindClass fails.
2293 * This is to ensure the class is structurally sound for compilation. An unsound class
2294 * will be rejected by the verifier and later skipped during compilation in the compiler.
2295 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002296 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2297 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002298 std::string error_msg;
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002299 if (verifier::MethodVerifier::VerifyClass(soa.Self(),
2300 &dex_file,
2301 dex_cache,
2302 class_loader,
David Brazdil15fc7292016-09-02 14:13:18 +01002303 class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08002304 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002305 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07002306 log_level_,
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002307 &error_msg) ==
Mathieu Chartier90443472015-07-16 20:32:27 -07002308 verifier::MethodVerifier::kHardFailure) {
2309 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2310 << " because: " << error_msg;
2311 manager_->GetCompiler()->SetHadHardVerifierFailure();
2312 }
2313 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
2314 CHECK(klass->IsResolved()) << PrettyClass(klass.Get());
Andreas Gampe7fe30232016-03-25 16:58:00 -07002315 class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002316
2317 if (klass->IsErroneous()) {
2318 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2319 CHECK(soa.Self()->IsExceptionPending());
2320 soa.Self()->ClearException();
2321 manager_->GetCompiler()->SetHadHardVerifierFailure();
2322 }
2323
2324 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
2325 << PrettyDescriptor(klass.Get()) << ": state=" << klass->GetStatus();
2326
2327 // It is *very* problematic if there are verification errors in the boot classpath. For example,
2328 // we rely on things working OK without verification when the decryption dialog is brought up.
2329 // So abort in a debug build if we find this violated.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002330 DCHECK(!manager_->GetCompiler()->IsBootImage() || klass->IsVerified())
2331 << "Boot classpath class " << PrettyClass(klass.Get()) << " failed to fully verify.";
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002332 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002333 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002334 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002335
2336 private:
2337 const ParallelCompilationManager* const manager_;
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002338 const verifier::HardFailLogMode log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002339};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002340
Andreas Gampeace0dc12016-01-20 13:33:13 -08002341void CompilerDriver::VerifyDexFile(jobject class_loader,
2342 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002343 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002344 ThreadPool* thread_pool,
2345 size_t thread_count,
2346 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002347 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002348 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002349 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2350 thread_pool);
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002351 verifier::HardFailLogMode log_level = GetCompilerOptions().AbortOnHardVerifierFailure()
2352 ? verifier::HardFailLogMode::kLogInternalFatal
2353 : verifier::HardFailLogMode::kLogWarning;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002354 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002355 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002356}
2357
Mathieu Chartier90443472015-07-16 20:32:27 -07002358class SetVerifiedClassVisitor : public CompilationVisitor {
2359 public:
2360 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2361
2362 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2363 ATRACE_CALL();
2364 ScopedObjectAccess soa(Thread::Current());
2365 const DexFile& dex_file = *manager_->GetDexFile();
2366 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2367 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2368 ClassLinker* class_linker = manager_->GetClassLinker();
2369 jobject jclass_loader = manager_->GetClassLoader();
2370 StackHandleScope<3> hs(soa.Self());
2371 Handle<mirror::ClassLoader> class_loader(
2372 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2373 Handle<mirror::Class> klass(
2374 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2375 // Class might have failed resolution. Then don't set it to verified.
2376 if (klass.Get() != nullptr) {
2377 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2378 // very wrong.
2379 if (klass->IsResolved()) {
2380 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
2381 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2382 // Set class status to verified.
2383 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self());
2384 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2385 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002386 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002387 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002388 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002389 }
2390 // Record the final class status if necessary.
2391 ClassReference ref(manager_->GetDexFile(), class_def_index);
2392 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002393 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002394 } else {
2395 Thread* self = soa.Self();
2396 DCHECK(self->IsExceptionPending());
2397 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002398 }
2399 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002400
2401 private:
2402 const ParallelCompilationManager* const manager_;
2403};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002404
Andreas Gampeace0dc12016-01-20 13:33:13 -08002405void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2406 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002407 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002408 ThreadPool* thread_pool,
2409 size_t thread_count,
2410 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002411 TimingLogger::ScopedTiming t("Verify Dex File", timings);
2412 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2413 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2414 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002415 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002416 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002417}
2418
Mathieu Chartier90443472015-07-16 20:32:27 -07002419class InitializeClassVisitor : public CompilationVisitor {
2420 public:
2421 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002422
Mathieu Chartier90443472015-07-16 20:32:27 -07002423 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2424 ATRACE_CALL();
2425 jobject jclass_loader = manager_->GetClassLoader();
2426 const DexFile& dex_file = *manager_->GetDexFile();
2427 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2428 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2429 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002430
Mathieu Chartier90443472015-07-16 20:32:27 -07002431 ScopedObjectAccess soa(Thread::Current());
2432 StackHandleScope<3> hs(soa.Self());
2433 Handle<mirror::ClassLoader> class_loader(
2434 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2435 Handle<mirror::Class> klass(
2436 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2437
2438 if (klass.Get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) {
2439 // Only try to initialize classes that were successfully verified.
2440 if (klass->IsVerified()) {
2441 // Attempt to initialize the class but bail if we either need to initialize the super-class
2442 // or static fields.
2443 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002444 if (!klass->IsInitialized()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002445 // We don't want non-trivial class initialization occurring on multiple threads due to
2446 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2447 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2448 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2449 // after first initializing its parents, whose locks are acquired. This leads to a
2450 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2451 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2452 // than use a special Object for the purpose we use the Class of java.lang.Class.
2453 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2454 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2455 // Attempt to initialize allowing initialization of parent classes but still not static
2456 // fields.
2457 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
2458 if (!klass->IsInitialized()) {
2459 // We need to initialize static fields, we only do this for image classes that aren't
2460 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002461 bool can_init_static_fields = manager_->GetCompiler()->IsBootImage() &&
Mathieu Chartier90443472015-07-16 20:32:27 -07002462 manager_->GetCompiler()->IsImageClass(descriptor) &&
2463 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2464 if (can_init_static_fields) {
2465 VLOG(compiler) << "Initializing: " << descriptor;
2466 // TODO multithreading support. We should ensure the current compilation thread has
2467 // exclusive access to the runtime and the transaction. To achieve this, we could use
2468 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2469 // checks in Thread::AssertThreadSuspensionIsAllowable.
2470 Runtime* const runtime = Runtime::Current();
2471 Transaction transaction;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002472
Mathieu Chartier90443472015-07-16 20:32:27 -07002473 // Run the class initializer in transaction mode.
2474 runtime->EnterTransactionMode(&transaction);
2475 const mirror::Class::Status old_status = klass->GetStatus();
2476 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2477 true);
2478 // TODO we detach transaction from runtime to indicate we quit the transactional
2479 // mode which prevents the GC from visiting objects modified during the transaction.
2480 // Ensure GC is not run so don't access freed objects when aborting transaction.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002481
Mathieu Chartier268764d2016-09-13 12:09:38 -07002482 ScopedAssertNoThreadSuspension ants("Transaction end");
Mathieu Chartier90443472015-07-16 20:32:27 -07002483 runtime->ExitTransactionMode();
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002484
Mathieu Chartier90443472015-07-16 20:32:27 -07002485 if (!success) {
2486 CHECK(soa.Self()->IsExceptionPending());
2487 mirror::Throwable* exception = soa.Self()->GetException();
2488 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2489 << exception->Dump();
2490 std::ostream* file_log = manager_->GetCompiler()->
2491 GetCompilerOptions().GetInitFailureOutput();
2492 if (file_log != nullptr) {
2493 *file_log << descriptor << "\n";
2494 *file_log << exception->Dump() << "\n";
2495 }
2496 soa.Self()->ClearException();
2497 transaction.Rollback();
2498 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002499 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002500 }
2501 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002502 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002503 }
2504 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002505 // Record the final class status if necessary.
2506 ClassReference ref(manager_->GetDexFile(), class_def_index);
2507 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002508 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002509 // Clear any class not found or verification exceptions.
2510 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002511 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002512
2513 private:
2514 const ParallelCompilationManager* const manager_;
2515};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002516
Andreas Gampeace0dc12016-01-20 13:33:13 -08002517void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2518 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002519 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002520 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002521 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002522
2523 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2524 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2525 ThreadPool* init_thread_pool = force_determinism
2526 ? single_thread_pool_.get()
2527 : parallel_thread_pool_.get();
2528 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2529
Brian Carlstrom7940e442013-07-12 13:46:57 -07002530 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002531 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002532 init_thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002533 if (IsBootImage()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002534 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002535 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002536 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002537 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002538 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002539}
2540
Mathieu Chartier91288d82016-04-28 09:44:54 -07002541class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002542 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002543 virtual bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier91288d82016-04-28 09:44:54 -07002544 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2545 return true;
2546 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002547 if (klass->IsArrayClass()) {
2548 StackHandleScope<1> hs(Thread::Current());
2549 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(),
2550 hs.NewHandle(klass),
2551 true,
2552 true);
2553 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002554 // Create the conflict tables.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002555 FillIMTAndConflictTables(klass);
Nicolas Geoffray88f288e2016-06-29 08:17:52 +00002556 return true;
Nelli Kimbadee982016-05-13 13:08:53 +03002557 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002558
2559 private:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002560 void FillIMTAndConflictTables(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002561 if (!klass->ShouldHaveImt()) {
2562 return;
2563 }
2564 if (visited_classes_.find(klass) != visited_classes_.end()) {
2565 return;
2566 }
2567 if (klass->HasSuperClass()) {
2568 FillIMTAndConflictTables(klass->GetSuperClass());
2569 }
2570 if (!klass->IsTemp()) {
2571 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
2572 }
2573 visited_classes_.insert(klass);
2574 }
2575
2576 std::set<mirror::Class*> visited_classes_;
Mathieu Chartier085a0722016-04-01 17:33:31 -07002577};
2578
Brian Carlstrom7940e442013-07-12 13:46:57 -07002579void CompilerDriver::InitializeClasses(jobject class_loader,
2580 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002581 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002582 for (size_t i = 0; i != dex_files.size(); ++i) {
2583 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002584 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002585 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002586 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002587 if (boot_image_ || app_image_) {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002588 // Make sure that we call EnsureIntiailized on all the array classes to call
2589 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2590 // changed at runtime resulting in more dirty image pages.
Mathieu Chartier91288d82016-04-28 09:44:54 -07002591 // Also create conflict tables.
2592 // Only useful if we are compiling an image (image_classes_ is not null).
Mathieu Chartier085a0722016-04-01 17:33:31 -07002593 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier91288d82016-04-28 09:44:54 -07002594 InitializeArrayClassesAndCreateConflictTablesVisitor visitor;
2595 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
Mathieu Chartier085a0722016-04-01 17:33:31 -07002596 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002597 if (IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002598 // Prune garbage objects created during aborted transactions.
2599 Runtime::Current()->GetHeap()->CollectGarbage(true);
2600 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002601}
2602
Andreas Gampeace0dc12016-01-20 13:33:13 -08002603void CompilerDriver::Compile(jobject class_loader,
2604 const std::vector<const DexFile*>& dex_files,
2605 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002606 if (kDebugProfileGuidedCompilation) {
2607 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2608 ((profile_compilation_info_ == nullptr)
2609 ? "null"
2610 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002611 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002612
2613 DCHECK(current_dex_to_dex_methods_ == nullptr);
2614 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002615 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002616 CompileDexFile(class_loader,
2617 *dex_file,
2618 dex_files,
2619 parallel_thread_pool_.get(),
2620 parallel_thread_count_,
2621 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002622 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2623 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2624 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002625 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002626 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002627
2628 ArrayRef<DexFileMethodSet> dex_to_dex_references;
2629 {
2630 // From this point on, we shall not modify dex_to_dex_references_, so
2631 // just grab a reference to it that we use without holding the mutex.
2632 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
2633 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
2634 }
2635 for (const auto& method_set : dex_to_dex_references) {
2636 current_dex_to_dex_methods_ = &method_set.GetMethodIndexes();
2637 CompileDexFile(class_loader,
2638 method_set.GetDexFile(),
2639 dex_files,
2640 parallel_thread_pool_.get(),
2641 parallel_thread_count_,
2642 timings);
2643 }
2644 current_dex_to_dex_methods_ = nullptr;
2645
Andreas Gampe8d295f82015-01-20 14:50:21 -08002646 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002647}
2648
Mathieu Chartier90443472015-07-16 20:32:27 -07002649class CompileClassVisitor : public CompilationVisitor {
2650 public:
2651 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2652
2653 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2654 ATRACE_CALL();
2655 const DexFile& dex_file = *manager_->GetDexFile();
2656 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2657 ClassLinker* class_linker = manager_->GetClassLinker();
2658 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002659 ClassReference ref(&dex_file, class_def_index);
2660 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2661 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002662 return;
2663 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002664 // Use a scoped object access to perform to the quick SkipClass check.
2665 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2666 ScopedObjectAccess soa(Thread::Current());
2667 StackHandleScope<3> hs(soa.Self());
2668 Handle<mirror::ClassLoader> class_loader(
2669 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2670 Handle<mirror::Class> klass(
2671 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2672 Handle<mirror::DexCache> dex_cache;
2673 if (klass.Get() == nullptr) {
2674 soa.Self()->AssertPendingException();
2675 soa.Self()->ClearException();
2676 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2677 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2678 return;
2679 } else {
2680 dex_cache = hs.NewHandle(klass->GetDexCache());
2681 }
2682
Mathieu Chartier90443472015-07-16 20:32:27 -07002683 const uint8_t* class_data = dex_file.GetClassData(class_def);
2684 if (class_data == nullptr) {
2685 // empty class, probably a marker interface
2686 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002687 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002688
Mathieu Chartier736b5602015-09-02 14:54:11 -07002689 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002690 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002691
Mathieu Chartier90443472015-07-16 20:32:27 -07002692 CompilerDriver* const driver = manager_->GetCompiler();
2693
2694 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002695 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002696 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002697
Mathieu Chartier90443472015-07-16 20:32:27 -07002698 ClassDataItemIterator it(dex_file, class_data);
2699 // Skip fields
2700 while (it.HasNextStaticField()) {
2701 it.Next();
2702 }
2703 while (it.HasNextInstanceField()) {
2704 it.Next();
2705 }
2706
2707 bool compilation_enabled = driver->IsClassToCompile(
2708 dex_file.StringByTypeIdx(class_def.class_idx_));
2709
2710 // Compile direct methods
2711 int64_t previous_direct_method_idx = -1;
2712 while (it.HasNextDirectMethod()) {
2713 uint32_t method_idx = it.GetMemberIndex();
2714 if (method_idx == previous_direct_method_idx) {
2715 // smali can create dex files with two encoded_methods sharing the same method_idx
2716 // http://code.google.com/p/smali/issues/detail?id=119
2717 it.Next();
2718 continue;
2719 }
2720 previous_direct_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002721 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002722 it.GetMethodInvokeType(class_def), class_def_index,
2723 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002724 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002725 it.Next();
2726 }
2727 // Compile virtual methods
2728 int64_t previous_virtual_method_idx = -1;
2729 while (it.HasNextVirtualMethod()) {
2730 uint32_t method_idx = it.GetMemberIndex();
2731 if (method_idx == previous_virtual_method_idx) {
2732 // smali can create dex files with two encoded_methods sharing the same method_idx
2733 // http://code.google.com/p/smali/issues/detail?id=119
2734 it.Next();
2735 continue;
2736 }
2737 previous_virtual_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002738 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002739 it.GetMethodInvokeType(class_def), class_def_index,
2740 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002741 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002742 it.Next();
2743 }
2744 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002745 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002746
2747 private:
2748 const ParallelCompilationManager* const manager_;
2749};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002750
Andreas Gampeace0dc12016-01-20 13:33:13 -08002751void CompilerDriver::CompileDexFile(jobject class_loader,
2752 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002753 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002754 ThreadPool* thread_pool,
2755 size_t thread_count,
2756 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002757 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002758 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002759 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002760 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002761 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002762}
2763
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002764void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2765 CompiledMethod* const compiled_method,
2766 size_t non_relative_linker_patch_count) {
2767 DCHECK(GetCompiledMethod(method_ref) == nullptr)
2768 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
2769 {
2770 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2771 compiled_methods_.Put(method_ref, compiled_method);
2772 non_relative_linker_patch_count_ += non_relative_linker_patch_count;
Ian Rogersa4a3f402014-10-20 18:10:34 -07002773 }
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002774 DCHECK(GetCompiledMethod(method_ref) != nullptr)
2775 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002776}
2777
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002778void CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2779 CompiledMethod* compiled_method = nullptr;
2780 {
2781 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2782 auto it = compiled_methods_.find(method_ref);
2783 if (it != compiled_methods_.end()) {
2784 compiled_method = it->second;
2785 compiled_methods_.erase(it);
2786 }
2787 }
2788 if (compiled_method != nullptr) {
2789 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, compiled_method);
2790 }
2791}
2792
Brian Carlstrom7940e442013-07-12 13:46:57 -07002793CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
2794 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2795 ClassTable::const_iterator it = compiled_classes_.find(ref);
2796 if (it == compiled_classes_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002797 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002798 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002799 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002800 return it->second;
2801}
2802
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002803void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2804 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2805 auto it = compiled_classes_.find(ref);
2806 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2807 // An entry doesn't exist or the status is lower than the new status.
2808 if (it != compiled_classes_.end()) {
2809 CHECK_GT(status, it->second->GetStatus());
2810 delete it->second;
2811 }
2812 switch (status) {
2813 case mirror::Class::kStatusNotReady:
2814 case mirror::Class::kStatusError:
2815 case mirror::Class::kStatusRetryVerificationAtRuntime:
2816 case mirror::Class::kStatusVerified:
2817 case mirror::Class::kStatusInitialized:
Mathieu Chartiera8077802016-03-16 19:08:31 -07002818 case mirror::Class::kStatusResolved:
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002819 break; // Expected states.
2820 default:
2821 LOG(FATAL) << "Unexpected class status for class "
2822 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2823 << " of " << status;
2824 }
2825 CompiledClass* compiled_class = new CompiledClass(status);
2826 compiled_classes_.Overwrite(ref, compiled_class);
2827 }
2828}
2829
Brian Carlstrom7940e442013-07-12 13:46:57 -07002830CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2831 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2832 MethodTable::const_iterator it = compiled_methods_.find(ref);
2833 if (it == compiled_methods_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002834 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002835 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002836 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002837 return it->second;
2838}
2839
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002840bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2841 uint16_t class_def_idx,
2842 const DexFile& dex_file) const {
2843 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2844 if (verified_method != nullptr) {
2845 return !verified_method->HasVerificationFailures();
2846 }
2847
2848 // If we can't find verification metadata, check if this is a system class (we trust that system
2849 // classes have their methods verified). If it's not, be conservative and assume the method
2850 // has not been verified successfully.
2851
2852 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2853 // even if methods are not found in the verification cache.
2854 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2855 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2856 Thread* self = Thread::Current();
2857 ScopedObjectAccess soa(self);
2858 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2859 if (!is_system_class) {
2860 self->ClearException();
2861 }
2862 return is_system_class;
2863}
2864
Vladimir Markof4da6752014-08-01 19:04:18 +01002865size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
2866 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2867 return non_relative_linker_patch_count_;
2868}
2869
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002870void CompilerDriver::SetRequiresConstructorBarrier(Thread* self,
2871 const DexFile* dex_file,
2872 uint16_t class_def_index,
2873 bool requires) {
2874 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2875 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002876}
2877
Mathieu Chartier371bd832016-04-07 10:19:48 -07002878bool CompilerDriver::RequiresConstructorBarrier(Thread* self,
2879 const DexFile* dex_file,
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002880 uint16_t class_def_index) {
2881 ClassReference class_ref(dex_file, class_def_index);
2882 {
2883 ReaderMutexLock mu(self, requires_constructor_barrier_lock_);
2884 auto it = requires_constructor_barrier_.find(class_ref);
2885 if (it != requires_constructor_barrier_.end()) {
2886 return it->second;
2887 }
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002888 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002889 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2890 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index);
2891 requires_constructor_barrier_.emplace(class_ref, requires);
2892 return requires;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002893}
2894
Andreas Gampe8d295f82015-01-20 14:50:21 -08002895std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002896 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002897 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002898 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002899 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002900 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002901#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002902 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002903 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2904 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002905 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2906 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002907#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002908 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002909 return oss.str();
2910}
2911
Jeff Hao848f70a2014-01-15 13:49:50 -08002912bool CompilerDriver::IsStringTypeIndex(uint16_t type_index, const DexFile* dex_file) {
2913 const char* type = dex_file->GetTypeDescriptor(dex_file->GetTypeId(type_index));
2914 return strcmp(type, "Ljava/lang/String;") == 0;
2915}
2916
2917bool CompilerDriver::IsStringInit(uint32_t method_index, const DexFile* dex_file, int32_t* offset) {
2918 DexFileMethodInliner* inliner = GetMethodInlinerMap()->GetMethodInliner(dex_file);
Igor Murashkin9d4b6da2016-07-29 09:51:58 -07002919 const PointerSize pointer_size = InstructionSetPointerSize(GetInstructionSet());
Jeff Hao848f70a2014-01-15 13:49:50 -08002920 *offset = inliner->GetOffsetForStringInit(method_index, pointer_size);
2921 return inliner->IsStringInitMethodIndex(method_index);
2922}
2923
Jeff Haodcdc85b2015-12-04 14:06:18 -08002924bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
2925 const DexFile* inlined_into) const {
2926 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
2927 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00002928 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
2929 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002930 return false;
2931 }
2932
2933 return true;
2934}
2935
Andreas Gampeace0dc12016-01-20 13:33:13 -08002936void CompilerDriver::InitializeThreadPools() {
2937 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2938 parallel_thread_pool_.reset(
2939 new ThreadPool("Compiler driver thread pool", parallel_count));
2940 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2941}
2942
2943void CompilerDriver::FreeThreadPools() {
2944 parallel_thread_pool_.reset();
2945 single_thread_pool_.reset();
2946}
2947
Brian Carlstrom7940e442013-07-12 13:46:57 -07002948} // namespace art