blob: 8bdff21c70feba4309b3581f5a89a28a06959de2 [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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070029#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080030#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010031#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010033#include "class_linker-inl.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070034#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000035#include "compiled_method.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000036#include "compiler.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000037#include "compiler_driver-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "dex_compilation_unit.h"
39#include "dex_file-inl.h"
Andreas Gampeace0dc12016-01-20 13:33:13 -080040#include "dex_instruction-inl.h"
Andreas Gampe5eb0d382015-07-23 01:19:26 -070041#include "dex/dex_to_dex_compiler.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000042#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000043#include "dex/verified_method.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000044#include "dex/quick/dex_file_method_inliner.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080045#include "dex/quick/dex_file_to_method_inliner_map.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080046#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070047#include "jni_internal.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070048#include "object_lock.h"
Calin Juravlebb0b53f2014-05-23 17:33:29 +010049#include "profiler.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "runtime.h"
51#include "gc/accounting/card_table-inl.h"
52#include "gc/accounting/heap_bitmap.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070053#include "gc/space/image_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "gc/space/space.h"
55#include "mirror/class_loader.h"
56#include "mirror/class-inl.h"
57#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "mirror/object-inl.h"
59#include "mirror/object_array-inl.h"
60#include "mirror/throwable.h"
61#include "scoped_thread_state_change.h"
62#include "ScopedLocalRef.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070063#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "thread.h"
Andreas Gampeb0f370e2014-09-25 22:51:40 -070065#include "thread_list.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070067#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010068#include "transaction.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000069#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampee21dc3d2014-12-08 16:59:43 -080070#include "utils/swap_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070071#include "verifier/method_verifier.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000072#include "verifier/method_verifier-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073
Brian Carlstrom7940e442013-07-12 13:46:57 -070074namespace art {
75
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070076static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
77
Andreas Gampe70bef0d2015-04-15 02:37:28 -070078// Whether classes-to-compile and methods-to-compile are only applied to the boot image, or, when
79// given, too all compilations.
Andreas Gampeb1fcead2015-04-20 18:53:51 -070080static constexpr bool kRestrictCompilationFiltersToImage = true;
81
Calin Juravle226501b2015-12-11 14:41:31 +000082// Print additional info during profile guided compilation.
83static constexpr bool kDebugProfileGuidedCompilation = false;
84
Brian Carlstrom7940e442013-07-12 13:46:57 -070085static double Percentage(size_t x, size_t y) {
86 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
87}
88
89static void DumpStat(size_t x, size_t y, const char* str) {
90 if (x == 0 && y == 0) {
91 return;
92 }
Ian Rogerse732ef12013-10-09 15:22:24 -070093 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -070094}
95
Vladimir Markof096aad2014-01-23 15:51:58 +000096class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -070097 public:
98 AOTCompilationStats()
99 : stats_lock_("AOT compilation statistics lock"),
100 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
101 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
102 resolved_types_(0), unresolved_types_(0),
103 resolved_instance_fields_(0), unresolved_instance_fields_(0),
104 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
105 type_based_devirtualization_(0),
106 safe_casts_(0), not_safe_casts_(0) {
107 for (size_t i = 0; i <= kMaxInvokeType; i++) {
108 resolved_methods_[i] = 0;
109 unresolved_methods_[i] = 0;
110 virtual_made_direct_[i] = 0;
111 direct_calls_to_boot_[i] = 0;
112 direct_methods_to_boot_[i] = 0;
113 }
114 }
115
116 void Dump() {
117 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
118 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
119 DumpStat(resolved_types_, unresolved_types_, "types resolved");
120 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
121 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
122 "static fields resolved");
123 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
124 "static fields local to a class");
125 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
126 // Note, the code below subtracts the stat value so that when added to the stat value we have
127 // 100% of samples. TODO: clean this up.
128 DumpStat(type_based_devirtualization_,
129 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
130 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
131 type_based_devirtualization_,
132 "virtual/interface calls made direct based on type information");
133
134 for (size_t i = 0; i <= kMaxInvokeType; i++) {
135 std::ostringstream oss;
136 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
137 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
138 if (virtual_made_direct_[i] > 0) {
139 std::ostringstream oss2;
140 oss2 << static_cast<InvokeType>(i) << " methods made direct";
141 DumpStat(virtual_made_direct_[i],
142 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
143 oss2.str().c_str());
144 }
145 if (direct_calls_to_boot_[i] > 0) {
146 std::ostringstream oss2;
147 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
148 DumpStat(direct_calls_to_boot_[i],
149 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
150 oss2.str().c_str());
151 }
152 if (direct_methods_to_boot_[i] > 0) {
153 std::ostringstream oss2;
154 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
155 DumpStat(direct_methods_to_boot_[i],
156 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
157 oss2.str().c_str());
158 }
159 }
160 }
161
162// Allow lossy statistics in non-debug builds.
163#ifndef NDEBUG
164#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
165#else
166#define STATS_LOCK()
167#endif
168
Mathieu Chartier90443472015-07-16 20:32:27 -0700169 void TypeInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700170 STATS_LOCK();
171 types_in_dex_cache_++;
172 }
173
Mathieu Chartier90443472015-07-16 20:32:27 -0700174 void TypeNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700175 STATS_LOCK();
176 types_not_in_dex_cache_++;
177 }
178
Mathieu Chartier90443472015-07-16 20:32:27 -0700179 void StringInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700180 STATS_LOCK();
181 strings_in_dex_cache_++;
182 }
183
Mathieu Chartier90443472015-07-16 20:32:27 -0700184 void StringNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700185 STATS_LOCK();
186 strings_not_in_dex_cache_++;
187 }
188
Mathieu Chartier90443472015-07-16 20:32:27 -0700189 void TypeDoesntNeedAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190 STATS_LOCK();
191 resolved_types_++;
192 }
193
Mathieu Chartier90443472015-07-16 20:32:27 -0700194 void TypeNeedsAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700195 STATS_LOCK();
196 unresolved_types_++;
197 }
198
Mathieu Chartier90443472015-07-16 20:32:27 -0700199 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700200 STATS_LOCK();
201 resolved_instance_fields_++;
202 }
203
Mathieu Chartier90443472015-07-16 20:32:27 -0700204 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700205 STATS_LOCK();
206 unresolved_instance_fields_++;
207 }
208
Mathieu Chartier90443472015-07-16 20:32:27 -0700209 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700210 STATS_LOCK();
211 resolved_local_static_fields_++;
212 }
213
Mathieu Chartier90443472015-07-16 20:32:27 -0700214 void ResolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700215 STATS_LOCK();
216 resolved_static_fields_++;
217 }
218
Mathieu Chartier90443472015-07-16 20:32:27 -0700219 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700220 STATS_LOCK();
221 unresolved_static_fields_++;
222 }
223
224 // Indicate that type information from the verifier led to devirtualization.
Mathieu Chartier90443472015-07-16 20:32:27 -0700225 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700226 STATS_LOCK();
227 type_based_devirtualization_++;
228 }
229
230 // Indicate that a method of the given type was resolved at compile time.
Mathieu Chartier90443472015-07-16 20:32:27 -0700231 void ResolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700232 DCHECK_LE(type, kMaxInvokeType);
233 STATS_LOCK();
234 resolved_methods_[type]++;
235 }
236
237 // Indicate that a method of the given type was unresolved at compile time as it was in an
238 // unknown dex file.
Mathieu Chartier90443472015-07-16 20:32:27 -0700239 void UnresolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700240 DCHECK_LE(type, kMaxInvokeType);
241 STATS_LOCK();
242 unresolved_methods_[type]++;
243 }
244
245 // Indicate that a type of virtual method dispatch has been converted into a direct method
246 // dispatch.
Mathieu Chartier90443472015-07-16 20:32:27 -0700247 void VirtualMadeDirect(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700248 DCHECK(type == kVirtual || type == kInterface || type == kSuper);
249 STATS_LOCK();
250 virtual_made_direct_[type]++;
251 }
252
253 // Indicate that a method of the given type was able to call directly into boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700254 void DirectCallsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700255 DCHECK_LE(type, kMaxInvokeType);
256 STATS_LOCK();
257 direct_calls_to_boot_[type]++;
258 }
259
260 // Indicate that a method of the given type was able to be resolved directly from boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700261 void DirectMethodsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700262 DCHECK_LE(type, kMaxInvokeType);
263 STATS_LOCK();
264 direct_methods_to_boot_[type]++;
265 }
266
Mathieu Chartier90443472015-07-16 20:32:27 -0700267 void ProcessedInvoke(InvokeType type, int flags) REQUIRES(!stats_lock_) {
Vladimir Markof096aad2014-01-23 15:51:58 +0000268 STATS_LOCK();
269 if (flags == 0) {
270 unresolved_methods_[type]++;
271 } else {
272 DCHECK_NE((flags & kFlagMethodResolved), 0);
273 resolved_methods_[type]++;
274 if ((flags & kFlagVirtualMadeDirect) != 0) {
275 virtual_made_direct_[type]++;
276 if ((flags & kFlagPreciseTypeDevirtualization) != 0) {
277 type_based_devirtualization_++;
278 }
279 } else {
280 DCHECK_EQ((flags & kFlagPreciseTypeDevirtualization), 0);
281 }
282 if ((flags & kFlagDirectCallToBoot) != 0) {
283 direct_calls_to_boot_[type]++;
284 }
285 if ((flags & kFlagDirectMethodToBoot) != 0) {
286 direct_methods_to_boot_[type]++;
287 }
288 }
289 }
290
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291 // A check-cast could be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700292 void SafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700293 STATS_LOCK();
294 safe_casts_++;
295 }
296
297 // A check-cast couldn't be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700298 void NotASafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700299 STATS_LOCK();
300 not_safe_casts_++;
301 }
302
303 private:
304 Mutex stats_lock_;
305
306 size_t types_in_dex_cache_;
307 size_t types_not_in_dex_cache_;
308
309 size_t strings_in_dex_cache_;
310 size_t strings_not_in_dex_cache_;
311
312 size_t resolved_types_;
313 size_t unresolved_types_;
314
315 size_t resolved_instance_fields_;
316 size_t unresolved_instance_fields_;
317
318 size_t resolved_local_static_fields_;
319 size_t resolved_static_fields_;
320 size_t unresolved_static_fields_;
321 // Type based devirtualization for invoke interface and virtual.
322 size_t type_based_devirtualization_;
323
324 size_t resolved_methods_[kMaxInvokeType + 1];
325 size_t unresolved_methods_[kMaxInvokeType + 1];
326 size_t virtual_made_direct_[kMaxInvokeType + 1];
327 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
328 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
329
330 size_t safe_casts_;
331 size_t not_safe_casts_;
332
333 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
334};
335
Jeff Haodcdc85b2015-12-04 14:06:18 -0800336CompilerDriver::CompilerDriver(
337 const CompilerOptions* compiler_options,
338 VerificationResults* verification_results,
339 DexFileToMethodInlinerMap* method_inliner_map,
340 Compiler::Kind compiler_kind,
341 InstructionSet instruction_set,
342 const InstructionSetFeatures* instruction_set_features,
Vladimir Marko944da602016-02-19 12:27:55 +0000343 bool boot_image,
344 std::unordered_set<std::string>* image_classes,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800345 std::unordered_set<std::string>* compiled_classes,
346 std::unordered_set<std::string>* compiled_methods,
Vladimir Marko944da602016-02-19 12:27:55 +0000347 size_t thread_count,
348 bool dump_stats,
349 bool dump_passes,
350 CumulativeLogger* timer,
351 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200352 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000353 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800354 verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000355 method_inliner_map_(method_inliner_map),
Ian Rogers72d32622014-05-06 16:20:11 -0700356 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700357 compiler_kind_(compiler_kind),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700358 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700359 instruction_set_features_(instruction_set_features),
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700360 requires_constructor_barrier_lock_("constructor barrier lock"),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700361 compiled_classes_lock_("compiled classes lock"),
362 compiled_methods_lock_("compiled method lock"),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800363 compiled_methods_(MethodTable::key_compare()),
Vladimir Markof4da6752014-08-01 19:04:18 +0100364 non_relative_linker_patch_count_(0u),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800365 boot_image_(boot_image),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700366 image_classes_(image_classes),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800367 classes_to_compile_(compiled_classes),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700368 methods_to_compile_(compiled_methods),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800369 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800370 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700371 stats_(new AOTCompilationStats),
372 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000373 dump_passes_(dump_passes),
374 timings_logger_(timer),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700375 compiler_context_(nullptr),
Andreas Gampe57b34292015-01-14 15:45:59 -0800376 support_boot_image_fixup_(instruction_set != kMips && instruction_set != kMips64),
Vladimir Markod1eaf0d2015-10-29 12:18:29 +0000377 dex_files_for_oat_file_(nullptr),
Calin Juravle998c2162015-12-21 15:39:33 +0200378 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000379 profile_compilation_info_(profile_compilation_info),
380 max_arena_alloc_(0) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800381 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom6449c622014-02-10 23:48:36 -0800382 DCHECK(method_inliner_map_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700383
Ian Rogers72d32622014-05-06 16:20:11 -0700384 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700385
Mathieu Chartiera8077802016-03-16 19:08:31 -0700386 if (compiler_options->VerifyOnlyProfile()) {
387 CHECK(profile_compilation_info_ != nullptr) << "Requires profile";
388 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800389 if (boot_image_) {
390 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image";
391 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700392}
393
394CompilerDriver::~CompilerDriver() {
395 Thread* self = Thread::Current();
396 {
397 MutexLock mu(self, compiled_classes_lock_);
398 STLDeleteValues(&compiled_classes_);
399 }
400 {
401 MutexLock mu(self, compiled_methods_lock_);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800402 for (auto& pair : compiled_methods_) {
403 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, pair.second);
404 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700405 }
Ian Rogers72d32622014-05-06 16:20:11 -0700406 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700407}
408
Vladimir Marko35831e82015-09-11 11:59:18 +0100409
Ian Rogersdd7624d2014-03-14 17:43:00 -0700410#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700411 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700412 return CreateTrampoline64(instruction_set_, abi, \
413 type ## _ENTRYPOINT_OFFSET(8, offset)); \
414 } else { \
415 return CreateTrampoline32(instruction_set_, abi, \
416 type ## _ENTRYPOINT_OFFSET(4, offset)); \
417 }
418
Vladimir Marko93205e32016-04-13 11:59:46 +0100419std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700420 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700421}
422
Vladimir Marko93205e32016-04-13 11:59:46 +0100423std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
424 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700425 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800426}
427
Vladimir Marko93205e32016-04-13 11:59:46 +0100428std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
429 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700430 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700431}
432
Vladimir Marko93205e32016-04-13 11:59:46 +0100433std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
434 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700435 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700436}
437
Vladimir Marko93205e32016-04-13 11:59:46 +0100438std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
439 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700440 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700441}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700442#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700443
444void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700445 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800446 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700447 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800448
449 InitializeThreadPools();
450
Andreas Gampe8d295f82015-01-20 14:50:21 -0800451 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
Andreas Gampe740667a2015-09-15 17:55:06 -0700452 // Precompile:
453 // 1) Load image classes
454 // 2) Resolve all classes
455 // 3) Attempt to verify all classes
456 // 4) Attempt to initialize image classes, and trivially initialized classes
Andreas Gampeace0dc12016-01-20 13:33:13 -0800457 PreCompile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700458 // Compile:
459 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
460 // compilation.
461 if (!GetCompilerOptions().VerifyAtRuntime()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800462 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700463 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700464 if (dump_stats_) {
465 stats_->Dump();
466 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800467
468 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700469}
470
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700471static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
472 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
473 const DexFile& dex_file, const DexFile::ClassDef& class_def)
474 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800475 auto* const runtime = Runtime::Current();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700476 if (runtime->UseJit() || driver.GetCompilerOptions().VerifyAtRuntime()) {
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700477 // Verify at runtime shouldn't dex to dex since we didn't resolve of verify.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700478 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800479 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700480 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800481 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800482 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700483 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700484 CHECK(self->IsExceptionPending());
485 self->ClearException();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700486 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700487 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700488 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
489 // references with actual offsets. We cannot re-verify such instructions.
490 //
491 // We store the verification information in the class status in the oat file, which the linker
492 // can validate (checksums) and use to skip load-time verification. It is thus safe to
493 // optimize when a class has been fully verified before.
494 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200495 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700496 return optimizer::DexToDexCompilationLevel::kOptimize;
Sebastien Hertz75021222013-07-16 18:34:50 +0200497 } else if (klass->IsCompileTimeVerified()) {
498 // Class verification has soft-failed. Anyway, ensure at least correctness.
499 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700500 return optimizer::DexToDexCompilationLevel::kRequired;
Sebastien Hertz75021222013-07-16 18:34:50 +0200501 } else {
502 // Class verification has failed: do not run DEX-to-DEX compilation.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700503 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
504 }
505}
506
507static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
508 Thread* self,
509 const CompilerDriver& driver,
510 jobject jclass_loader,
511 const DexFile& dex_file,
512 const DexFile::ClassDef& class_def) {
513 ScopedObjectAccess soa(self);
514 StackHandleScope<1> hs(soa.Self());
515 Handle<mirror::ClassLoader> class_loader(
516 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
517 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
518}
519
520// Does the runtime for the InstructionSet provide an implementation returned by
521// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
522static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
523 switch (isa) {
524 case kArm:
525 case kArm64:
526 case kThumb2:
527 case kMips:
528 case kMips64:
529 case kX86:
530 case kX86_64: return true;
531 default: return false;
532 }
533}
534
535static void CompileMethod(Thread* self,
536 CompilerDriver* driver,
537 const DexFile::CodeItem* code_item,
538 uint32_t access_flags,
539 InvokeType invoke_type,
540 uint16_t class_def_idx,
541 uint32_t method_idx,
542 jobject class_loader,
543 const DexFile& dex_file,
544 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700545 bool compilation_enabled,
546 Handle<mirror::DexCache> dex_cache)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700547 REQUIRES(!driver->compiled_methods_lock_) {
548 DCHECK(driver != nullptr);
549 CompiledMethod* compiled_method = nullptr;
550 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
551 MethodReference method_ref(&dex_file, method_idx);
552
553 if ((access_flags & kAccNative) != 0) {
554 // Are we interpreting only and have support for generic JNI down calls?
555 if (!driver->GetCompilerOptions().IsCompilationEnabled() &&
556 InstructionSetHasGenericJniStub(driver->GetInstructionSet())) {
557 // Leaving this empty will trigger the generic JNI version
558 } else {
559 compiled_method = driver->GetCompiler()->JniCompile(access_flags, method_idx, dex_file);
560 CHECK(compiled_method != nullptr);
561 }
562 } else if ((access_flags & kAccAbstract) != 0) {
563 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000564 } else {
Andreas Gampe0760a812015-08-26 17:12:51 -0700565 const VerifiedMethod* verified_method =
566 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700567 bool compile = compilation_enabled &&
568 // Basic checks, e.g., not <clinit>.
569 driver->GetVerificationResults()
570 ->IsCandidateForCompilation(method_ref, access_flags) &&
571 // Did not fail to create VerifiedMethod metadata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700572 verified_method != nullptr &&
573 // Do not have failures that should punt to the interpreter.
574 !verified_method->HasRuntimeThrow() &&
575 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700576 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700577 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000578 driver->IsMethodToCompile(method_ref) &&
579 driver->ShouldCompileBasedOnProfile(method_ref);
580
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700581 if (compile) {
582 // NOTE: if compiler declines to compile this method, it will return null.
583 compiled_method = driver->GetCompiler()->Compile(code_item, access_flags, invoke_type,
584 class_def_idx, method_idx, class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700585 dex_file, dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700586 }
587 if (compiled_method == nullptr &&
588 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
589 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
590 // Do not optimize if a VerifiedMethod is missing. SafeCast elision, for example, relies on
591 // it.
592 compiled_method = optimizer::ArtCompileDEX(
593 driver,
594 code_item,
595 access_flags,
596 invoke_type,
597 class_def_idx,
598 method_idx,
599 class_loader,
600 dex_file,
Andreas Gampe0760a812015-08-26 17:12:51 -0700601 (verified_method != nullptr)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700602 ? dex_to_dex_compilation_level
603 : optimizer::DexToDexCompilationLevel::kRequired);
604 }
605 }
606 if (kTimeCompileMethod) {
607 uint64_t duration_ns = NanoTime() - start_ns;
608 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
609 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
610 << " took " << PrettyDuration(duration_ns);
611 }
612 }
613
614 if (compiled_method != nullptr) {
615 // Count non-relative linker patches.
616 size_t non_relative_linker_patch_count = 0u;
617 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
618 if (!patch.IsPcRelative()) {
619 ++non_relative_linker_patch_count;
620 }
621 }
622 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
623 // When compiling with PIC, there should be zero non-relative linker patches
624 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
625
626 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
627 }
628
629 // Done compiling, delete the verified method to reduce native memory usage. Do not delete in
630 // optimizing compiler, which may need the verified method again for inlining.
631 if (driver->GetCompilerKind() != Compiler::kOptimizing) {
632 driver->GetVerificationResults()->RemoveVerifiedMethod(method_ref);
633 }
634
635 if (self->IsExceptionPending()) {
636 ScopedObjectAccess soa(self);
637 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
638 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200639 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700640}
641
Mathieu Chartiere401d142015-04-22 13:56:20 -0700642void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700643 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700644 jobject jclass_loader;
645 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700646 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800647 uint32_t method_idx = method->GetDexMethodIndex();
648 uint32_t access_flags = method->GetAccessFlags();
649 InvokeType invoke_type = method->GetInvokeType();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700650 StackHandleScope<1> hs(self);
651 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700652 {
653 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800654 ScopedLocalRef<jobject> local_class_loader(
655 soa.Env(), soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700656 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
657 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700658 dex_file = method->GetDexFile();
659 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700660 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800661 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700662
663 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700664 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700665
666 std::vector<const DexFile*> dex_files;
667 dex_files.push_back(dex_file);
668
Andreas Gampeace0dc12016-01-20 13:33:13 -0800669 InitializeThreadPools();
670
671 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700672
Brian Carlstrom7940e442013-07-12 13:46:57 -0700673 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700674 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
675 GetDexToDexCompilationLevel(self,
676 *this,
677 jclass_loader,
678 *dex_file,
679 dex_file->GetClassDef(class_def_idx));
680
681 CompileMethod(self,
682 this,
683 code_item,
684 access_flags,
685 invoke_type,
686 class_def_idx,
687 method_idx,
688 jclass_loader,
689 *dex_file,
690 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700691 true,
692 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700693
Andreas Gampeace0dc12016-01-20 13:33:13 -0800694 FreeThreadPools();
695
Brian Carlstrom7940e442013-07-12 13:46:57 -0700696 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800697}
698
Andreas Gampeace0dc12016-01-20 13:33:13 -0800699void CompilerDriver::Resolve(jobject class_loader,
700 const std::vector<const DexFile*>& dex_files,
701 TimingLogger* timings) {
702 // Resolution allocates classes and needs to run single-threaded to be deterministic.
703 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
704 ThreadPool* resolve_thread_pool = force_determinism
705 ? single_thread_pool_.get()
706 : parallel_thread_pool_.get();
707 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
708
Brian Carlstrom7940e442013-07-12 13:46:57 -0700709 for (size_t i = 0; i != dex_files.size(); ++i) {
710 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700711 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800712 ResolveDexFile(class_loader,
713 *dex_file,
714 dex_files,
715 resolve_thread_pool,
716 resolve_thread_count,
717 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700718 }
719}
720
Andreas Gampeace0dc12016-01-20 13:33:13 -0800721// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
722// this is single-threaded for simplicity.
723// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
724// stable order.
725
726static void ResolveConstStrings(CompilerDriver* driver,
727 const DexFile& dex_file,
728 const DexFile::CodeItem* code_item) {
729 if (code_item == nullptr) {
730 // Abstract or native method.
731 return;
732 }
733
734 const uint16_t* code_ptr = code_item->insns_;
735 const uint16_t* code_end = code_item->insns_ + code_item->insns_size_in_code_units_;
736
737 while (code_ptr < code_end) {
738 const Instruction* inst = Instruction::At(code_ptr);
739 switch (inst->Opcode()) {
740 case Instruction::CONST_STRING: {
741 uint32_t string_index = inst->VRegB_21c();
742 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
743 break;
744 }
745 case Instruction::CONST_STRING_JUMBO: {
746 uint32_t string_index = inst->VRegB_31c();
747 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
748 break;
749 }
750
751 default:
752 break;
753 }
754
755 code_ptr += inst->SizeInCodeUnits();
756 }
757}
758
759static void ResolveConstStrings(CompilerDriver* driver,
760 const std::vector<const DexFile*>& dex_files,
761 TimingLogger* timings) {
762 for (const DexFile* dex_file : dex_files) {
763 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
764
765 size_t class_def_count = dex_file->NumClassDefs();
766 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
767 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
768
769 const uint8_t* class_data = dex_file->GetClassData(class_def);
770 if (class_data == nullptr) {
771 // empty class, probably a marker interface
772 continue;
773 }
774
775 ClassDataItemIterator it(*dex_file, class_data);
776 // Skip fields
777 while (it.HasNextStaticField()) {
778 it.Next();
779 }
780 while (it.HasNextInstanceField()) {
781 it.Next();
782 }
783
784 bool compilation_enabled = driver->IsClassToCompile(
785 dex_file->StringByTypeIdx(class_def.class_idx_));
786 if (!compilation_enabled) {
787 // Compilation is skipped, do not resolve const-string in code of this class.
788 // TODO: Make sure that inlining honors this.
789 continue;
790 }
791
792 // Direct methods.
793 int64_t previous_direct_method_idx = -1;
794 while (it.HasNextDirectMethod()) {
795 uint32_t method_idx = it.GetMemberIndex();
796 if (method_idx == previous_direct_method_idx) {
797 // smali can create dex files with two encoded_methods sharing the same method_idx
798 // http://code.google.com/p/smali/issues/detail?id=119
799 it.Next();
800 continue;
801 }
802 previous_direct_method_idx = method_idx;
803 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
804 it.Next();
805 }
806 // Virtual methods.
807 int64_t previous_virtual_method_idx = -1;
808 while (it.HasNextVirtualMethod()) {
809 uint32_t method_idx = it.GetMemberIndex();
810 if (method_idx == previous_virtual_method_idx) {
811 // smali can create dex files with two encoded_methods sharing the same method_idx
812 // http://code.google.com/p/smali/issues/detail?id=119
813 it.Next();
814 continue;
815 }
816 previous_virtual_method_idx = method_idx;
817 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
818 it.Next();
819 }
820 DCHECK(!it.HasNext());
821 }
822 }
823}
824
825inline void CompilerDriver::CheckThreadPools() {
826 DCHECK(parallel_thread_pool_ != nullptr);
827 DCHECK(single_thread_pool_ != nullptr);
828}
829
830void CompilerDriver::PreCompile(jobject class_loader,
831 const std::vector<const DexFile*>& dex_files,
832 TimingLogger* timings) {
833 CheckThreadPools();
834
Brian Carlstrom7940e442013-07-12 13:46:57 -0700835 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800836 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700837
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700838 const bool verification_enabled = compiler_options_->IsVerificationEnabled();
839 const bool never_verify = compiler_options_->NeverVerify();
Mathieu Chartiera8077802016-03-16 19:08:31 -0700840 const bool verify_only_profile = compiler_options_->VerifyOnlyProfile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700841
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700842 // We need to resolve for never_verify since it needs to run dex to dex to add the
843 // RETURN_VOID_NO_BARRIER.
Mathieu Chartiera8077802016-03-16 19:08:31 -0700844 // Let the verifier resolve as needed for the verify_only_profile case.
845 if ((never_verify || verification_enabled) && !verify_only_profile) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800846 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700847 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
848 }
849
850 if (never_verify) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800851 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800852 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700853 }
854
855 if (!verification_enabled) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700856 return;
857 }
858
Andreas Gampeace0dc12016-01-20 13:33:13 -0800859 if (GetCompilerOptions().IsForceDeterminism() && IsBootImage()) {
860 // Resolve strings from const-string. Do this now to have a deterministic image.
861 ResolveConstStrings(this, dex_files, timings);
862 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
863 }
864
865 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800866 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700867
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800868 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
869 LOG(FATAL) << "Had a hard failure verifying all classes, and was asked to abort in such "
870 << "situations. Please check the log.";
871 }
872
Andreas Gampeace0dc12016-01-20 13:33:13 -0800873 InitializeClasses(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800874 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700875
876 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800877 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700878}
879
Ian Rogersdfb325e2013-10-30 01:00:44 -0700880bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800881 if (image_classes_ != nullptr) {
882 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -0700883 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700884 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800885 // No set of image classes, assume we include all the classes.
886 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
887 return !IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700888}
889
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800890bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800891 if (kRestrictCompilationFiltersToImage && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800892 return true;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800893 }
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700894
895 if (classes_to_compile_ == nullptr) {
896 return true;
897 }
898 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800899}
900
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700901bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800902 if (kRestrictCompilationFiltersToImage && !IsBootImage()) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700903 return true;
904 }
905
906 if (methods_to_compile_ == nullptr) {
907 return true;
908 }
909
910 std::string tmp = PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
911 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
912}
913
Calin Juravle226501b2015-12-11 14:41:31 +0000914bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
915 if (profile_compilation_info_ == nullptr) {
916 // If we miss profile information it means that we don't do a profile guided compilation.
917 // Return true, and let the other filters decide if the method should be compiled.
918 return true;
919 }
920 bool result = profile_compilation_info_->ContainsMethod(method_ref);
921
922 if (kDebugProfileGuidedCompilation) {
923 LOG(INFO) << "[ProfileGuidedCompilation] "
924 << (result ? "Compiled" : "Skipped") << " method:"
925 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
926 }
927 return result;
928}
929
Mathieu Chartiera8077802016-03-16 19:08:31 -0700930bool CompilerDriver::ShouldVerifyClassBasedOnProfile(const DexFile& dex_file,
931 uint16_t class_idx) const {
932 if (!compiler_options_->VerifyOnlyProfile()) {
933 // No profile, verify everything.
934 return true;
935 }
936 DCHECK(profile_compilation_info_ != nullptr);
937 bool result = profile_compilation_info_->ContainsClass(dex_file, class_idx);
938 if (kDebugProfileGuidedCompilation) {
939 LOG(INFO) << "[ProfileGuidedCompilation] "
940 << (result ? "Verified" : "Skipped") << " method:"
941 << dex_file.GetClassDescriptor(dex_file.GetClassDef(class_idx));
942 }
943 return result;
944}
945
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700946class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
947 public:
948 ResolveCatchBlockExceptionsClassVisitor(
949 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve)
950 : exceptions_to_resolve_(exceptions_to_resolve) {}
951
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800952 virtual bool operator()(mirror::Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700953 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Alex Lighte64300b2015-12-15 15:02:47 -0800954 for (auto& m : c->GetMethods(pointer_size)) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100955 ResolveExceptionsForMethod(&m, pointer_size);
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700956 }
957 return true;
958 }
959
960 private:
Vladimir Marko05792b92015-08-03 11:56:49 +0100961 void ResolveExceptionsForMethod(ArtMethod* method_handle, size_t pointer_size)
962 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700963 const DexFile::CodeItem* code_item = method_handle->GetCodeItem();
964 if (code_item == nullptr) {
965 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -0700966 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700967 if (code_item->tries_size_ == 0) {
968 return; // nothing to process
969 }
970 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
971 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
972 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
973 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
974 bool has_catch_all = false;
975 if (encoded_catch_handler_size <= 0) {
976 encoded_catch_handler_size = -encoded_catch_handler_size;
977 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700978 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700979 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
980 uint16_t encoded_catch_handler_handlers_type_idx =
981 DecodeUnsignedLeb128(&encoded_catch_handler_list);
982 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko05792b92015-08-03 11:56:49 +0100983 if (!method_handle->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx,
984 pointer_size)) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700985 exceptions_to_resolve_.emplace(encoded_catch_handler_handlers_type_idx,
986 method_handle->GetDexFile());
987 }
988 // ignore address associated with catch handler
989 DecodeUnsignedLeb128(&encoded_catch_handler_list);
990 }
991 if (has_catch_all) {
992 // ignore catch all address
993 DecodeUnsignedLeb128(&encoded_catch_handler_list);
994 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700995 }
996 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700997
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700998 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve_;
999};
1000
1001class RecordImageClassesVisitor : public ClassVisitor {
1002 public:
1003 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
1004 : image_classes_(image_classes) {}
1005
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001006 bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001007 std::string temp;
1008 image_classes_->insert(klass->GetDescriptor(&temp));
1009 return true;
1010 }
1011
1012 private:
1013 std::unordered_set<std::string>* const image_classes_;
1014};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001015
1016// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001017void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001018 CHECK(timings != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001019 if (!IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001020 return;
1021 }
1022
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001023 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001024 // Make a first class to load all classes explicitly listed in the file
1025 Thread* self = Thread::Current();
1026 ScopedObjectAccess soa(self);
1027 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001028 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001029 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001030 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001031 StackHandleScope<1> hs(self);
1032 Handle<mirror::Class> klass(
1033 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001034 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001035 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001036 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001037 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001038 } else {
1039 ++it;
1040 }
1041 }
1042
1043 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1044 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1045 // Do this here so that exception classes appear to have been specified image classes.
Ian Rogers700a4022014-05-19 16:49:03 -07001046 std::set<std::pair<uint16_t, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001047 StackHandleScope<1> hs(self);
1048 Handle<mirror::Class> java_lang_Throwable(
1049 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001050 do {
1051 unresolved_exception_types.clear();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001052 ResolveCatchBlockExceptionsClassVisitor visitor(unresolved_exception_types);
1053 class_linker->VisitClasses(&visitor);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001054 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
1055 uint16_t exception_type_idx = exception_type.first;
1056 const DexFile* dex_file = exception_type.second;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001057 StackHandleScope<2> hs2(self);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001058 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(
1059 *dex_file,
1060 Runtime::Current()->GetLinearAlloc())));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001061 Handle<mirror::Class> klass(hs2.NewHandle(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001062 class_linker->ResolveType(*dex_file,
1063 exception_type_idx,
1064 dex_cache,
1065 ScopedNullHandle<mirror::ClassLoader>())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001066 if (klass.Get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001067 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1068 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1069 LOG(FATAL) << "Failed to resolve class " << descriptor;
1070 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001071 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001072 }
1073 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1074 // more are found
1075 } while (!unresolved_exception_types.empty());
1076
1077 // We walk the roots looking for classes so that we'll pick up the
1078 // above classes plus any classes them depend on such super
1079 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001080 RecordImageClassesVisitor visitor(image_classes_.get());
1081 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001082
1083 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001084}
1085
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001086static void MaybeAddToImageClasses(Handle<mirror::Class> c,
1087 std::unordered_set<std::string>* image_classes)
Mathieu Chartier90443472015-07-16 20:32:27 -07001088 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001089 Thread* self = Thread::Current();
1090 StackHandleScope<1> hs(self);
1091 // Make a copy of the handle so that we don't clobber it doing Assign.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001092 MutableHandle<mirror::Class> klass(hs.NewHandle(c.Get()));
Ian Rogers1ff3c982014-08-12 02:30:58 -07001093 std::string temp;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001094 const size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001095 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001096 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001097 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1098 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001099 if (!result.second) { // Previously inserted.
1100 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001101 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001102 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Mathieu Chartierf8322842014-05-16 10:59:25 -07001103 for (size_t i = 0; i < klass->NumDirectInterfaces(); ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001104 StackHandleScope<1> hs2(self);
1105 MaybeAddToImageClasses(hs2.NewHandle(mirror::Class::GetDirectInterface(self, klass, i)),
Mathieu Chartierf8322842014-05-16 10:59:25 -07001106 image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001107 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001108 for (auto& m : c->GetVirtualMethods(pointer_size)) {
Alex Light36121492016-02-22 13:43:29 -08001109 StackHandleScope<1> hs2(self);
1110 MaybeAddToImageClasses(hs2.NewHandle(m.GetDeclaringClass()), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001111 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001112 if (klass->IsArrayClass()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001113 StackHandleScope<1> hs2(self);
1114 MaybeAddToImageClasses(hs2.NewHandle(klass->GetComponentType()), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001115 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001116 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001117 }
1118}
1119
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001120// Keeps all the data for the update together. Also doubles as the reference visitor.
1121// Note: we can use object pointers because we suspend all threads.
1122class ClinitImageUpdate {
1123 public:
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001124 static ClinitImageUpdate* Create(std::unordered_set<std::string>* image_class_descriptors,
1125 Thread* self, ClassLinker* linker, std::string* error_msg) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001126 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(image_class_descriptors, self,
1127 linker));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001128 if (res->dex_cache_class_ == nullptr) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001129 *error_msg = "Could not find DexCache class.";
1130 return nullptr;
1131 }
1132
1133 return res.release();
1134 }
1135
1136 ~ClinitImageUpdate() {
1137 // Allow others to suspend again.
1138 self_->EndAssertNoThreadSuspension(old_cause_);
1139 }
1140
1141 // Visitor for VisitReferences.
1142 void operator()(mirror::Object* object, MemberOffset field_offset, bool /* is_static */) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001143 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001144 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1145 if (ref != nullptr) {
1146 VisitClinitClassesObject(ref);
1147 }
1148 }
1149
1150 // java.lang.Reference visitor for VisitReferences.
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001151 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref ATTRIBUTE_UNUSED)
1152 const {}
1153
1154 // Ignore class native roots.
1155 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1156 const {}
1157 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001158
Mathieu Chartier90443472015-07-16 20:32:27 -07001159 void Walk() SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001160 // Use the initial classes as roots for a search.
1161 for (mirror::Class* klass_root : image_classes_) {
1162 VisitClinitClassesObject(klass_root);
1163 }
1164 }
1165
1166 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001167 class FindImageClassesVisitor : public ClassVisitor {
1168 public:
1169 explicit FindImageClassesVisitor(ClinitImageUpdate* data) : data_(data) {}
1170
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001171 bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001172 std::string temp;
1173 const char* name = klass->GetDescriptor(&temp);
1174 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
1175 data_->image_classes_.push_back(klass);
1176 } else {
1177 // Check whether it is initialized and has a clinit. They must be kept, too.
1178 if (klass->IsInitialized() && klass->FindClassInitializer(
1179 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
1180 data_->image_classes_.push_back(klass);
1181 }
1182 }
1183 return true;
1184 }
1185
1186 private:
1187 ClinitImageUpdate* const data_;
1188 };
1189
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001190 ClinitImageUpdate(std::unordered_set<std::string>* image_class_descriptors, Thread* self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001191 ClassLinker* linker)
Mathieu Chartier90443472015-07-16 20:32:27 -07001192 SHARED_REQUIRES(Locks::mutator_lock_) :
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001193 image_class_descriptors_(image_class_descriptors), self_(self) {
1194 CHECK(linker != nullptr);
1195 CHECK(image_class_descriptors != nullptr);
1196
1197 // Make sure nobody interferes with us.
1198 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1199
1200 // Find the interesting classes.
Andreas Gampedc8b63c2014-12-02 14:39:52 -08001201 dex_cache_class_ = linker->LookupClass(self, "Ljava/lang/DexCache;",
1202 ComputeModifiedUtf8Hash("Ljava/lang/DexCache;"), nullptr);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001203
1204 // Find all the already-marked classes.
1205 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001206 FindImageClassesVisitor visitor(this);
1207 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001208 }
1209
1210 void VisitClinitClassesObject(mirror::Object* object) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001211 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001212 DCHECK(object != nullptr);
1213 if (marked_objects_.find(object) != marked_objects_.end()) {
1214 // Already processed.
1215 return;
1216 }
1217
1218 // Mark it.
1219 marked_objects_.insert(object);
1220
1221 if (object->IsClass()) {
1222 // If it is a class, add it.
1223 StackHandleScope<1> hs(self_);
1224 MaybeAddToImageClasses(hs.NewHandle(object->AsClass()), image_class_descriptors_);
1225 } else {
1226 // Else visit the object's class.
1227 VisitClinitClassesObject(object->GetClass());
1228 }
1229
Mathieu Chartiere401d142015-04-22 13:56:20 -07001230 // If it is not a DexCache, visit all references.
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001231 mirror::Class* klass = object->GetClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001232 if (klass != dex_cache_class_) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001233 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001234 }
1235 }
1236
1237 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001238 std::unordered_set<std::string>* const image_class_descriptors_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001239 std::vector<mirror::Class*> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001240 const mirror::Class* dex_cache_class_;
1241 Thread* const self_;
1242 const char* old_cause_;
1243
1244 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1245};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001246
Ian Rogers3d504072014-03-01 09:16:49 -08001247void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001248 if (IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001249 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001250
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001251 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001252
1253 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001254 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001255
1256 std::string error_msg;
1257 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(image_classes_.get(),
1258 Thread::Current(),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001259 runtime->GetClassLinker(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001260 &error_msg));
1261 CHECK(update.get() != nullptr) << error_msg; // TODO: Soft failure?
1262
1263 // Do the marking.
1264 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001265 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001266}
1267
Vladimir Marko07785bb2015-06-15 18:52:54 +01001268bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1269 Runtime* runtime = Runtime::Current();
1270 if (!runtime->IsAotCompiler()) {
1271 DCHECK(runtime->UseJit());
1272 // Having the klass reference here implies that the klass is already loaded.
1273 return true;
1274 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001275 if (!IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001276 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1277 // loaded because we don't even know what class loader will be used to load them.
1278 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1279 return class_in_image;
1280 }
1281 std::string temp;
1282 const char* descriptor = klass->GetDescriptor(&temp);
1283 return IsImageClass(descriptor);
1284}
1285
Mathieu Chartier590fee92013-09-13 13:46:47 -07001286bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(const DexFile& dex_file, uint32_t type_idx) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001287 bool result = false;
1288 if ((IsBootImage() &&
1289 IsImageClass(dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_))) ||
1290 Runtime::Current()->UseJit()) {
1291 ScopedObjectAccess soa(Thread::Current());
1292 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(
1293 soa.Self(), dex_file, false);
1294 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1295 result = (resolved_class != nullptr);
1296 }
1297
1298 if (result) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001299 stats_->TypeInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001300 } else {
1301 stats_->TypeNotInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001302 }
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001303 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001304}
1305
1306bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
1307 uint32_t string_idx) {
1308 // See also Compiler::ResolveDexFile
1309
1310 bool result = false;
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001311 if (IsBootImage() || Runtime::Current()->UseJit()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001312 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001313 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001314 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1315 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1316 soa.Self(), dex_file, false)));
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001317 if (IsBootImage()) {
1318 // We resolve all const-string strings when building for the image.
1319 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1320 result = true;
1321 } else {
1322 // Just check whether the dex cache already has the string.
1323 DCHECK(Runtime::Current()->UseJit());
1324 result = (dex_cache->GetResolvedString(string_idx) != nullptr);
1325 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001326 }
1327 if (result) {
1328 stats_->StringInDexCache();
1329 } else {
1330 stats_->StringNotInDexCache();
1331 }
1332 return result;
1333}
1334
1335bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
1336 uint32_t type_idx,
1337 bool* type_known_final, bool* type_known_abstract,
1338 bool* equals_referrers_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001339 if (type_known_final != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001340 *type_known_final = false;
1341 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001342 if (type_known_abstract != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001343 *type_known_abstract = false;
1344 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001345 if (equals_referrers_class != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001346 *equals_referrers_class = false;
1347 }
1348 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001349 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(
1350 soa.Self(), dex_file, false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001351 // Get type from dex cache assuming it was populated by the verifier
1352 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001353 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001354 stats_->TypeNeedsAccessCheck();
1355 return false; // Unknown class needs access checks.
1356 }
1357 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001358 if (equals_referrers_class != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001359 *equals_referrers_class = (method_id.class_idx_ == type_idx);
1360 }
David Brazdil38f64d32016-01-18 17:13:41 +00001361 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1362 if (!is_accessible) {
1363 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1364 if (referrer_class == nullptr) {
1365 stats_->TypeNeedsAccessCheck();
1366 return false; // Incomplete referrer knowledge needs access check.
1367 }
1368 // Perform access check, will return true if access is ok or false if we're going to have to
1369 // check this at runtime (for example for class loaders).
1370 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001371 }
David Brazdil38f64d32016-01-18 17:13:41 +00001372 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001373 stats_->TypeDoesntNeedAccessCheck();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001374 if (type_known_final != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001375 *type_known_final = resolved_class->IsFinal() && !resolved_class->IsArrayClass();
1376 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001377 if (type_known_abstract != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001378 *type_known_abstract = resolved_class->IsAbstract() && !resolved_class->IsArrayClass();
1379 }
1380 } else {
1381 stats_->TypeNeedsAccessCheck();
1382 }
David Brazdil38f64d32016-01-18 17:13:41 +00001383 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001384}
1385
1386bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
1387 const DexFile& dex_file,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001388 uint32_t type_idx,
1389 bool* finalizable) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001390 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001391 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(
1392 soa.Self(), dex_file, false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001393 // Get type from dex cache assuming it was populated by the verifier.
1394 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001395 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001396 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001397 // Be conservative.
1398 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001399 return false; // Unknown class needs access checks.
1400 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001401 *finalizable = resolved_class->IsFinalizable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001402 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001403 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1404 if (!is_accessible) {
1405 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1406 if (referrer_class == nullptr) {
1407 stats_->TypeNeedsAccessCheck();
1408 return false; // Incomplete referrer knowledge needs access check.
1409 }
1410 // Perform access and instantiable checks, will return true if access is ok or false if we're
1411 // going to have to check this at runtime (for example for class loaders).
1412 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001413 }
David Brazdil38f64d32016-01-18 17:13:41 +00001414 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001415 if (result) {
1416 stats_->TypeDoesntNeedAccessCheck();
1417 } else {
1418 stats_->TypeNeedsAccessCheck();
1419 }
1420 return result;
1421}
1422
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001423bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
1424 bool* is_type_initialized, bool* use_direct_type_ptr,
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001425 uintptr_t* direct_type_ptr, bool* out_is_finalizable) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001426 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001427 Runtime* runtime = Runtime::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001428 mirror::DexCache* dex_cache = runtime->GetClassLinker()->FindDexCache(
1429 soa.Self(), dex_file, false);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001430 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1431 if (resolved_class == nullptr) {
1432 return false;
1433 }
Igor Murashkind6dee672014-10-16 18:36:16 -07001434 if (GetCompilerOptions().GetCompilePic()) {
1435 // Do not allow a direct class pointer to be used when compiling for position-independent
1436 return false;
1437 }
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001438 *out_is_finalizable = resolved_class->IsFinalizable();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001439 gc::Heap* heap = runtime->GetHeap();
1440 const bool compiling_boot = heap->IsCompilingBoot();
Alex Light6e183f22014-07-18 14:57:04 -07001441 const bool support_boot_image_fixup = GetSupportBootImageFixup();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001442 if (compiling_boot) {
1443 // boot -> boot class pointers.
1444 // True if the class is in the image at boot compiling time.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001445 const bool is_image_class = IsBootImage() && IsImageClass(
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001446 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
1447 // True if pc relative load works.
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001448 if (is_image_class && support_boot_image_fixup) {
1449 *is_type_initialized = resolved_class->IsInitialized();
1450 *use_direct_type_ptr = false;
1451 *direct_type_ptr = 0;
1452 return true;
1453 } else {
1454 return false;
1455 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001456 } else if (runtime->UseJit() && !heap->IsMovableObject(resolved_class)) {
1457 *is_type_initialized = resolved_class->IsInitialized();
1458 // If the class may move around, then don't embed it as a direct pointer.
1459 *use_direct_type_ptr = true;
1460 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1461 return true;
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001462 } else {
1463 // True if the class is in the image at app compiling time.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001464 const bool class_in_image = heap->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
Alex Light6e183f22014-07-18 14:57:04 -07001465 if (class_in_image && support_boot_image_fixup) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001466 // boot -> app class pointers.
1467 *is_type_initialized = resolved_class->IsInitialized();
Alex Lighta59dd802014-07-02 16:28:08 -07001468 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1469 *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001470 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1471 return true;
1472 } else {
1473 // app -> app class pointers.
1474 // Give up because app does not have an image and class
1475 // isn't created at compile time. TODO: implement this
1476 // if/when each app gets an image.
1477 return false;
1478 }
1479 }
1480}
1481
Fred Shihe7f82e22014-08-06 10:46:37 -07001482bool CompilerDriver::CanEmbedReferenceTypeInCode(ClassReference* ref,
1483 bool* use_direct_ptr,
1484 uintptr_t* direct_type_ptr) {
1485 CHECK(ref != nullptr);
1486 CHECK(use_direct_ptr != nullptr);
1487 CHECK(direct_type_ptr != nullptr);
1488
1489 ScopedObjectAccess soa(Thread::Current());
1490 mirror::Class* reference_class = mirror::Reference::GetJavaLangRefReference();
Andreas Gampe928f72b2014-09-09 19:53:48 -07001491 bool is_initialized = false;
Fred Shihe7f82e22014-08-06 10:46:37 -07001492 bool unused_finalizable;
1493 // Make sure we have a finished Reference class object before attempting to use it.
1494 if (!CanEmbedTypeInCode(*reference_class->GetDexCache()->GetDexFile(),
1495 reference_class->GetDexTypeIndex(), &is_initialized,
1496 use_direct_ptr, direct_type_ptr, &unused_finalizable) ||
1497 !is_initialized) {
1498 return false;
1499 }
1500 ref->first = &reference_class->GetDexFile();
1501 ref->second = reference_class->GetDexClassDefIndex();
1502 return true;
1503}
1504
1505uint32_t CompilerDriver::GetReferenceSlowFlagOffset() const {
1506 ScopedObjectAccess soa(Thread::Current());
1507 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1508 DCHECK(klass->IsInitialized());
1509 return klass->GetSlowPathFlagOffset().Uint32Value();
1510}
1511
1512uint32_t CompilerDriver::GetReferenceDisableFlagOffset() const {
1513 ScopedObjectAccess soa(Thread::Current());
1514 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1515 DCHECK(klass->IsInitialized());
1516 return klass->GetDisableIntrinsicFlagOffset().Uint32Value();
1517}
1518
Vladimir Marko20f85592015-03-19 10:07:02 +00001519DexCacheArraysLayout CompilerDriver::GetDexCacheArraysLayout(const DexFile* dex_file) {
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001520 return ContainsElement(GetDexFilesForOatFile(), dex_file)
Mathieu Chartierc7853442015-03-27 14:35:38 -07001521 ? DexCacheArraysLayout(GetInstructionSetPointerSize(instruction_set_), dex_file)
Vladimir Marko20f85592015-03-19 10:07:02 +00001522 : DexCacheArraysLayout();
1523}
1524
Vladimir Markobe0e5462014-02-26 11:24:15 +00001525void CompilerDriver::ProcessedInstanceField(bool resolved) {
1526 if (!resolved) {
1527 stats_->UnresolvedInstanceField();
1528 } else {
1529 stats_->ResolvedInstanceField();
1530 }
1531}
1532
1533void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1534 if (!resolved) {
1535 stats_->UnresolvedStaticField();
1536 } else if (local) {
1537 stats_->ResolvedLocalStaticField();
1538 } else {
1539 stats_->ResolvedStaticField();
1540 }
1541}
1542
Vladimir Markof096aad2014-01-23 15:51:58 +00001543void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
1544 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001545}
1546
Mathieu Chartierc7853442015-03-27 14:35:38 -07001547ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1548 const DexCompilationUnit* mUnit, bool is_put,
1549 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001550 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001551 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001552 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001553 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001554 {
Mathieu Chartier736b5602015-09-02 14:54:11 -07001555 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001556 Handle<mirror::ClassLoader> class_loader_handle(
1557 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartier736b5602015-09-02 14:54:11 -07001558 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001559 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001560 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001561 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001562 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001563 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001564 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001565 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001566 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001567 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001568 ProcessedInstanceField(can_link);
1569 return can_link ? resolved_field : nullptr;
1570}
1571
1572bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1573 bool is_put, MemberOffset* field_offset,
1574 bool* is_volatile) {
1575 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001576 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001577
Mathieu Chartierc7853442015-03-27 14:35:38 -07001578 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001579 // Conservative defaults.
1580 *is_volatile = true;
1581 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001582 return false;
1583 } else {
1584 *is_volatile = resolved_field->IsVolatile();
1585 *field_offset = resolved_field->GetOffset();
1586 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001587 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001588}
1589
1590bool CompilerDriver::ComputeStaticFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
Vladimir Markobe0e5462014-02-26 11:24:15 +00001591 bool is_put, MemberOffset* field_offset,
1592 uint32_t* storage_index, bool* is_referrers_class,
Nicolas Geoffray19a19cf2014-10-22 16:07:05 +01001593 bool* is_volatile, bool* is_initialized,
1594 Primitive::Type* type) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001595 ScopedObjectAccess soa(Thread::Current());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001596 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001597 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001598 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001599 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001600 {
Mathieu Chartier736b5602015-09-02 14:54:11 -07001601 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001602 Handle<mirror::ClassLoader> class_loader_handle(
1603 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001604 resolved_field =
Mathieu Chartier736b5602015-09-02 14:54:11 -07001605 ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, true);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001606 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001607 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001608 }
Vladimir Markobe0e5462014-02-26 11:24:15 +00001609 bool result = false;
1610 if (resolved_field != nullptr && referrer_class != nullptr) {
1611 *is_volatile = IsFieldVolatile(resolved_field);
1612 std::pair<bool, bool> fast_path = IsFastStaticField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001613 dex_cache.Get(), referrer_class, resolved_field, field_idx, storage_index);
Vladimir Markobe0e5462014-02-26 11:24:15 +00001614 result = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001615 }
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001616 if (result) {
1617 *field_offset = GetFieldOffset(resolved_field);
1618 *is_referrers_class = IsStaticFieldInReferrerClass(referrer_class, resolved_field);
1619 // *is_referrers_class == true implies no worrying about class initialization.
1620 *is_initialized = (*is_referrers_class) ||
1621 (IsStaticFieldsClassInitialized(referrer_class, resolved_field) &&
1622 CanAssumeTypeIsPresentInDexCache(*mUnit->GetDexFile(), *storage_index));
Nicolas Geoffray19a19cf2014-10-22 16:07:05 +01001623 *type = resolved_field->GetTypeAsPrimitiveType();
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001624 } else {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001625 // Conservative defaults.
1626 *is_volatile = true;
1627 *field_offset = MemberOffset(static_cast<size_t>(-1));
1628 *storage_index = -1;
1629 *is_referrers_class = false;
1630 *is_initialized = false;
Nicolas Geoffray19a19cf2014-10-22 16:07:05 +01001631 *type = Primitive::kPrimVoid;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001632 }
1633 ProcessedStaticField(result, *is_referrers_class);
1634 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001635}
1636
Ian Rogers83883d72013-10-21 21:07:24 -07001637void CompilerDriver::GetCodeAndMethodForDirectCall(InvokeType* type, InvokeType sharp_type,
1638 bool no_guarantee_of_dex_cache_entry,
Igor Murashkind6dee672014-10-16 18:36:16 -07001639 const mirror::Class* referrer_class,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001640 ArtMethod* method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001641 int* stats_flags,
Ian Rogers83883d72013-10-21 21:07:24 -07001642 MethodReference* target_method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001643 uintptr_t* direct_code,
1644 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001645 // For direct and static methods compute possible direct_code and direct_method values, ie
1646 // an address for the Method* being invoked and an address of the code for that Method*.
1647 // For interface calls compute a value for direct_method that is the interface method being
1648 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001649 *direct_code = 0;
1650 *direct_method = 0;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001651 Runtime* const runtime = Runtime::Current();
1652 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001653 auto* cl = runtime->GetClassLinker();
1654 const auto pointer_size = cl->GetImagePointerSize();
Igor Murashkind6dee672014-10-16 18:36:16 -07001655 bool use_dex_cache = GetCompilerOptions().GetCompilePic(); // Off by default
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001656 const bool compiling_boot = heap->IsCompilingBoot();
Alex Lighta59dd802014-07-02 16:28:08 -07001657 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1658 const bool force_relocations = (compiling_boot ||
1659 GetCompilerOptions().GetIncludePatchInformation());
Elliott Hughes956af0f2014-12-11 14:34:28 -08001660 if (sharp_type != kStatic && sharp_type != kDirect) {
1661 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001662 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001663 // TODO: support patching on all architectures.
1664 use_dex_cache = use_dex_cache || (force_relocations && !support_boot_image_fixup_);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001665 mirror::Class* declaring_class = method->GetDeclaringClass();
1666 bool method_code_in_boot = declaring_class->GetClassLoader() == nullptr;
Ian Rogers83883d72013-10-21 21:07:24 -07001667 if (!use_dex_cache) {
1668 if (!method_code_in_boot) {
1669 use_dex_cache = true;
1670 } else {
Brian Carlstrom14247b62015-01-31 21:35:32 -08001671 bool has_clinit_trampoline =
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001672 method->IsStatic() && !declaring_class->IsInitialized();
1673 if (has_clinit_trampoline && declaring_class != referrer_class) {
Ian Rogers83883d72013-10-21 21:07:24 -07001674 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1675 // class.
1676 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001677 }
1678 }
Ian Rogers83883d72013-10-21 21:07:24 -07001679 }
Mathieu Chartier28a35882015-02-26 18:28:07 -08001680 if (runtime->UseJit()) {
1681 // If we are the JIT, then don't allow a direct call to the interpreter bridge since this will
1682 // never be updated even after we compile the method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001683 if (cl->IsQuickToInterpreterBridge(
Mathieu Chartier28a35882015-02-26 18:28:07 -08001684 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)))) {
1685 use_dex_cache = true;
1686 }
1687 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001688 if (method_code_in_boot) {
1689 *stats_flags |= kFlagDirectCallToBoot | kFlagDirectMethodToBoot;
Ian Rogers83883d72013-10-21 21:07:24 -07001690 }
Alex Lighta59dd802014-07-02 16:28:08 -07001691 if (!use_dex_cache && force_relocations) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001692 bool is_in_image;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001693 if (IsBootImage()) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001694 is_in_image = IsImageClass(method->GetDeclaringClassDescriptor());
1695 } else {
1696 is_in_image = instruction_set_ != kX86 && instruction_set_ != kX86_64 &&
Vladimir Markoc08ab292015-06-22 14:35:42 +01001697 heap->FindSpaceFromObject(method->GetDeclaringClass(), false)->IsImageSpace() &&
1698 !cl->IsQuickToInterpreterBridge(
1699 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)));
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001700 }
1701 if (!is_in_image) {
Ian Rogers83883d72013-10-21 21:07:24 -07001702 // We can only branch directly to Methods that are resolved in the DexCache.
1703 // Otherwise we won't invoke the resolution trampoline.
1704 use_dex_cache = true;
1705 }
1706 }
1707 // The method is defined not within this dex file. We need a dex cache slot within the current
1708 // dex file or direct pointers.
1709 bool must_use_direct_pointers = false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001710 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
1711 if (target_method->dex_file == dex_cache->GetDexFile() &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07001712 !(runtime->UseJit() && dex_cache->GetResolvedMethod(
1713 method->GetDexMethodIndex(), pointer_size) == nullptr)) {
Ian Rogers83883d72013-10-21 21:07:24 -07001714 target_method->dex_method_index = method->GetDexMethodIndex();
1715 } else {
Ian Rogers83883d72013-10-21 21:07:24 -07001716 if (no_guarantee_of_dex_cache_entry) {
1717 // See if the method is also declared in this dex cache.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001718 uint32_t dex_method_idx = method->FindDexMethodIndexInOtherDexFile(
1719 *target_method->dex_file, target_method->dex_method_index);
Ian Rogers83883d72013-10-21 21:07:24 -07001720 if (dex_method_idx != DexFile::kDexNoIndex) {
1721 target_method->dex_method_index = dex_method_idx;
1722 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001723 if (force_relocations && !use_dex_cache) {
Jeff Hao49161ce2014-03-12 11:05:25 -07001724 target_method->dex_method_index = method->GetDexMethodIndex();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001725 target_method->dex_file = dex_cache->GetDexFile();
Jeff Hao49161ce2014-03-12 11:05:25 -07001726 }
Ian Rogers83883d72013-10-21 21:07:24 -07001727 must_use_direct_pointers = true;
1728 }
1729 }
1730 }
1731 if (use_dex_cache) {
1732 if (must_use_direct_pointers) {
1733 // Fail. Test above showed the only safe dispatch was via the dex cache, however, the direct
1734 // pointers are required as the dex cache lacks an appropriate entry.
1735 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1736 } else {
1737 *type = sharp_type;
1738 }
1739 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001740 bool method_in_image = false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001741 const std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
1742 for (gc::space::ImageSpace* image_space : image_spaces) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001743 const auto& method_section = image_space->GetImageHeader().GetMethodsSection();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001744 if (method_section.Contains(reinterpret_cast<uint8_t*>(method) - image_space->Begin())) {
1745 method_in_image = true;
1746 break;
1747 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001748 }
Mathieu Chartier6ced4092015-02-27 16:10:48 -08001749 if (method_in_image || compiling_boot || runtime->UseJit()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001750 // 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 -08001751 // In the case where we are the JIT, we can always use direct pointers since we know where
1752 // the method and its code are / will be. We don't sharpen to interpreter bridge since we
1753 // check IsQuickToInterpreterBridge above.
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001754 CHECK(!method->IsAbstract());
Ian Rogers83883d72013-10-21 21:07:24 -07001755 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001756 *direct_method = force_relocations ? -1 : reinterpret_cast<uintptr_t>(method);
1757 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Brian Carlstrom14247b62015-01-31 21:35:32 -08001758 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001759 target_method->dex_method_index = method->GetDexMethodIndex();
1760 } else if (!must_use_direct_pointers) {
1761 // Set the code and rely on the dex cache for the method.
1762 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001763 if (force_relocations) {
1764 *direct_code = -1;
Brian Carlstrom14247b62015-01-31 21:35:32 -08001765 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Alex Lighta59dd802014-07-02 16:28:08 -07001766 target_method->dex_method_index = method->GetDexMethodIndex();
1767 } else {
1768 *direct_code = compiler_->GetEntryPointOf(method);
1769 }
Ian Rogers83883d72013-10-21 21:07:24 -07001770 } else {
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001771 // Direct pointers were required but none were available.
1772 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001773 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001774 }
1775}
1776
1777bool CompilerDriver::ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001778 bool update_stats, bool enable_devirtualization,
1779 InvokeType* invoke_type, MethodReference* target_method,
1780 int* vtable_idx, uintptr_t* direct_code,
1781 uintptr_t* direct_method) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001782 InvokeType orig_invoke_type = *invoke_type;
1783 int stats_flags = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001784 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof096aad2014-01-23 15:51:58 +00001785 // Try to resolve the method and compiling method's class.
Mathieu Chartier736b5602015-09-02 14:54:11 -07001786 StackHandleScope<2> hs(soa.Self());
1787 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001788 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1789 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001790 uint32_t method_idx = target_method->dex_method_index;
1791 ArtMethod* resolved_method = ResolveMethod(
1792 soa, dex_cache, class_loader, mUnit, method_idx, orig_invoke_type);
1793 auto h_referrer_class = hs.NewHandle(resolved_method != nullptr ?
1794 ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr);
Vladimir Markof096aad2014-01-23 15:51:58 +00001795 bool result = false;
1796 if (resolved_method != nullptr) {
1797 *vtable_idx = GetResolvedMethodVTableIndex(resolved_method, orig_invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001798
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001799 if (enable_devirtualization && mUnit->GetVerifiedMethod() != nullptr) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001800 const MethodReference* devirt_target = mUnit->GetVerifiedMethod()->GetDevirtTarget(dex_pc);
1801
1802 stats_flags = IsFastInvoke(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001803 soa, dex_cache, class_loader, mUnit, h_referrer_class.Get(), resolved_method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001804 invoke_type, target_method, devirt_target, direct_code, direct_method);
1805 result = stats_flags != 0;
1806 } else {
1807 // Devirtualization not enabled. Inline IsFastInvoke(), dropping the devirtualization parts.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001808 if (UNLIKELY(h_referrer_class.Get() == nullptr) ||
1809 UNLIKELY(!h_referrer_class->CanAccessResolvedMethod(resolved_method->GetDeclaringClass(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001810 resolved_method, dex_cache.Get(),
Vladimir Markof096aad2014-01-23 15:51:58 +00001811 target_method->dex_method_index)) ||
1812 *invoke_type == kSuper) {
1813 // Slow path. (Without devirtualization, all super calls go slow path as well.)
1814 } else {
1815 // Sharpening failed so generate a regular resolved method dispatch.
1816 stats_flags = kFlagMethodResolved;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001817 GetCodeAndMethodForDirectCall(
1818 invoke_type, *invoke_type, false, h_referrer_class.Get(), resolved_method, &stats_flags,
1819 target_method, direct_code, direct_method);
Vladimir Markof096aad2014-01-23 15:51:58 +00001820 result = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001821 }
1822 }
1823 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001824 if (!result) {
1825 // Conservative defaults.
1826 *vtable_idx = -1;
1827 *direct_code = 0u;
1828 *direct_method = 0u;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001829 }
1830 if (update_stats) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001831 ProcessedInvoke(orig_invoke_type, stats_flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001832 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001833 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001834}
1835
Vladimir Marko2730db02014-01-27 11:15:17 +00001836const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1837 uint32_t method_idx) const {
1838 MethodReference ref(dex_file, method_idx);
1839 return verification_results_->GetVerifiedMethod(ref);
1840}
1841
1842bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001843 if (!compiler_options_->IsVerificationEnabled()) {
1844 // If we didn't verify, every cast has to be treated as non-safe.
1845 return false;
1846 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001847 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1848 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001849 if (result) {
1850 stats_->SafeCast();
1851 } else {
1852 stats_->NotASafeCast();
1853 }
1854 return result;
1855}
1856
Mathieu Chartier90443472015-07-16 20:32:27 -07001857class CompilationVisitor {
1858 public:
1859 virtual ~CompilationVisitor() {}
1860 virtual void Visit(size_t index) = 0;
1861};
1862
Brian Carlstrom7940e442013-07-12 13:46:57 -07001863class ParallelCompilationManager {
1864 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001865 ParallelCompilationManager(ClassLinker* class_linker,
1866 jobject class_loader,
1867 CompilerDriver* compiler,
1868 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001869 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001870 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001871 : index_(0),
1872 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001873 class_loader_(class_loader),
1874 compiler_(compiler),
1875 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001876 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001877 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001878
1879 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001880 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001881 return class_linker_;
1882 }
1883
1884 jobject GetClassLoader() const {
1885 return class_loader_;
1886 }
1887
1888 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001889 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001890 return compiler_;
1891 }
1892
1893 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001894 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001895 return dex_file_;
1896 }
1897
Andreas Gampede7b4362014-07-28 18:38:57 -07001898 const std::vector<const DexFile*>& GetDexFiles() const {
1899 return dex_files_;
1900 }
1901
Mathieu Chartier90443472015-07-16 20:32:27 -07001902 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1903 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001904 Thread* self = Thread::Current();
1905 self->AssertNoPendingException();
1906 CHECK_GT(work_units, 0U);
1907
Ian Rogers3e5cf302014-05-20 16:40:37 -07001908 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001909 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001910 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001911 }
1912 thread_pool_->StartWorkers(self);
1913
1914 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1915 // thread destructor's called below perform join).
1916 CHECK_NE(self->GetState(), kRunnable);
1917
1918 // Wait for all the worker threads to finish.
1919 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001920
1921 // And stop the workers accepting jobs.
1922 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001923 }
1924
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001925 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001926 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001927 }
1928
Brian Carlstrom7940e442013-07-12 13:46:57 -07001929 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001930 class ForAllClosure : public Task {
1931 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001932 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001933 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001934 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001935 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001936
1937 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001938 while (true) {
1939 const size_t index = manager_->NextIndex();
1940 if (UNLIKELY(index >= end_)) {
1941 break;
1942 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001943 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001944 self->AssertNoPendingException();
1945 }
1946 }
1947
1948 virtual void Finalize() {
1949 delete this;
1950 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001951
Brian Carlstrom7940e442013-07-12 13:46:57 -07001952 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001953 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001954 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001955 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001956 };
1957
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001958 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001959 ClassLinker* const class_linker_;
1960 const jobject class_loader_;
1961 CompilerDriver* const compiler_;
1962 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001963 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001964 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001965
1966 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001967};
1968
Jeff Hao0e49b422013-11-08 12:16:56 -08001969// A fast version of SkipClass above if the class pointer is available
1970// that avoids the expensive FindInClassPath search.
1971static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
Mathieu Chartier90443472015-07-16 20:32:27 -07001972 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001973 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001974 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1975 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001976 if (class_loader == nullptr) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001977 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1978 << dex_file.GetLocation() << " previously found in "
1979 << original_dex_file.GetLocation();
1980 }
1981 return true;
1982 }
1983 return false;
1984}
1985
Mathieu Chartier70b63482014-06-27 17:19:04 -07001986static void CheckAndClearResolveException(Thread* self)
Mathieu Chartier90443472015-07-16 20:32:27 -07001987 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07001988 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001989 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001990 std::string temp;
1991 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1992 const char* expected_exceptions[] = {
1993 "Ljava/lang/IllegalAccessError;",
1994 "Ljava/lang/IncompatibleClassChangeError;",
1995 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001996 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07001997 "Ljava/lang/NoClassDefFoundError;",
1998 "Ljava/lang/NoSuchFieldError;",
1999 "Ljava/lang/NoSuchMethodError;"
2000 };
2001 bool found = false;
2002 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
2003 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
2004 found = true;
2005 }
2006 }
2007 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07002008 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07002009 }
2010 self->ClearException();
2011}
2012
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002013bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file,
2014 uint16_t class_def_idx) const {
2015 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2016 const uint8_t* class_data = dex_file.GetClassData(class_def);
2017 if (class_data == nullptr) {
2018 // Empty class such as a marker interface.
2019 return false;
2020 }
2021 ClassDataItemIterator it(dex_file, class_data);
2022 while (it.HasNextStaticField()) {
2023 it.Next();
2024 }
2025 // We require a constructor barrier if there are final instance fields.
2026 while (it.HasNextInstanceField()) {
2027 if (it.MemberIsFinal()) {
2028 return true;
2029 }
2030 it.Next();
2031 }
2032 return false;
2033}
2034
Mathieu Chartier90443472015-07-16 20:32:27 -07002035class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
2036 public:
2037 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
2038 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002039
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002040 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002041 ATRACE_CALL();
2042 Thread* const self = Thread::Current();
2043 jobject jclass_loader = manager_->GetClassLoader();
2044 const DexFile& dex_file = *manager_->GetDexFile();
2045 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002046
Mathieu Chartier90443472015-07-16 20:32:27 -07002047 // If an instance field is final then we need to have a barrier on the return, static final
2048 // fields are assigned within the lock held for class initialization. Conservatively assume
2049 // constructor barriers are always required.
2050 bool requires_constructor_barrier = true;
2051
2052 // Method and Field are the worst. We can't resolve without either
2053 // context from the code use (to disambiguate virtual vs direct
2054 // method and instance vs static field) or from class
2055 // definitions. While the compiler will resolve what it can as it
2056 // needs it, here we try to resolve fields and methods used in class
2057 // definitions, since many of them many never be referenced by
2058 // generated code.
2059 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2060 ScopedObjectAccess soa(self);
2061 StackHandleScope<2> hs(soa.Self());
2062 Handle<mirror::ClassLoader> class_loader(
2063 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002064 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2065 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002066 // Resolve the class.
2067 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
2068 class_loader);
2069 bool resolve_fields_and_methods;
2070 if (klass == nullptr) {
2071 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
2072 // attempt to resolve methods and fields when there is no declaring class.
2073 CheckAndClearResolveException(soa.Self());
2074 resolve_fields_and_methods = false;
2075 } else {
2076 // We successfully resolved a class, should we skip it?
2077 if (SkipClass(jclass_loader, dex_file, klass)) {
2078 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002079 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002080 // We want to resolve the methods and fields eagerly.
2081 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07002082 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002083 // Note the class_data pointer advances through the headers,
2084 // static fields, instance fields, direct methods, and virtual
2085 // methods.
2086 const uint8_t* class_data = dex_file.GetClassData(class_def);
2087 if (class_data == nullptr) {
2088 // Empty class such as a marker interface.
2089 requires_constructor_barrier = false;
2090 } else {
2091 ClassDataItemIterator it(dex_file, class_data);
2092 while (it.HasNextStaticField()) {
2093 if (resolve_fields_and_methods) {
2094 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2095 dex_cache, class_loader, true);
2096 if (field == nullptr) {
2097 CheckAndClearResolveException(soa.Self());
2098 }
Ian Rogers68b56852014-08-29 20:19:11 -07002099 }
2100 it.Next();
2101 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002102 // We require a constructor barrier if there are final instance fields.
2103 requires_constructor_barrier = false;
2104 while (it.HasNextInstanceField()) {
2105 if (it.MemberIsFinal()) {
2106 requires_constructor_barrier = true;
2107 }
2108 if (resolve_fields_and_methods) {
2109 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2110 dex_cache, class_loader, false);
2111 if (field == nullptr) {
2112 CheckAndClearResolveException(soa.Self());
2113 }
Ian Rogers68b56852014-08-29 20:19:11 -07002114 }
2115 it.Next();
2116 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002117 if (resolve_fields_and_methods) {
2118 while (it.HasNextDirectMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002119 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002120 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2121 it.GetMethodInvokeType(class_def));
2122 if (method == nullptr) {
2123 CheckAndClearResolveException(soa.Self());
2124 }
2125 it.Next();
2126 }
2127 while (it.HasNextVirtualMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002128 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002129 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2130 it.GetMethodInvokeType(class_def));
2131 if (method == nullptr) {
2132 CheckAndClearResolveException(soa.Self());
2133 }
2134 it.Next();
2135 }
2136 DCHECK(!it.HasNext());
2137 }
2138 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002139 manager_->GetCompiler()->SetRequiresConstructorBarrier(self,
2140 &dex_file,
2141 class_def_index,
2142 requires_constructor_barrier);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002143 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002144
Mathieu Chartier90443472015-07-16 20:32:27 -07002145 private:
2146 const ParallelCompilationManager* const manager_;
2147};
2148
2149class ResolveTypeVisitor : public CompilationVisitor {
2150 public:
2151 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
2152 }
2153 virtual void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002154 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07002155 ScopedObjectAccess soa(Thread::Current());
2156 ClassLinker* class_linker = manager_->GetClassLinker();
2157 const DexFile& dex_file = *manager_->GetDexFile();
2158 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07002159 Handle<mirror::ClassLoader> class_loader(
2160 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002161 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
2162 dex_file,
2163 class_linker->GetOrCreateAllocatorForClassLoader(class_loader.Get()))));
Mathieu Chartier90443472015-07-16 20:32:27 -07002164 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002165
Mathieu Chartier90443472015-07-16 20:32:27 -07002166 if (klass == nullptr) {
2167 soa.Self()->AssertPendingException();
2168 mirror::Throwable* exception = soa.Self()->GetException();
2169 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
2170 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
2171 // There's little point continuing compilation if the heap is exhausted.
2172 LOG(FATAL) << "Out of memory during type resolution for compilation";
2173 }
2174 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07002175 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002176 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002177
2178 private:
2179 const ParallelCompilationManager* const manager_;
2180};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002181
Andreas Gampeace0dc12016-01-20 13:33:13 -08002182void CompilerDriver::ResolveDexFile(jobject class_loader,
2183 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002184 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002185 ThreadPool* thread_pool,
2186 size_t thread_count,
2187 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002188 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2189
2190 // TODO: we could resolve strings here, although the string table is largely filled with class
2191 // and method names.
2192
Andreas Gampede7b4362014-07-28 18:38:57 -07002193 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2194 thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002195 if (IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002196 // For images we resolve all types, such as array, whereas for applications just those with
2197 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002198 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002199 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002200 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002201 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002202
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002203 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002204 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002205 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002206}
2207
Andreas Gampeace0dc12016-01-20 13:33:13 -08002208void CompilerDriver::SetVerified(jobject class_loader,
2209 const std::vector<const DexFile*>& dex_files,
2210 TimingLogger* timings) {
2211 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07002212 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002213 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002214 SetVerifiedDexFile(class_loader,
2215 *dex_file,
2216 dex_files,
2217 parallel_thread_pool_.get(),
2218 parallel_thread_count_,
2219 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002220 }
2221}
2222
Andreas Gampeace0dc12016-01-20 13:33:13 -08002223void CompilerDriver::Verify(jobject class_loader,
2224 const std::vector<const DexFile*>& dex_files,
2225 TimingLogger* timings) {
2226 // Note: verification should not be pulling in classes anymore when compiling the boot image,
2227 // as all should have been resolved before. As such, doing this in parallel should still
2228 // be deterministic.
Mathieu Chartier90443472015-07-16 20:32:27 -07002229 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002230 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002231 VerifyDexFile(class_loader,
2232 *dex_file,
2233 dex_files,
2234 parallel_thread_pool_.get(),
2235 parallel_thread_count_,
2236 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002237 }
2238}
2239
Mathieu Chartier90443472015-07-16 20:32:27 -07002240class VerifyClassVisitor : public CompilationVisitor {
2241 public:
Andreas Gampe7fe30232016-03-25 16:58:00 -07002242 VerifyClassVisitor(const ParallelCompilationManager* manager, LogSeverity log_level)
2243 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002244
Mathieu Chartier90443472015-07-16 20:32:27 -07002245 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2246 ATRACE_CALL();
2247 ScopedObjectAccess soa(Thread::Current());
2248 const DexFile& dex_file = *manager_->GetDexFile();
Mathieu Chartiera8077802016-03-16 19:08:31 -07002249 if (!manager_->GetCompiler()->ShouldVerifyClassBasedOnProfile(dex_file, class_def_index)) {
2250 // Skip verification since the class is not in the profile.
2251 return;
2252 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002253 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2254 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2255 ClassLinker* class_linker = manager_->GetClassLinker();
2256 jobject jclass_loader = manager_->GetClassLoader();
2257 StackHandleScope<3> hs(soa.Self());
2258 Handle<mirror::ClassLoader> class_loader(
2259 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2260 Handle<mirror::Class> klass(
2261 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2262 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002263 CHECK(soa.Self()->IsExceptionPending());
2264 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07002265
2266 /*
2267 * At compile time, we can still structurally verify the class even if FindClass fails.
2268 * This is to ensure the class is structurally sound for compilation. An unsound class
2269 * will be rejected by the verifier and later skipped during compilation in the compiler.
2270 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002271 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2272 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002273 std::string error_msg;
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002274 if (verifier::MethodVerifier::VerifyClass(soa.Self(),
2275 &dex_file,
2276 dex_cache,
2277 class_loader,
2278 &class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08002279 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002280 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07002281 log_level_,
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002282 &error_msg) ==
Mathieu Chartier90443472015-07-16 20:32:27 -07002283 verifier::MethodVerifier::kHardFailure) {
2284 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2285 << " because: " << error_msg;
2286 manager_->GetCompiler()->SetHadHardVerifierFailure();
2287 }
2288 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
2289 CHECK(klass->IsResolved()) << PrettyClass(klass.Get());
Andreas Gampe7fe30232016-03-25 16:58:00 -07002290 class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002291
2292 if (klass->IsErroneous()) {
2293 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2294 CHECK(soa.Self()->IsExceptionPending());
2295 soa.Self()->ClearException();
2296 manager_->GetCompiler()->SetHadHardVerifierFailure();
2297 }
2298
2299 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
2300 << PrettyDescriptor(klass.Get()) << ": state=" << klass->GetStatus();
2301
2302 // It is *very* problematic if there are verification errors in the boot classpath. For example,
2303 // we rely on things working OK without verification when the decryption dialog is brought up.
2304 // So abort in a debug build if we find this violated.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002305 DCHECK(!manager_->GetCompiler()->IsBootImage() || klass->IsVerified())
2306 << "Boot classpath class " << PrettyClass(klass.Get()) << " failed to fully verify.";
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002307 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002308 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002309 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002310
2311 private:
2312 const ParallelCompilationManager* const manager_;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002313 const LogSeverity log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002314};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002315
Andreas Gampeace0dc12016-01-20 13:33:13 -08002316void CompilerDriver::VerifyDexFile(jobject class_loader,
2317 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002318 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002319 ThreadPool* thread_pool,
2320 size_t thread_count,
2321 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002322 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002323 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002324 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2325 thread_pool);
Andreas Gampe7fe30232016-03-25 16:58:00 -07002326 LogSeverity log_level = GetCompilerOptions().AbortOnHardVerifierFailure()
2327 ? LogSeverity::INTERNAL_FATAL
2328 : LogSeverity::WARNING;
2329 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002330 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002331}
2332
Mathieu Chartier90443472015-07-16 20:32:27 -07002333class SetVerifiedClassVisitor : public CompilationVisitor {
2334 public:
2335 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2336
2337 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2338 ATRACE_CALL();
2339 ScopedObjectAccess soa(Thread::Current());
2340 const DexFile& dex_file = *manager_->GetDexFile();
2341 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2342 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2343 ClassLinker* class_linker = manager_->GetClassLinker();
2344 jobject jclass_loader = manager_->GetClassLoader();
2345 StackHandleScope<3> hs(soa.Self());
2346 Handle<mirror::ClassLoader> class_loader(
2347 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2348 Handle<mirror::Class> klass(
2349 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2350 // Class might have failed resolution. Then don't set it to verified.
2351 if (klass.Get() != nullptr) {
2352 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2353 // very wrong.
2354 if (klass->IsResolved()) {
2355 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
2356 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2357 // Set class status to verified.
2358 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self());
2359 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2360 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002361 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002362 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002363 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002364 }
2365 // Record the final class status if necessary.
2366 ClassReference ref(manager_->GetDexFile(), class_def_index);
2367 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002368 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002369 } else {
2370 Thread* self = soa.Self();
2371 DCHECK(self->IsExceptionPending());
2372 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002373 }
2374 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002375
2376 private:
2377 const ParallelCompilationManager* const manager_;
2378};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002379
Andreas Gampeace0dc12016-01-20 13:33:13 -08002380void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2381 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002382 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002383 ThreadPool* thread_pool,
2384 size_t thread_count,
2385 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002386 TimingLogger::ScopedTiming t("Verify Dex File", timings);
2387 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2388 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2389 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002390 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002391 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002392}
2393
Mathieu Chartier90443472015-07-16 20:32:27 -07002394class InitializeClassVisitor : public CompilationVisitor {
2395 public:
2396 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002397
Mathieu Chartier90443472015-07-16 20:32:27 -07002398 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2399 ATRACE_CALL();
2400 jobject jclass_loader = manager_->GetClassLoader();
2401 const DexFile& dex_file = *manager_->GetDexFile();
2402 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2403 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2404 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002405
Mathieu Chartier90443472015-07-16 20:32:27 -07002406 ScopedObjectAccess soa(Thread::Current());
2407 StackHandleScope<3> hs(soa.Self());
2408 Handle<mirror::ClassLoader> class_loader(
2409 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2410 Handle<mirror::Class> klass(
2411 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2412
2413 if (klass.Get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) {
2414 // Only try to initialize classes that were successfully verified.
2415 if (klass->IsVerified()) {
2416 // Attempt to initialize the class but bail if we either need to initialize the super-class
2417 // or static fields.
2418 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002419 if (!klass->IsInitialized()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002420 // We don't want non-trivial class initialization occurring on multiple threads due to
2421 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2422 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2423 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2424 // after first initializing its parents, whose locks are acquired. This leads to a
2425 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2426 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2427 // than use a special Object for the purpose we use the Class of java.lang.Class.
2428 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2429 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2430 // Attempt to initialize allowing initialization of parent classes but still not static
2431 // fields.
2432 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
2433 if (!klass->IsInitialized()) {
2434 // We need to initialize static fields, we only do this for image classes that aren't
2435 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002436 bool can_init_static_fields = manager_->GetCompiler()->IsBootImage() &&
Mathieu Chartier90443472015-07-16 20:32:27 -07002437 manager_->GetCompiler()->IsImageClass(descriptor) &&
2438 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2439 if (can_init_static_fields) {
2440 VLOG(compiler) << "Initializing: " << descriptor;
2441 // TODO multithreading support. We should ensure the current compilation thread has
2442 // exclusive access to the runtime and the transaction. To achieve this, we could use
2443 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2444 // checks in Thread::AssertThreadSuspensionIsAllowable.
2445 Runtime* const runtime = Runtime::Current();
2446 Transaction transaction;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002447
Mathieu Chartier90443472015-07-16 20:32:27 -07002448 // Run the class initializer in transaction mode.
2449 runtime->EnterTransactionMode(&transaction);
2450 const mirror::Class::Status old_status = klass->GetStatus();
2451 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2452 true);
2453 // TODO we detach transaction from runtime to indicate we quit the transactional
2454 // mode which prevents the GC from visiting objects modified during the transaction.
2455 // Ensure GC is not run so don't access freed objects when aborting transaction.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002456
Mathieu Chartier90443472015-07-16 20:32:27 -07002457 ScopedAssertNoThreadSuspension ants(soa.Self(), "Transaction end");
2458 runtime->ExitTransactionMode();
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002459
Mathieu Chartier90443472015-07-16 20:32:27 -07002460 if (!success) {
2461 CHECK(soa.Self()->IsExceptionPending());
2462 mirror::Throwable* exception = soa.Self()->GetException();
2463 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2464 << exception->Dump();
2465 std::ostream* file_log = manager_->GetCompiler()->
2466 GetCompilerOptions().GetInitFailureOutput();
2467 if (file_log != nullptr) {
2468 *file_log << descriptor << "\n";
2469 *file_log << exception->Dump() << "\n";
2470 }
2471 soa.Self()->ClearException();
2472 transaction.Rollback();
2473 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002474 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002475 }
2476 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002477 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002478 }
2479 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002480 // Record the final class status if necessary.
2481 ClassReference ref(manager_->GetDexFile(), class_def_index);
2482 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002483 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002484 // Clear any class not found or verification exceptions.
2485 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002486 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002487
2488 private:
2489 const ParallelCompilationManager* const manager_;
2490};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002491
Andreas Gampeace0dc12016-01-20 13:33:13 -08002492void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2493 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002494 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002495 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002496 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002497
2498 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2499 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2500 ThreadPool* init_thread_pool = force_determinism
2501 ? single_thread_pool_.get()
2502 : parallel_thread_pool_.get();
2503 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2504
Brian Carlstrom7940e442013-07-12 13:46:57 -07002505 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002506 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002507 init_thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002508 if (IsBootImage()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002509 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002510 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002511 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002512 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002513 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002514}
2515
Mathieu Chartier085a0722016-04-01 17:33:31 -07002516class InitializeArrayClassVisitor : public ClassVisitor {
2517 public:
2518 virtual bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
2519 if (klass->IsArrayClass()) {
2520 StackHandleScope<1> hs(Thread::Current());
2521 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(),
2522 hs.NewHandle(klass),
2523 true,
2524 true);
2525 }
2526 return true;
2527 }
2528};
2529
Brian Carlstrom7940e442013-07-12 13:46:57 -07002530void CompilerDriver::InitializeClasses(jobject class_loader,
2531 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002532 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002533 for (size_t i = 0; i != dex_files.size(); ++i) {
2534 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002535 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002536 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002537 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002538 {
2539 // Make sure that we call EnsureIntiailized on all the array classes to call
2540 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2541 // changed at runtime resulting in more dirty image pages.
2542 ScopedObjectAccess soa(Thread::Current());
2543 InitializeArrayClassVisitor visitor;
2544 Runtime::Current()->GetClassLinker()->VisitClasses(&visitor);
2545 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002546 if (IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002547 // Prune garbage objects created during aborted transactions.
2548 Runtime::Current()->GetHeap()->CollectGarbage(true);
2549 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002550}
2551
Andreas Gampeace0dc12016-01-20 13:33:13 -08002552void CompilerDriver::Compile(jobject class_loader,
2553 const std::vector<const DexFile*>& dex_files,
2554 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002555 if (kDebugProfileGuidedCompilation) {
2556 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2557 ((profile_compilation_info_ == nullptr)
2558 ? "null"
2559 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002560 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002561 for (size_t i = 0; i != dex_files.size(); ++i) {
2562 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002563 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002564 CompileDexFile(class_loader,
2565 *dex_file,
2566 dex_files,
2567 parallel_thread_pool_.get(),
2568 parallel_thread_count_,
2569 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002570 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2571 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2572 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002573 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002574 }
Andreas Gampe8d295f82015-01-20 14:50:21 -08002575 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002576}
2577
Mathieu Chartier90443472015-07-16 20:32:27 -07002578class CompileClassVisitor : public CompilationVisitor {
2579 public:
2580 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2581
2582 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2583 ATRACE_CALL();
2584 const DexFile& dex_file = *manager_->GetDexFile();
2585 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2586 ClassLinker* class_linker = manager_->GetClassLinker();
2587 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002588 ClassReference ref(&dex_file, class_def_index);
2589 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2590 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002591 return;
2592 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002593 // Use a scoped object access to perform to the quick SkipClass check.
2594 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2595 ScopedObjectAccess soa(Thread::Current());
2596 StackHandleScope<3> hs(soa.Self());
2597 Handle<mirror::ClassLoader> class_loader(
2598 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2599 Handle<mirror::Class> klass(
2600 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2601 Handle<mirror::DexCache> dex_cache;
2602 if (klass.Get() == nullptr) {
2603 soa.Self()->AssertPendingException();
2604 soa.Self()->ClearException();
2605 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2606 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2607 return;
2608 } else {
2609 dex_cache = hs.NewHandle(klass->GetDexCache());
2610 }
2611
Mathieu Chartier90443472015-07-16 20:32:27 -07002612 const uint8_t* class_data = dex_file.GetClassData(class_def);
2613 if (class_data == nullptr) {
2614 // empty class, probably a marker interface
2615 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002616 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002617
Mathieu Chartier736b5602015-09-02 14:54:11 -07002618 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002619 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002620
Mathieu Chartier90443472015-07-16 20:32:27 -07002621 CompilerDriver* const driver = manager_->GetCompiler();
2622
2623 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002624 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002625 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002626
Mathieu Chartier90443472015-07-16 20:32:27 -07002627 ClassDataItemIterator it(dex_file, class_data);
2628 // Skip fields
2629 while (it.HasNextStaticField()) {
2630 it.Next();
2631 }
2632 while (it.HasNextInstanceField()) {
2633 it.Next();
2634 }
2635
2636 bool compilation_enabled = driver->IsClassToCompile(
2637 dex_file.StringByTypeIdx(class_def.class_idx_));
2638
2639 // Compile direct methods
2640 int64_t previous_direct_method_idx = -1;
2641 while (it.HasNextDirectMethod()) {
2642 uint32_t method_idx = it.GetMemberIndex();
2643 if (method_idx == previous_direct_method_idx) {
2644 // smali can create dex files with two encoded_methods sharing the same method_idx
2645 // http://code.google.com/p/smali/issues/detail?id=119
2646 it.Next();
2647 continue;
2648 }
2649 previous_direct_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002650 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002651 it.GetMethodInvokeType(class_def), class_def_index,
2652 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002653 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002654 it.Next();
2655 }
2656 // Compile virtual methods
2657 int64_t previous_virtual_method_idx = -1;
2658 while (it.HasNextVirtualMethod()) {
2659 uint32_t method_idx = it.GetMemberIndex();
2660 if (method_idx == previous_virtual_method_idx) {
2661 // smali can create dex files with two encoded_methods sharing the same method_idx
2662 // http://code.google.com/p/smali/issues/detail?id=119
2663 it.Next();
2664 continue;
2665 }
2666 previous_virtual_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002667 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002668 it.GetMethodInvokeType(class_def), class_def_index,
2669 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002670 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002671 it.Next();
2672 }
2673 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002674 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002675
2676 private:
2677 const ParallelCompilationManager* const manager_;
2678};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002679
Andreas Gampeace0dc12016-01-20 13:33:13 -08002680void CompilerDriver::CompileDexFile(jobject class_loader,
2681 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002682 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002683 ThreadPool* thread_pool,
2684 size_t thread_count,
2685 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002686 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002687 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002688 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002689 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002690 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002691}
2692
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002693void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2694 CompiledMethod* const compiled_method,
2695 size_t non_relative_linker_patch_count) {
2696 DCHECK(GetCompiledMethod(method_ref) == nullptr)
2697 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
2698 {
2699 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2700 compiled_methods_.Put(method_ref, compiled_method);
2701 non_relative_linker_patch_count_ += non_relative_linker_patch_count;
Ian Rogersa4a3f402014-10-20 18:10:34 -07002702 }
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002703 DCHECK(GetCompiledMethod(method_ref) != nullptr)
2704 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002705}
2706
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002707void CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2708 CompiledMethod* compiled_method = nullptr;
2709 {
2710 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2711 auto it = compiled_methods_.find(method_ref);
2712 if (it != compiled_methods_.end()) {
2713 compiled_method = it->second;
2714 compiled_methods_.erase(it);
2715 }
2716 }
2717 if (compiled_method != nullptr) {
2718 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, compiled_method);
2719 }
2720}
2721
Brian Carlstrom7940e442013-07-12 13:46:57 -07002722CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
2723 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2724 ClassTable::const_iterator it = compiled_classes_.find(ref);
2725 if (it == compiled_classes_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002726 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002727 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002728 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002729 return it->second;
2730}
2731
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002732void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2733 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2734 auto it = compiled_classes_.find(ref);
2735 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2736 // An entry doesn't exist or the status is lower than the new status.
2737 if (it != compiled_classes_.end()) {
2738 CHECK_GT(status, it->second->GetStatus());
2739 delete it->second;
2740 }
2741 switch (status) {
2742 case mirror::Class::kStatusNotReady:
2743 case mirror::Class::kStatusError:
2744 case mirror::Class::kStatusRetryVerificationAtRuntime:
2745 case mirror::Class::kStatusVerified:
2746 case mirror::Class::kStatusInitialized:
Mathieu Chartiera8077802016-03-16 19:08:31 -07002747 case mirror::Class::kStatusResolved:
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002748 break; // Expected states.
2749 default:
2750 LOG(FATAL) << "Unexpected class status for class "
2751 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2752 << " of " << status;
2753 }
2754 CompiledClass* compiled_class = new CompiledClass(status);
2755 compiled_classes_.Overwrite(ref, compiled_class);
2756 }
2757}
2758
Brian Carlstrom7940e442013-07-12 13:46:57 -07002759CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2760 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2761 MethodTable::const_iterator it = compiled_methods_.find(ref);
2762 if (it == compiled_methods_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002763 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002764 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002765 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002766 return it->second;
2767}
2768
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002769bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2770 uint16_t class_def_idx,
2771 const DexFile& dex_file) const {
2772 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2773 if (verified_method != nullptr) {
2774 return !verified_method->HasVerificationFailures();
2775 }
2776
2777 // If we can't find verification metadata, check if this is a system class (we trust that system
2778 // classes have their methods verified). If it's not, be conservative and assume the method
2779 // has not been verified successfully.
2780
2781 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2782 // even if methods are not found in the verification cache.
2783 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2784 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2785 Thread* self = Thread::Current();
2786 ScopedObjectAccess soa(self);
2787 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2788 if (!is_system_class) {
2789 self->ClearException();
2790 }
2791 return is_system_class;
2792}
2793
Vladimir Markof4da6752014-08-01 19:04:18 +01002794size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
2795 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2796 return non_relative_linker_patch_count_;
2797}
2798
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002799void CompilerDriver::SetRequiresConstructorBarrier(Thread* self,
2800 const DexFile* dex_file,
2801 uint16_t class_def_index,
2802 bool requires) {
2803 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2804 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002805}
2806
Mathieu Chartier371bd832016-04-07 10:19:48 -07002807bool CompilerDriver::RequiresConstructorBarrier(Thread* self,
2808 const DexFile* dex_file,
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002809 uint16_t class_def_index) {
2810 ClassReference class_ref(dex_file, class_def_index);
2811 {
2812 ReaderMutexLock mu(self, requires_constructor_barrier_lock_);
2813 auto it = requires_constructor_barrier_.find(class_ref);
2814 if (it != requires_constructor_barrier_.end()) {
2815 return it->second;
2816 }
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002817 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002818 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2819 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index);
2820 requires_constructor_barrier_.emplace(class_ref, requires);
2821 return requires;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002822}
2823
Andreas Gampe8d295f82015-01-20 14:50:21 -08002824std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002825 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002826 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002827 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002828 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002829 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002830#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002831 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002832 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2833 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002834 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2835 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002836#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002837 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002838 return oss.str();
2839}
2840
Jeff Hao848f70a2014-01-15 13:49:50 -08002841bool CompilerDriver::IsStringTypeIndex(uint16_t type_index, const DexFile* dex_file) {
2842 const char* type = dex_file->GetTypeDescriptor(dex_file->GetTypeId(type_index));
2843 return strcmp(type, "Ljava/lang/String;") == 0;
2844}
2845
2846bool CompilerDriver::IsStringInit(uint32_t method_index, const DexFile* dex_file, int32_t* offset) {
2847 DexFileMethodInliner* inliner = GetMethodInlinerMap()->GetMethodInliner(dex_file);
2848 size_t pointer_size = InstructionSetPointerSize(GetInstructionSet());
2849 *offset = inliner->GetOffsetForStringInit(method_index, pointer_size);
2850 return inliner->IsStringInitMethodIndex(method_index);
2851}
2852
Jeff Haodcdc85b2015-12-04 14:06:18 -08002853bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
2854 const DexFile* inlined_into) const {
2855 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
2856 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00002857 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
2858 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002859 return false;
2860 }
2861
2862 return true;
2863}
2864
Andreas Gampeace0dc12016-01-20 13:33:13 -08002865void CompilerDriver::InitializeThreadPools() {
2866 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2867 parallel_thread_pool_.reset(
2868 new ThreadPool("Compiler driver thread pool", parallel_count));
2869 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2870}
2871
2872void CompilerDriver::FreeThreadPools() {
2873 parallel_thread_pool_.reset();
2874 single_thread_pool_.reset();
2875}
2876
Brian Carlstrom7940e442013-07-12 13:46:57 -07002877} // namespace art