blob: e41f7e61eabba474dfc781549160ab81bdcc3630 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "compiler_driver.h"
18
Andreas Gampeb0f370e2014-09-25 22:51:40 -070019#include <unordered_set>
Anwar Ghuloum67f99412013-08-12 14:19:48 -070020#include <vector>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021#include <unistd.h>
22
Mathieu Chartierab972ef2014-12-03 17:38:22 -080023#ifndef __APPLE__
24#include <malloc.h> // For mallinfo
25#endif
26
Mathieu Chartierc7853442015-03-27 14:35:38 -070027#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070028#include "art_method-inl.h"
David Brazdild9c90372016-09-14 16:53:55 +010029#include "base/array_ref.h"
Vladimir Marko492a7fa2016-06-01 18:38:43 +010030#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070031#include "base/enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080033#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010034#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070035#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010036#include "class_linker-inl.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070037#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000038#include "compiled_method.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000039#include "compiler.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000040#include "compiler_driver-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "dex_compilation_unit.h"
42#include "dex_file-inl.h"
Andreas Gampeace0dc12016-01-20 13:33:13 -080043#include "dex_instruction-inl.h"
Andreas Gampe5eb0d382015-07-23 01:19:26 -070044#include "dex/dex_to_dex_compiler.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000045#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000046#include "dex/verified_method.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080047#include "driver/compiler_options.h"
Nicolas Geoffray762869d2016-07-15 15:28:35 +010048#include "intrinsics_enum.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "jni_internal.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070050#include "object_lock.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "runtime.h"
52#include "gc/accounting/card_table-inl.h"
53#include "gc/accounting/heap_bitmap.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070054#include "gc/space/image_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "gc/space/space.h"
56#include "mirror/class_loader.h"
57#include "mirror/class-inl.h"
58#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "mirror/object-inl.h"
60#include "mirror/object_array-inl.h"
61#include "mirror/throwable.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070062#include "scoped_thread_state_change-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063#include "ScopedLocalRef.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070064#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "thread.h"
Andreas Gampeb0f370e2014-09-25 22:51:40 -070066#include "thread_list.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070068#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010069#include "transaction.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000070#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampee21dc3d2014-12-08 16:59:43 -080071#include "utils/swap_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070072#include "verifier/method_verifier.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000073#include "verifier/method_verifier-inl.h"
Andreas Gampe5fd66d02016-09-12 20:22:19 -070074#include "verifier/verifier_log_mode.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075
Brian Carlstrom7940e442013-07-12 13:46:57 -070076namespace art {
77
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070078static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
79
Calin Juravle226501b2015-12-11 14:41:31 +000080// Print additional info during profile guided compilation.
81static constexpr bool kDebugProfileGuidedCompilation = false;
82
Brian Carlstrom7940e442013-07-12 13:46:57 -070083static double Percentage(size_t x, size_t y) {
84 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
85}
86
87static void DumpStat(size_t x, size_t y, const char* str) {
88 if (x == 0 && y == 0) {
89 return;
90 }
Ian Rogerse732ef12013-10-09 15:22:24 -070091 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -070092}
93
Vladimir Markof096aad2014-01-23 15:51:58 +000094class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -070095 public:
96 AOTCompilationStats()
97 : stats_lock_("AOT compilation statistics lock"),
98 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
99 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
100 resolved_types_(0), unresolved_types_(0),
101 resolved_instance_fields_(0), unresolved_instance_fields_(0),
102 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
103 type_based_devirtualization_(0),
104 safe_casts_(0), not_safe_casts_(0) {
105 for (size_t i = 0; i <= kMaxInvokeType; i++) {
106 resolved_methods_[i] = 0;
107 unresolved_methods_[i] = 0;
108 virtual_made_direct_[i] = 0;
109 direct_calls_to_boot_[i] = 0;
110 direct_methods_to_boot_[i] = 0;
111 }
112 }
113
114 void Dump() {
115 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
116 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
117 DumpStat(resolved_types_, unresolved_types_, "types resolved");
118 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
119 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
120 "static fields resolved");
121 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
122 "static fields local to a class");
123 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
124 // Note, the code below subtracts the stat value so that when added to the stat value we have
125 // 100% of samples. TODO: clean this up.
126 DumpStat(type_based_devirtualization_,
127 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
128 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
129 type_based_devirtualization_,
130 "virtual/interface calls made direct based on type information");
131
132 for (size_t i = 0; i <= kMaxInvokeType; i++) {
133 std::ostringstream oss;
134 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
135 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
136 if (virtual_made_direct_[i] > 0) {
137 std::ostringstream oss2;
138 oss2 << static_cast<InvokeType>(i) << " methods made direct";
139 DumpStat(virtual_made_direct_[i],
140 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
141 oss2.str().c_str());
142 }
143 if (direct_calls_to_boot_[i] > 0) {
144 std::ostringstream oss2;
145 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
146 DumpStat(direct_calls_to_boot_[i],
147 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
148 oss2.str().c_str());
149 }
150 if (direct_methods_to_boot_[i] > 0) {
151 std::ostringstream oss2;
152 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
153 DumpStat(direct_methods_to_boot_[i],
154 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
155 oss2.str().c_str());
156 }
157 }
158 }
159
160// Allow lossy statistics in non-debug builds.
161#ifndef NDEBUG
162#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
163#else
164#define STATS_LOCK()
165#endif
166
Mathieu Chartier90443472015-07-16 20:32:27 -0700167 void TypeInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700168 STATS_LOCK();
169 types_in_dex_cache_++;
170 }
171
Mathieu Chartier90443472015-07-16 20:32:27 -0700172 void TypeNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700173 STATS_LOCK();
174 types_not_in_dex_cache_++;
175 }
176
Mathieu Chartier90443472015-07-16 20:32:27 -0700177 void StringInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 STATS_LOCK();
179 strings_in_dex_cache_++;
180 }
181
Mathieu Chartier90443472015-07-16 20:32:27 -0700182 void StringNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700183 STATS_LOCK();
184 strings_not_in_dex_cache_++;
185 }
186
Mathieu Chartier90443472015-07-16 20:32:27 -0700187 void TypeDoesntNeedAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188 STATS_LOCK();
189 resolved_types_++;
190 }
191
Mathieu Chartier90443472015-07-16 20:32:27 -0700192 void TypeNeedsAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700193 STATS_LOCK();
194 unresolved_types_++;
195 }
196
Mathieu Chartier90443472015-07-16 20:32:27 -0700197 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700198 STATS_LOCK();
199 resolved_instance_fields_++;
200 }
201
Mathieu Chartier90443472015-07-16 20:32:27 -0700202 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 STATS_LOCK();
204 unresolved_instance_fields_++;
205 }
206
Mathieu Chartier90443472015-07-16 20:32:27 -0700207 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700208 STATS_LOCK();
209 resolved_local_static_fields_++;
210 }
211
Mathieu Chartier90443472015-07-16 20:32:27 -0700212 void ResolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700213 STATS_LOCK();
214 resolved_static_fields_++;
215 }
216
Mathieu Chartier90443472015-07-16 20:32:27 -0700217 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 STATS_LOCK();
219 unresolved_static_fields_++;
220 }
221
222 // Indicate that type information from the verifier led to devirtualization.
Mathieu Chartier90443472015-07-16 20:32:27 -0700223 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700224 STATS_LOCK();
225 type_based_devirtualization_++;
226 }
227
228 // Indicate that a method of the given type was resolved at compile time.
Mathieu Chartier90443472015-07-16 20:32:27 -0700229 void ResolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700230 DCHECK_LE(type, kMaxInvokeType);
231 STATS_LOCK();
232 resolved_methods_[type]++;
233 }
234
235 // Indicate that a method of the given type was unresolved at compile time as it was in an
236 // unknown dex file.
Mathieu Chartier90443472015-07-16 20:32:27 -0700237 void UnresolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700238 DCHECK_LE(type, kMaxInvokeType);
239 STATS_LOCK();
240 unresolved_methods_[type]++;
241 }
242
243 // Indicate that a type of virtual method dispatch has been converted into a direct method
244 // dispatch.
Mathieu Chartier90443472015-07-16 20:32:27 -0700245 void VirtualMadeDirect(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700246 DCHECK(type == kVirtual || type == kInterface || type == kSuper);
247 STATS_LOCK();
248 virtual_made_direct_[type]++;
249 }
250
251 // Indicate that a method of the given type was able to call directly into boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700252 void DirectCallsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700253 DCHECK_LE(type, kMaxInvokeType);
254 STATS_LOCK();
255 direct_calls_to_boot_[type]++;
256 }
257
258 // Indicate that a method of the given type was able to be resolved directly from boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700259 void DirectMethodsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700260 DCHECK_LE(type, kMaxInvokeType);
261 STATS_LOCK();
262 direct_methods_to_boot_[type]++;
263 }
264
Mathieu Chartier90443472015-07-16 20:32:27 -0700265 void ProcessedInvoke(InvokeType type, int flags) REQUIRES(!stats_lock_) {
Vladimir Markof096aad2014-01-23 15:51:58 +0000266 STATS_LOCK();
267 if (flags == 0) {
268 unresolved_methods_[type]++;
269 } else {
270 DCHECK_NE((flags & kFlagMethodResolved), 0);
271 resolved_methods_[type]++;
272 if ((flags & kFlagVirtualMadeDirect) != 0) {
273 virtual_made_direct_[type]++;
274 if ((flags & kFlagPreciseTypeDevirtualization) != 0) {
275 type_based_devirtualization_++;
276 }
277 } else {
278 DCHECK_EQ((flags & kFlagPreciseTypeDevirtualization), 0);
279 }
280 if ((flags & kFlagDirectCallToBoot) != 0) {
281 direct_calls_to_boot_[type]++;
282 }
283 if ((flags & kFlagDirectMethodToBoot) != 0) {
284 direct_methods_to_boot_[type]++;
285 }
286 }
287 }
288
Brian Carlstrom7940e442013-07-12 13:46:57 -0700289 // A check-cast could be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700290 void SafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291 STATS_LOCK();
292 safe_casts_++;
293 }
294
295 // A check-cast couldn't be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700296 void NotASafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700297 STATS_LOCK();
298 not_safe_casts_++;
299 }
300
301 private:
302 Mutex stats_lock_;
303
304 size_t types_in_dex_cache_;
305 size_t types_not_in_dex_cache_;
306
307 size_t strings_in_dex_cache_;
308 size_t strings_not_in_dex_cache_;
309
310 size_t resolved_types_;
311 size_t unresolved_types_;
312
313 size_t resolved_instance_fields_;
314 size_t unresolved_instance_fields_;
315
316 size_t resolved_local_static_fields_;
317 size_t resolved_static_fields_;
318 size_t unresolved_static_fields_;
319 // Type based devirtualization for invoke interface and virtual.
320 size_t type_based_devirtualization_;
321
322 size_t resolved_methods_[kMaxInvokeType + 1];
323 size_t unresolved_methods_[kMaxInvokeType + 1];
324 size_t virtual_made_direct_[kMaxInvokeType + 1];
325 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
326 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
327
328 size_t safe_casts_;
329 size_t not_safe_casts_;
330
331 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
332};
333
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100334class CompilerDriver::DexFileMethodSet {
335 public:
336 explicit DexFileMethodSet(const DexFile& dex_file)
337 : dex_file_(dex_file),
338 method_indexes_(dex_file.NumMethodIds(), false, Allocator::GetMallocAllocator()) {
339 }
340 DexFileMethodSet(DexFileMethodSet&& other) = default;
341
342 const DexFile& GetDexFile() const { return dex_file_; }
343
344 BitVector& GetMethodIndexes() { return method_indexes_; }
345 const BitVector& GetMethodIndexes() const { return method_indexes_; }
346
347 private:
348 const DexFile& dex_file_;
349 BitVector method_indexes_;
350};
351
Jeff Haodcdc85b2015-12-04 14:06:18 -0800352CompilerDriver::CompilerDriver(
353 const CompilerOptions* compiler_options,
354 VerificationResults* verification_results,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800355 Compiler::Kind compiler_kind,
356 InstructionSet instruction_set,
357 const InstructionSetFeatures* instruction_set_features,
Vladimir Marko5f926052016-09-30 17:04:49 +0000358 bool boot_image,
359 bool app_image,
Vladimir Marko944da602016-02-19 12:27:55 +0000360 std::unordered_set<std::string>* image_classes,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800361 std::unordered_set<std::string>* compiled_classes,
362 std::unordered_set<std::string>* compiled_methods,
Vladimir Marko944da602016-02-19 12:27:55 +0000363 size_t thread_count,
364 bool dump_stats,
365 bool dump_passes,
366 CumulativeLogger* timer,
367 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200368 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000369 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800370 verification_results_(verification_results),
Ian Rogers72d32622014-05-06 16:20:11 -0700371 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700372 compiler_kind_(compiler_kind),
Artem Serovba6b6792016-08-15 14:22:07 +0100373 instruction_set_(instruction_set == kArm ? kThumb2: instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700374 instruction_set_features_(instruction_set_features),
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700375 requires_constructor_barrier_lock_("constructor barrier lock"),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700376 compiled_classes_lock_("compiled classes lock"),
377 compiled_methods_lock_("compiled method lock"),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800378 compiled_methods_(MethodTable::key_compare()),
Vladimir Markof4da6752014-08-01 19:04:18 +0100379 non_relative_linker_patch_count_(0u),
Vladimir Marko5f926052016-09-30 17:04:49 +0000380 boot_image_(boot_image),
381 app_image_(app_image),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700382 image_classes_(image_classes),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800383 classes_to_compile_(compiled_classes),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700384 methods_to_compile_(compiled_methods),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800385 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800386 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700387 stats_(new AOTCompilationStats),
388 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000389 dump_passes_(dump_passes),
390 timings_logger_(timer),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700391 compiler_context_(nullptr),
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700392 support_boot_image_fixup_(instruction_set != kMips64),
Vladimir Markod1eaf0d2015-10-29 12:18:29 +0000393 dex_files_for_oat_file_(nullptr),
Calin Juravle998c2162015-12-21 15:39:33 +0200394 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000395 profile_compilation_info_(profile_compilation_info),
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100396 max_arena_alloc_(0),
397 dex_to_dex_references_lock_("dex-to-dex references lock"),
398 dex_to_dex_references_(),
399 current_dex_to_dex_methods_(nullptr) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800400 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700401
Ian Rogers72d32622014-05-06 16:20:11 -0700402 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700403
Mathieu Chartiera8077802016-03-16 19:08:31 -0700404 if (compiler_options->VerifyOnlyProfile()) {
405 CHECK(profile_compilation_info_ != nullptr) << "Requires profile";
406 }
Vladimir Marko5f926052016-09-30 17:04:49 +0000407 if (boot_image_) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800408 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image";
409 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700410}
411
412CompilerDriver::~CompilerDriver() {
413 Thread* self = Thread::Current();
414 {
415 MutexLock mu(self, compiled_classes_lock_);
416 STLDeleteValues(&compiled_classes_);
417 }
418 {
419 MutexLock mu(self, compiled_methods_lock_);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800420 for (auto& pair : compiled_methods_) {
421 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, pair.second);
422 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700423 }
Ian Rogers72d32622014-05-06 16:20:11 -0700424 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700425}
426
Vladimir Marko35831e82015-09-11 11:59:18 +0100427
Ian Rogersdd7624d2014-03-14 17:43:00 -0700428#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700429 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700430 return CreateTrampoline64(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700431 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700432 } else { \
433 return CreateTrampoline32(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700434 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700435 }
436
Vladimir Marko93205e32016-04-13 11:59:46 +0100437std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700438 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700439}
440
Vladimir Marko93205e32016-04-13 11:59:46 +0100441std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
442 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700443 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800444}
445
Vladimir Marko93205e32016-04-13 11:59:46 +0100446std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
447 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700448 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700449}
450
Vladimir Marko93205e32016-04-13 11:59:46 +0100451std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
452 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700453 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700454}
455
Vladimir Marko93205e32016-04-13 11:59:46 +0100456std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
457 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700458 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700459}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700460#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700461
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100462static void SetupIntrinsic(Thread* self,
463 Intrinsics intrinsic,
464 InvokeType invoke_type,
465 const char* class_name,
466 const char* method_name,
467 const char* signature)
468 REQUIRES_SHARED(Locks::mutator_lock_) {
469 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
470 PointerSize image_size = class_linker->GetImagePointerSize();
471 mirror::Class* cls = class_linker->FindSystemClass(self, class_name);
472 if (cls == nullptr) {
473 LOG(FATAL) << "Could not find class of intrinsic " << class_name;
474 }
475 ArtMethod* method = (invoke_type == kStatic || invoke_type == kDirect)
476 ? cls->FindDeclaredDirectMethod(method_name, signature, image_size)
477 : cls->FindDeclaredVirtualMethod(method_name, signature, image_size);
478 if (method == nullptr) {
Nicolas Geoffrayb20f1fe2016-10-03 13:57:40 +0100479 LOG(FATAL) << "Could not find method of intrinsic "
480 << class_name << " " << method_name << " " << signature;
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100481 }
482 DCHECK_EQ(method->GetInvokeType(), invoke_type);
483 method->SetIntrinsic(static_cast<uint32_t>(intrinsic));
484}
485
Brian Carlstrom7940e442013-07-12 13:46:57 -0700486void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700487 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800488 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700489 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800490
491 InitializeThreadPools();
492
Andreas Gampe8d295f82015-01-20 14:50:21 -0800493 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
Andreas Gampe740667a2015-09-15 17:55:06 -0700494 // Precompile:
495 // 1) Load image classes
496 // 2) Resolve all classes
497 // 3) Attempt to verify all classes
498 // 4) Attempt to initialize image classes, and trivially initialized classes
Andreas Gampeace0dc12016-01-20 13:33:13 -0800499 PreCompile(class_loader, dex_files, timings);
Vladimir Marko5f926052016-09-30 17:04:49 +0000500 if (IsBootImage()) {
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100501 // We don't need to setup the intrinsics for non boot image compilation, as
502 // those compilations will pick up a boot image that have the ArtMethod already
503 // set with the intrinsics flag.
504 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffrayb20f1fe2016-10-03 13:57:40 +0100505#define SETUP_INTRINSICS(Name, InvokeType, NeedsEnvironmentOrCache, SideEffects, Exceptions, \
506 ClassName, MethodName, Signature) \
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100507 SetupIntrinsic(soa.Self(), Intrinsics::k##Name, InvokeType, ClassName, MethodName, Signature);
508#include "intrinsics_list.h"
Nicolas Geoffrayb20f1fe2016-10-03 13:57:40 +0100509INTRINSICS_LIST(SETUP_INTRINSICS)
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100510#undef INTRINSICS_LIST
Nicolas Geoffrayb20f1fe2016-10-03 13:57:40 +0100511#undef SETUP_INTRINSICS
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100512 }
Andreas Gampe740667a2015-09-15 17:55:06 -0700513 // Compile:
514 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
515 // compilation.
516 if (!GetCompilerOptions().VerifyAtRuntime()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800517 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700518 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700519 if (dump_stats_) {
520 stats_->Dump();
521 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800522
523 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700524}
525
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700526static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
527 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
528 const DexFile& dex_file, const DexFile::ClassDef& class_def)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700529 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800530 auto* const runtime = Runtime::Current();
Calin Juravleffc87072016-04-20 14:22:09 +0100531 if (runtime->UseJitCompilation() || driver.GetCompilerOptions().VerifyAtRuntime()) {
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700532 // Verify at runtime shouldn't dex to dex since we didn't resolve of verify.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700533 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800534 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700535 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800536 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800537 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700538 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700539 CHECK(self->IsExceptionPending());
540 self->ClearException();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700541 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700542 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700543 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
544 // references with actual offsets. We cannot re-verify such instructions.
545 //
546 // We store the verification information in the class status in the oat file, which the linker
547 // can validate (checksums) and use to skip load-time verification. It is thus safe to
548 // optimize when a class has been fully verified before.
549 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200550 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700551 return optimizer::DexToDexCompilationLevel::kOptimize;
Sebastien Hertz75021222013-07-16 18:34:50 +0200552 } else if (klass->IsCompileTimeVerified()) {
553 // Class verification has soft-failed. Anyway, ensure at least correctness.
554 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700555 return optimizer::DexToDexCompilationLevel::kRequired;
Sebastien Hertz75021222013-07-16 18:34:50 +0200556 } else {
557 // Class verification has failed: do not run DEX-to-DEX compilation.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700558 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
559 }
560}
561
562static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
563 Thread* self,
564 const CompilerDriver& driver,
565 jobject jclass_loader,
566 const DexFile& dex_file,
567 const DexFile::ClassDef& class_def) {
568 ScopedObjectAccess soa(self);
569 StackHandleScope<1> hs(soa.Self());
570 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700571 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700572 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
573}
574
575// Does the runtime for the InstructionSet provide an implementation returned by
576// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
577static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
578 switch (isa) {
579 case kArm:
580 case kArm64:
581 case kThumb2:
582 case kMips:
583 case kMips64:
584 case kX86:
585 case kX86_64: return true;
586 default: return false;
587 }
588}
589
590static void CompileMethod(Thread* self,
591 CompilerDriver* driver,
592 const DexFile::CodeItem* code_item,
593 uint32_t access_flags,
594 InvokeType invoke_type,
595 uint16_t class_def_idx,
596 uint32_t method_idx,
597 jobject class_loader,
598 const DexFile& dex_file,
599 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700600 bool compilation_enabled,
601 Handle<mirror::DexCache> dex_cache)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700602 REQUIRES(!driver->compiled_methods_lock_) {
603 DCHECK(driver != nullptr);
604 CompiledMethod* compiled_method = nullptr;
605 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
606 MethodReference method_ref(&dex_file, method_idx);
607
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100608 if (driver->GetCurrentDexToDexMethods() != nullptr) {
609 // This is the second pass when we dex-to-dex compile previously marked methods.
610 // TODO: Refactor the compilation to avoid having to distinguish the two passes
611 // here. That should be done on a higher level. http://b/29089975
612 if (driver->GetCurrentDexToDexMethods()->IsBitSet(method_idx)) {
613 const VerifiedMethod* verified_method =
614 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
615 // Do not optimize if a VerifiedMethod is missing. SafeCast elision,
616 // for example, relies on it.
617 compiled_method = optimizer::ArtCompileDEX(
618 driver,
619 code_item,
620 access_flags,
621 invoke_type,
622 class_def_idx,
623 method_idx,
624 class_loader,
625 dex_file,
626 (verified_method != nullptr)
627 ? dex_to_dex_compilation_level
628 : optimizer::DexToDexCompilationLevel::kRequired);
629 }
630 } else if ((access_flags & kAccNative) != 0) {
Igor Murashkin9aa9fa22016-09-26 10:10:17 -0700631 const InstructionSet instruction_set = driver->GetInstructionSet();
632 const bool use_generic_jni =
633 // Are we extracting only and have support for generic JNI down calls?
634 (!driver->GetCompilerOptions().IsJniCompilationEnabled() &&
635 InstructionSetHasGenericJniStub(instruction_set)) ||
636 // Always punt to generic JNI for MIPS because of no support for @CriticalNative. b/31743474
637 (instruction_set == kMips || instruction_set == kMips64);
638 if (use_generic_jni) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700639 // Leaving this empty will trigger the generic JNI version
640 } else {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700641 // Look-up the ArtMethod associated with this code_item (if any)
642 // -- It is later used to lookup any [optimization] annotations for this method.
643 ScopedObjectAccess soa(self);
644 StackHandleScope<1> hs(soa.Self());
645 Handle<mirror::ClassLoader> class_loader_handle(hs.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700646 soa.Decode<mirror::ClassLoader>(class_loader)));
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700647
648 // TODO: Lookup annotation from DexFile directly without resolving method.
649 ArtMethod* method =
650 Runtime::Current()->GetClassLinker()->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
651 dex_file,
652 method_idx,
653 dex_cache,
654 class_loader_handle,
655 /* referrer */ nullptr,
656 invoke_type);
657
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700658 // Query any JNI optimization annotations such as @FastNative or @CriticalNative.
659 Compiler::JniOptimizationFlags optimization_flags = Compiler::kNone;
660 if (UNLIKELY(method == nullptr)) {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700661 // Failed method resolutions happen very rarely, e.g. ancestor class cannot be resolved.
662 DCHECK(self->IsExceptionPending());
663 self->ClearException();
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700664 } else if (method->IsAnnotatedWithFastNative()) {
665 // TODO: Will no longer need this CHECK once we have verifier checking this.
666 CHECK(!method->IsAnnotatedWithCriticalNative());
667 optimization_flags = Compiler::kFastNative;
668 } else if (method->IsAnnotatedWithCriticalNative()) {
669 // TODO: Will no longer need this CHECK once we have verifier checking this.
670 CHECK(!method->IsAnnotatedWithFastNative());
671 optimization_flags = Compiler::kCriticalNative;
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700672 }
673
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700674 compiled_method = driver->GetCompiler()->JniCompile(access_flags,
675 method_idx,
676 dex_file,
677 optimization_flags);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700678 CHECK(compiled_method != nullptr);
679 }
680 } else if ((access_flags & kAccAbstract) != 0) {
681 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000682 } else {
Andreas Gampe0760a812015-08-26 17:12:51 -0700683 const VerifiedMethod* verified_method =
684 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700685 bool compile = compilation_enabled &&
686 // Basic checks, e.g., not <clinit>.
687 driver->GetVerificationResults()
688 ->IsCandidateForCompilation(method_ref, access_flags) &&
689 // Did not fail to create VerifiedMethod metadata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700690 verified_method != nullptr &&
691 // Do not have failures that should punt to the interpreter.
692 !verified_method->HasRuntimeThrow() &&
693 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700694 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700695 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000696 driver->IsMethodToCompile(method_ref) &&
697 driver->ShouldCompileBasedOnProfile(method_ref);
698
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700699 if (compile) {
700 // NOTE: if compiler declines to compile this method, it will return null.
701 compiled_method = driver->GetCompiler()->Compile(code_item, access_flags, invoke_type,
702 class_def_idx, method_idx, class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700703 dex_file, dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700704 }
705 if (compiled_method == nullptr &&
706 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100707 DCHECK(!Runtime::Current()->UseJitCompilation());
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700708 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100709 driver->MarkForDexToDexCompilation(self, method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700710 }
711 }
712 if (kTimeCompileMethod) {
713 uint64_t duration_ns = NanoTime() - start_ns;
714 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
715 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
716 << " took " << PrettyDuration(duration_ns);
717 }
718 }
719
720 if (compiled_method != nullptr) {
721 // Count non-relative linker patches.
722 size_t non_relative_linker_patch_count = 0u;
723 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
724 if (!patch.IsPcRelative()) {
725 ++non_relative_linker_patch_count;
726 }
727 }
728 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
729 // When compiling with PIC, there should be zero non-relative linker patches
730 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
731
732 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
733 }
734
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700735 if (self->IsExceptionPending()) {
736 ScopedObjectAccess soa(self);
737 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
738 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200739 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700740}
741
Mathieu Chartiere401d142015-04-22 13:56:20 -0700742void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700743 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700744 jobject jclass_loader;
745 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700746 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800747 uint32_t method_idx = method->GetDexMethodIndex();
748 uint32_t access_flags = method->GetAccessFlags();
749 InvokeType invoke_type = method->GetInvokeType();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700750 StackHandleScope<1> hs(self);
751 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700752 {
753 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800754 ScopedLocalRef<jobject> local_class_loader(
755 soa.Env(), soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700756 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
757 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700758 dex_file = method->GetDexFile();
759 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700760 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800761 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700762
763 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700764 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700765
766 std::vector<const DexFile*> dex_files;
767 dex_files.push_back(dex_file);
768
Andreas Gampeace0dc12016-01-20 13:33:13 -0800769 InitializeThreadPools();
770
771 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700772
Brian Carlstrom7940e442013-07-12 13:46:57 -0700773 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700774 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
775 GetDexToDexCompilationLevel(self,
776 *this,
777 jclass_loader,
778 *dex_file,
779 dex_file->GetClassDef(class_def_idx));
780
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100781 DCHECK(current_dex_to_dex_methods_ == nullptr);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700782 CompileMethod(self,
783 this,
784 code_item,
785 access_flags,
786 invoke_type,
787 class_def_idx,
788 method_idx,
789 jclass_loader,
790 *dex_file,
791 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700792 true,
793 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700794
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100795 ArrayRef<DexFileMethodSet> dex_to_dex_references;
796 {
797 // From this point on, we shall not modify dex_to_dex_references_, so
798 // just grab a reference to it that we use without holding the mutex.
799 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
800 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
801 }
802 if (!dex_to_dex_references.empty()) {
803 DCHECK_EQ(dex_to_dex_references.size(), 1u);
804 DCHECK(&dex_to_dex_references[0].GetDexFile() == dex_file);
805 current_dex_to_dex_methods_ = &dex_to_dex_references.front().GetMethodIndexes();
806 DCHECK(current_dex_to_dex_methods_->IsBitSet(method_idx));
807 DCHECK_EQ(current_dex_to_dex_methods_->NumSetBits(), 1u);
808 CompileMethod(self,
809 this,
810 code_item,
811 access_flags,
812 invoke_type,
813 class_def_idx,
814 method_idx,
815 jclass_loader,
816 *dex_file,
817 dex_to_dex_compilation_level,
818 true,
819 dex_cache);
820 current_dex_to_dex_methods_ = nullptr;
821 }
822
Andreas Gampeace0dc12016-01-20 13:33:13 -0800823 FreeThreadPools();
824
Brian Carlstrom7940e442013-07-12 13:46:57 -0700825 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800826}
827
Andreas Gampeace0dc12016-01-20 13:33:13 -0800828void CompilerDriver::Resolve(jobject class_loader,
829 const std::vector<const DexFile*>& dex_files,
830 TimingLogger* timings) {
831 // Resolution allocates classes and needs to run single-threaded to be deterministic.
832 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
833 ThreadPool* resolve_thread_pool = force_determinism
834 ? single_thread_pool_.get()
835 : parallel_thread_pool_.get();
836 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
837
Brian Carlstrom7940e442013-07-12 13:46:57 -0700838 for (size_t i = 0; i != dex_files.size(); ++i) {
839 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700840 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800841 ResolveDexFile(class_loader,
842 *dex_file,
843 dex_files,
844 resolve_thread_pool,
845 resolve_thread_count,
846 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700847 }
848}
849
Andreas Gampeace0dc12016-01-20 13:33:13 -0800850// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
851// this is single-threaded for simplicity.
852// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
853// stable order.
854
855static void ResolveConstStrings(CompilerDriver* driver,
856 const DexFile& dex_file,
857 const DexFile::CodeItem* code_item) {
858 if (code_item == nullptr) {
859 // Abstract or native method.
860 return;
861 }
862
863 const uint16_t* code_ptr = code_item->insns_;
864 const uint16_t* code_end = code_item->insns_ + code_item->insns_size_in_code_units_;
865
866 while (code_ptr < code_end) {
867 const Instruction* inst = Instruction::At(code_ptr);
868 switch (inst->Opcode()) {
869 case Instruction::CONST_STRING: {
870 uint32_t string_index = inst->VRegB_21c();
871 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
872 break;
873 }
874 case Instruction::CONST_STRING_JUMBO: {
875 uint32_t string_index = inst->VRegB_31c();
876 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
877 break;
878 }
879
880 default:
881 break;
882 }
883
884 code_ptr += inst->SizeInCodeUnits();
885 }
886}
887
888static void ResolveConstStrings(CompilerDriver* driver,
889 const std::vector<const DexFile*>& dex_files,
890 TimingLogger* timings) {
891 for (const DexFile* dex_file : dex_files) {
892 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
893
894 size_t class_def_count = dex_file->NumClassDefs();
895 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
896 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
897
898 const uint8_t* class_data = dex_file->GetClassData(class_def);
899 if (class_data == nullptr) {
900 // empty class, probably a marker interface
901 continue;
902 }
903
904 ClassDataItemIterator it(*dex_file, class_data);
905 // Skip fields
906 while (it.HasNextStaticField()) {
907 it.Next();
908 }
909 while (it.HasNextInstanceField()) {
910 it.Next();
911 }
912
913 bool compilation_enabled = driver->IsClassToCompile(
914 dex_file->StringByTypeIdx(class_def.class_idx_));
915 if (!compilation_enabled) {
916 // Compilation is skipped, do not resolve const-string in code of this class.
917 // TODO: Make sure that inlining honors this.
918 continue;
919 }
920
921 // Direct methods.
922 int64_t previous_direct_method_idx = -1;
923 while (it.HasNextDirectMethod()) {
924 uint32_t method_idx = it.GetMemberIndex();
925 if (method_idx == previous_direct_method_idx) {
926 // smali can create dex files with two encoded_methods sharing the same method_idx
927 // http://code.google.com/p/smali/issues/detail?id=119
928 it.Next();
929 continue;
930 }
931 previous_direct_method_idx = method_idx;
932 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
933 it.Next();
934 }
935 // Virtual methods.
936 int64_t previous_virtual_method_idx = -1;
937 while (it.HasNextVirtualMethod()) {
938 uint32_t method_idx = it.GetMemberIndex();
939 if (method_idx == previous_virtual_method_idx) {
940 // smali can create dex files with two encoded_methods sharing the same method_idx
941 // http://code.google.com/p/smali/issues/detail?id=119
942 it.Next();
943 continue;
944 }
945 previous_virtual_method_idx = method_idx;
946 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
947 it.Next();
948 }
949 DCHECK(!it.HasNext());
950 }
951 }
952}
953
954inline void CompilerDriver::CheckThreadPools() {
955 DCHECK(parallel_thread_pool_ != nullptr);
956 DCHECK(single_thread_pool_ != nullptr);
957}
958
959void CompilerDriver::PreCompile(jobject class_loader,
960 const std::vector<const DexFile*>& dex_files,
961 TimingLogger* timings) {
962 CheckThreadPools();
963
Brian Carlstrom7940e442013-07-12 13:46:57 -0700964 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800965 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700966
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700967 const bool verification_enabled = compiler_options_->IsVerificationEnabled();
968 const bool never_verify = compiler_options_->NeverVerify();
Mathieu Chartiera8077802016-03-16 19:08:31 -0700969 const bool verify_only_profile = compiler_options_->VerifyOnlyProfile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700970
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700971 // We need to resolve for never_verify since it needs to run dex to dex to add the
972 // RETURN_VOID_NO_BARRIER.
Mathieu Chartiera8077802016-03-16 19:08:31 -0700973 // Let the verifier resolve as needed for the verify_only_profile case.
974 if ((never_verify || verification_enabled) && !verify_only_profile) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800975 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700976 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
977 }
978
979 if (never_verify) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800980 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800981 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700982 }
983
984 if (!verification_enabled) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700985 return;
986 }
987
Vladimir Marko5f926052016-09-30 17:04:49 +0000988 if (GetCompilerOptions().IsForceDeterminism() && IsBootImage()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800989 // Resolve strings from const-string. Do this now to have a deterministic image.
990 ResolveConstStrings(this, dex_files, timings);
991 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
992 }
993
994 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800995 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700996
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800997 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
998 LOG(FATAL) << "Had a hard failure verifying all classes, and was asked to abort in such "
999 << "situations. Please check the log.";
1000 }
1001
Andreas Gampeace0dc12016-01-20 13:33:13 -08001002 InitializeClasses(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -08001003 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001004
1005 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -08001006 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001007}
1008
Ian Rogersdfb325e2013-10-30 01:00:44 -07001009bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001010 if (image_classes_ != nullptr) {
1011 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -07001012 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001013 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001014 // No set of image classes, assume we include all the classes.
1015 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
Vladimir Marko5f926052016-09-30 17:04:49 +00001016 return !IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001017}
1018
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001019bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001020 if (classes_to_compile_ == nullptr) {
1021 return true;
1022 }
1023 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001024}
1025
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001026bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001027 if (methods_to_compile_ == nullptr) {
1028 return true;
1029 }
1030
1031 std::string tmp = PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
1032 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
1033}
1034
Calin Juravle226501b2015-12-11 14:41:31 +00001035bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
1036 if (profile_compilation_info_ == nullptr) {
1037 // If we miss profile information it means that we don't do a profile guided compilation.
1038 // Return true, and let the other filters decide if the method should be compiled.
1039 return true;
1040 }
1041 bool result = profile_compilation_info_->ContainsMethod(method_ref);
1042
1043 if (kDebugProfileGuidedCompilation) {
1044 LOG(INFO) << "[ProfileGuidedCompilation] "
1045 << (result ? "Compiled" : "Skipped") << " method:"
1046 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
1047 }
1048 return result;
1049}
1050
Mathieu Chartiera8077802016-03-16 19:08:31 -07001051bool CompilerDriver::ShouldVerifyClassBasedOnProfile(const DexFile& dex_file,
1052 uint16_t class_idx) const {
1053 if (!compiler_options_->VerifyOnlyProfile()) {
1054 // No profile, verify everything.
1055 return true;
1056 }
1057 DCHECK(profile_compilation_info_ != nullptr);
1058 bool result = profile_compilation_info_->ContainsClass(dex_file, class_idx);
1059 if (kDebugProfileGuidedCompilation) {
1060 LOG(INFO) << "[ProfileGuidedCompilation] "
1061 << (result ? "Verified" : "Skipped") << " method:"
1062 << dex_file.GetClassDescriptor(dex_file.GetClassDef(class_idx));
1063 }
1064 return result;
1065}
1066
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001067class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
1068 public:
Chih-Hung Hsieh471118e2016-04-29 14:27:41 -07001069 explicit ResolveCatchBlockExceptionsClassVisitor(
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001070 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve)
1071 : exceptions_to_resolve_(exceptions_to_resolve) {}
1072
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001073 virtual bool operator()(mirror::Class* c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001074 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Alex Lighte64300b2015-12-15 15:02:47 -08001075 for (auto& m : c->GetMethods(pointer_size)) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001076 ResolveExceptionsForMethod(&m, pointer_size);
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001077 }
1078 return true;
1079 }
1080
1081 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001082 void ResolveExceptionsForMethod(ArtMethod* method_handle, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001083 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001084 const DexFile::CodeItem* code_item = method_handle->GetCodeItem();
1085 if (code_item == nullptr) {
1086 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -07001087 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001088 if (code_item->tries_size_ == 0) {
1089 return; // nothing to process
1090 }
1091 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
1092 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
1093 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1094 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
1095 bool has_catch_all = false;
1096 if (encoded_catch_handler_size <= 0) {
1097 encoded_catch_handler_size = -encoded_catch_handler_size;
1098 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001099 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001100 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
1101 uint16_t encoded_catch_handler_handlers_type_idx =
1102 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1103 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko05792b92015-08-03 11:56:49 +01001104 if (!method_handle->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx,
1105 pointer_size)) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001106 exceptions_to_resolve_.emplace(encoded_catch_handler_handlers_type_idx,
1107 method_handle->GetDexFile());
1108 }
1109 // ignore address associated with catch handler
1110 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1111 }
1112 if (has_catch_all) {
1113 // ignore catch all address
1114 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1115 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001116 }
1117 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001118
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001119 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve_;
1120};
1121
1122class RecordImageClassesVisitor : public ClassVisitor {
1123 public:
1124 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
1125 : image_classes_(image_classes) {}
1126
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001127 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001128 std::string temp;
1129 image_classes_->insert(klass->GetDescriptor(&temp));
1130 return true;
1131 }
1132
1133 private:
1134 std::unordered_set<std::string>* const image_classes_;
1135};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001136
1137// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001138void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001139 CHECK(timings != nullptr);
Vladimir Marko5f926052016-09-30 17:04:49 +00001140 if (!IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001141 return;
1142 }
1143
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001144 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001145 // Make a first class to load all classes explicitly listed in the file
1146 Thread* self = Thread::Current();
1147 ScopedObjectAccess soa(self);
1148 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001149 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001150 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001151 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001152 StackHandleScope<1> hs(self);
1153 Handle<mirror::Class> klass(
1154 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001155 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001156 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001157 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001158 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001159 } else {
1160 ++it;
1161 }
1162 }
1163
1164 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1165 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1166 // Do this here so that exception classes appear to have been specified image classes.
Ian Rogers700a4022014-05-19 16:49:03 -07001167 std::set<std::pair<uint16_t, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001168 StackHandleScope<1> hs(self);
1169 Handle<mirror::Class> java_lang_Throwable(
1170 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001171 do {
1172 unresolved_exception_types.clear();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001173 ResolveCatchBlockExceptionsClassVisitor visitor(unresolved_exception_types);
1174 class_linker->VisitClasses(&visitor);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001175 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
1176 uint16_t exception_type_idx = exception_type.first;
1177 const DexFile* dex_file = exception_type.second;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001178 StackHandleScope<2> hs2(self);
Mathieu Chartierf284d442016-06-02 11:48:30 -07001179 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file,
1180 nullptr)));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001181 Handle<mirror::Class> klass(hs2.NewHandle(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001182 class_linker->ResolveType(*dex_file,
1183 exception_type_idx,
1184 dex_cache,
1185 ScopedNullHandle<mirror::ClassLoader>())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001186 if (klass.Get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001187 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1188 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1189 LOG(FATAL) << "Failed to resolve class " << descriptor;
1190 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001191 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001192 }
1193 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1194 // more are found
1195 } while (!unresolved_exception_types.empty());
1196
1197 // We walk the roots looking for classes so that we'll pick up the
1198 // above classes plus any classes them depend on such super
1199 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001200 RecordImageClassesVisitor visitor(image_classes_.get());
1201 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001202
1203 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001204}
1205
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001206static void MaybeAddToImageClasses(Handle<mirror::Class> c,
1207 std::unordered_set<std::string>* image_classes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001208 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001209 Thread* self = Thread::Current();
1210 StackHandleScope<1> hs(self);
1211 // Make a copy of the handle so that we don't clobber it doing Assign.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001212 MutableHandle<mirror::Class> klass(hs.NewHandle(c.Get()));
Ian Rogers1ff3c982014-08-12 02:30:58 -07001213 std::string temp;
Andreas Gampe542451c2016-07-26 09:02:02 -07001214 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001215 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001216 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001217 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1218 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001219 if (!result.second) { // Previously inserted.
1220 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001221 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001222 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Mathieu Chartierf8322842014-05-16 10:59:25 -07001223 for (size_t i = 0; i < klass->NumDirectInterfaces(); ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001224 StackHandleScope<1> hs2(self);
1225 MaybeAddToImageClasses(hs2.NewHandle(mirror::Class::GetDirectInterface(self, klass, i)),
Mathieu Chartierf8322842014-05-16 10:59:25 -07001226 image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001227 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001228 for (auto& m : c->GetVirtualMethods(pointer_size)) {
Alex Light36121492016-02-22 13:43:29 -08001229 StackHandleScope<1> hs2(self);
1230 MaybeAddToImageClasses(hs2.NewHandle(m.GetDeclaringClass()), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001231 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001232 if (klass->IsArrayClass()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001233 StackHandleScope<1> hs2(self);
1234 MaybeAddToImageClasses(hs2.NewHandle(klass->GetComponentType()), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001235 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001236 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001237 }
1238}
1239
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001240// Keeps all the data for the update together. Also doubles as the reference visitor.
1241// Note: we can use object pointers because we suspend all threads.
1242class ClinitImageUpdate {
1243 public:
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001244 static ClinitImageUpdate* Create(std::unordered_set<std::string>* image_class_descriptors,
1245 Thread* self, ClassLinker* linker, std::string* error_msg) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001246 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(image_class_descriptors, self,
1247 linker));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001248 if (res->dex_cache_class_ == nullptr) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001249 *error_msg = "Could not find DexCache class.";
1250 return nullptr;
1251 }
1252
1253 return res.release();
1254 }
1255
1256 ~ClinitImageUpdate() {
1257 // Allow others to suspend again.
1258 self_->EndAssertNoThreadSuspension(old_cause_);
1259 }
1260
1261 // Visitor for VisitReferences.
1262 void operator()(mirror::Object* object, MemberOffset field_offset, bool /* is_static */) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001263 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001264 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1265 if (ref != nullptr) {
1266 VisitClinitClassesObject(ref);
1267 }
1268 }
1269
1270 // java.lang.Reference visitor for VisitReferences.
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001271 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref ATTRIBUTE_UNUSED)
1272 const {}
1273
1274 // Ignore class native roots.
1275 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1276 const {}
1277 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001278
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001279 void Walk() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001280 // Use the initial classes as roots for a search.
1281 for (mirror::Class* klass_root : image_classes_) {
1282 VisitClinitClassesObject(klass_root);
1283 }
1284 }
1285
1286 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001287 class FindImageClassesVisitor : public ClassVisitor {
1288 public:
1289 explicit FindImageClassesVisitor(ClinitImageUpdate* data) : data_(data) {}
1290
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001291 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001292 std::string temp;
1293 const char* name = klass->GetDescriptor(&temp);
1294 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
1295 data_->image_classes_.push_back(klass);
1296 } else {
1297 // Check whether it is initialized and has a clinit. They must be kept, too.
1298 if (klass->IsInitialized() && klass->FindClassInitializer(
1299 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
1300 data_->image_classes_.push_back(klass);
1301 }
1302 }
1303 return true;
1304 }
1305
1306 private:
1307 ClinitImageUpdate* const data_;
1308 };
1309
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001310 ClinitImageUpdate(std::unordered_set<std::string>* image_class_descriptors, Thread* self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001311 ClassLinker* linker)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001312 REQUIRES_SHARED(Locks::mutator_lock_) :
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001313 image_class_descriptors_(image_class_descriptors), self_(self) {
1314 CHECK(linker != nullptr);
1315 CHECK(image_class_descriptors != nullptr);
1316
1317 // Make sure nobody interferes with us.
1318 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1319
1320 // Find the interesting classes.
Andreas Gampedc8b63c2014-12-02 14:39:52 -08001321 dex_cache_class_ = linker->LookupClass(self, "Ljava/lang/DexCache;",
1322 ComputeModifiedUtf8Hash("Ljava/lang/DexCache;"), nullptr);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001323
1324 // Find all the already-marked classes.
1325 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001326 FindImageClassesVisitor visitor(this);
1327 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001328 }
1329
1330 void VisitClinitClassesObject(mirror::Object* object) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001331 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001332 DCHECK(object != nullptr);
1333 if (marked_objects_.find(object) != marked_objects_.end()) {
1334 // Already processed.
1335 return;
1336 }
1337
1338 // Mark it.
1339 marked_objects_.insert(object);
1340
1341 if (object->IsClass()) {
1342 // If it is a class, add it.
1343 StackHandleScope<1> hs(self_);
1344 MaybeAddToImageClasses(hs.NewHandle(object->AsClass()), image_class_descriptors_);
1345 } else {
1346 // Else visit the object's class.
1347 VisitClinitClassesObject(object->GetClass());
1348 }
1349
Mathieu Chartiere401d142015-04-22 13:56:20 -07001350 // If it is not a DexCache, visit all references.
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001351 mirror::Class* klass = object->GetClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001352 if (klass != dex_cache_class_) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001353 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001354 }
1355 }
1356
1357 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001358 std::unordered_set<std::string>* const image_class_descriptors_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001359 std::vector<mirror::Class*> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001360 const mirror::Class* dex_cache_class_;
1361 Thread* const self_;
1362 const char* old_cause_;
1363
1364 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1365};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001366
Ian Rogers3d504072014-03-01 09:16:49 -08001367void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Vladimir Marko5f926052016-09-30 17:04:49 +00001368 if (IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001369 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001370
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001371 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001372
1373 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001374 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001375
1376 std::string error_msg;
1377 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(image_classes_.get(),
1378 Thread::Current(),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001379 runtime->GetClassLinker(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001380 &error_msg));
1381 CHECK(update.get() != nullptr) << error_msg; // TODO: Soft failure?
1382
1383 // Do the marking.
1384 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001385 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001386}
1387
Vladimir Marko07785bb2015-06-15 18:52:54 +01001388bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1389 Runtime* runtime = Runtime::Current();
1390 if (!runtime->IsAotCompiler()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001391 DCHECK(runtime->UseJitCompilation());
Vladimir Marko07785bb2015-06-15 18:52:54 +01001392 // Having the klass reference here implies that the klass is already loaded.
1393 return true;
1394 }
Vladimir Marko5f926052016-09-30 17:04:49 +00001395 if (!IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001396 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1397 // loaded because we don't even know what class loader will be used to load them.
1398 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1399 return class_in_image;
1400 }
1401 std::string temp;
1402 const char* descriptor = klass->GetDescriptor(&temp);
1403 return IsImageClass(descriptor);
1404}
1405
Vladimir Marko492a7fa2016-06-01 18:38:43 +01001406void CompilerDriver::MarkForDexToDexCompilation(Thread* self, const MethodReference& method_ref) {
1407 MutexLock lock(self, dex_to_dex_references_lock_);
1408 // Since we're compiling one dex file at a time, we need to look for the
1409 // current dex file entry only at the end of dex_to_dex_references_.
1410 if (dex_to_dex_references_.empty() ||
1411 &dex_to_dex_references_.back().GetDexFile() != method_ref.dex_file) {
1412 dex_to_dex_references_.emplace_back(*method_ref.dex_file);
1413 }
1414 dex_to_dex_references_.back().GetMethodIndexes().SetBit(method_ref.dex_method_index);
1415}
1416
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001417bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(Handle<mirror::DexCache> dex_cache,
1418 uint32_t type_idx) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001419 bool result = false;
Vladimir Marko5f926052016-09-30 17:04:49 +00001420 if ((IsBootImage() &&
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001421 IsImageClass(dex_cache->GetDexFile()->StringDataByIdx(
1422 dex_cache->GetDexFile()->GetTypeId(type_idx).descriptor_idx_))) ||
Calin Juravleffc87072016-04-20 14:22:09 +01001423 Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001424 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1425 result = (resolved_class != nullptr);
1426 }
1427
1428 if (result) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001429 stats_->TypeInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001430 } else {
1431 stats_->TypeNotInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001432 }
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001433 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001434}
1435
1436bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
1437 uint32_t string_idx) {
1438 // See also Compiler::ResolveDexFile
1439
1440 bool result = false;
Vladimir Marko5f926052016-09-30 17:04:49 +00001441 if (IsBootImage() || Runtime::Current()->UseJitCompilation()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001442 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001443 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001444 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1445 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1446 soa.Self(), dex_file, false)));
Vladimir Marko5f926052016-09-30 17:04:49 +00001447 if (IsBootImage()) {
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001448 // We resolve all const-string strings when building for the image.
1449 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1450 result = true;
1451 } else {
1452 // Just check whether the dex cache already has the string.
Calin Juravleffc87072016-04-20 14:22:09 +01001453 DCHECK(Runtime::Current()->UseJitCompilation());
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001454 result = (dex_cache->GetResolvedString(string_idx) != nullptr);
1455 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001456 }
1457 if (result) {
1458 stats_->StringInDexCache();
1459 } else {
1460 stats_->StringNotInDexCache();
1461 }
1462 return result;
1463}
1464
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001465bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx,
1466 Handle<mirror::DexCache> dex_cache,
1467 uint32_t type_idx) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001468 // Get type from dex cache assuming it was populated by the verifier
1469 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001470 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001471 stats_->TypeNeedsAccessCheck();
1472 return false; // Unknown class needs access checks.
1473 }
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001474 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001475 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1476 if (!is_accessible) {
1477 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1478 if (referrer_class == nullptr) {
1479 stats_->TypeNeedsAccessCheck();
1480 return false; // Incomplete referrer knowledge needs access check.
1481 }
1482 // Perform access check, will return true if access is ok or false if we're going to have to
1483 // check this at runtime (for example for class loaders).
1484 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001485 }
David Brazdil38f64d32016-01-18 17:13:41 +00001486 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001487 stats_->TypeDoesntNeedAccessCheck();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001488 } else {
1489 stats_->TypeNeedsAccessCheck();
1490 }
David Brazdil38f64d32016-01-18 17:13:41 +00001491 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001492}
1493
1494bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001495 Handle<mirror::DexCache> dex_cache,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001496 uint32_t type_idx,
1497 bool* finalizable) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001498 // Get type from dex cache assuming it was populated by the verifier.
1499 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001500 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001501 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001502 // Be conservative.
1503 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001504 return false; // Unknown class needs access checks.
1505 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001506 *finalizable = resolved_class->IsFinalizable();
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001507 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001508 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1509 if (!is_accessible) {
1510 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1511 if (referrer_class == nullptr) {
1512 stats_->TypeNeedsAccessCheck();
1513 return false; // Incomplete referrer knowledge needs access check.
1514 }
1515 // Perform access and instantiable checks, will return true if access is ok or false if we're
1516 // going to have to check this at runtime (for example for class loaders).
1517 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001518 }
David Brazdil38f64d32016-01-18 17:13:41 +00001519 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001520 if (result) {
1521 stats_->TypeDoesntNeedAccessCheck();
1522 } else {
1523 stats_->TypeNeedsAccessCheck();
1524 }
1525 return result;
1526}
1527
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001528bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
1529 bool* is_type_initialized, bool* use_direct_type_ptr,
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001530 uintptr_t* direct_type_ptr, bool* out_is_finalizable) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001531 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001532 Runtime* runtime = Runtime::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001533 mirror::DexCache* dex_cache = runtime->GetClassLinker()->FindDexCache(
1534 soa.Self(), dex_file, false);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001535 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1536 if (resolved_class == nullptr) {
1537 return false;
1538 }
Igor Murashkind6dee672014-10-16 18:36:16 -07001539 if (GetCompilerOptions().GetCompilePic()) {
1540 // Do not allow a direct class pointer to be used when compiling for position-independent
1541 return false;
1542 }
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001543 *out_is_finalizable = resolved_class->IsFinalizable();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001544 gc::Heap* heap = runtime->GetHeap();
1545 const bool compiling_boot = heap->IsCompilingBoot();
Alex Light6e183f22014-07-18 14:57:04 -07001546 const bool support_boot_image_fixup = GetSupportBootImageFixup();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001547 if (compiling_boot) {
1548 // boot -> boot class pointers.
1549 // True if the class is in the image at boot compiling time.
Vladimir Marko5f926052016-09-30 17:04:49 +00001550 const bool is_image_class = IsBootImage() && IsImageClass(
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001551 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
1552 // True if pc relative load works.
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001553 if (is_image_class && support_boot_image_fixup) {
1554 *is_type_initialized = resolved_class->IsInitialized();
1555 *use_direct_type_ptr = false;
1556 *direct_type_ptr = 0;
1557 return true;
1558 } else {
1559 return false;
1560 }
Calin Juravleffc87072016-04-20 14:22:09 +01001561 } else if (runtime->UseJitCompilation() && !heap->IsMovableObject(resolved_class)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001562 *is_type_initialized = resolved_class->IsInitialized();
1563 // If the class may move around, then don't embed it as a direct pointer.
1564 *use_direct_type_ptr = true;
1565 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1566 return true;
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001567 } else {
1568 // True if the class is in the image at app compiling time.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001569 const bool class_in_image = heap->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
Alex Light6e183f22014-07-18 14:57:04 -07001570 if (class_in_image && support_boot_image_fixup) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001571 // boot -> app class pointers.
1572 *is_type_initialized = resolved_class->IsInitialized();
Alex Lighta59dd802014-07-02 16:28:08 -07001573 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1574 *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001575 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1576 return true;
1577 } else {
1578 // app -> app class pointers.
1579 // Give up because app does not have an image and class
1580 // isn't created at compile time. TODO: implement this
1581 // if/when each app gets an image.
1582 return false;
1583 }
1584 }
1585}
1586
Fred Shihe7f82e22014-08-06 10:46:37 -07001587bool CompilerDriver::CanEmbedReferenceTypeInCode(ClassReference* ref,
1588 bool* use_direct_ptr,
1589 uintptr_t* direct_type_ptr) {
1590 CHECK(ref != nullptr);
1591 CHECK(use_direct_ptr != nullptr);
1592 CHECK(direct_type_ptr != nullptr);
1593
1594 ScopedObjectAccess soa(Thread::Current());
1595 mirror::Class* reference_class = mirror::Reference::GetJavaLangRefReference();
Andreas Gampe928f72b2014-09-09 19:53:48 -07001596 bool is_initialized = false;
Fred Shihe7f82e22014-08-06 10:46:37 -07001597 bool unused_finalizable;
1598 // Make sure we have a finished Reference class object before attempting to use it.
1599 if (!CanEmbedTypeInCode(*reference_class->GetDexCache()->GetDexFile(),
1600 reference_class->GetDexTypeIndex(), &is_initialized,
1601 use_direct_ptr, direct_type_ptr, &unused_finalizable) ||
1602 !is_initialized) {
1603 return false;
1604 }
1605 ref->first = &reference_class->GetDexFile();
1606 ref->second = reference_class->GetDexClassDefIndex();
1607 return true;
1608}
1609
1610uint32_t CompilerDriver::GetReferenceSlowFlagOffset() const {
1611 ScopedObjectAccess soa(Thread::Current());
1612 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1613 DCHECK(klass->IsInitialized());
1614 return klass->GetSlowPathFlagOffset().Uint32Value();
1615}
1616
1617uint32_t CompilerDriver::GetReferenceDisableFlagOffset() const {
1618 ScopedObjectAccess soa(Thread::Current());
1619 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1620 DCHECK(klass->IsInitialized());
1621 return klass->GetDisableIntrinsicFlagOffset().Uint32Value();
1622}
1623
Vladimir Marko20f85592015-03-19 10:07:02 +00001624DexCacheArraysLayout CompilerDriver::GetDexCacheArraysLayout(const DexFile* dex_file) {
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001625 return ContainsElement(GetDexFilesForOatFile(), dex_file)
Mathieu Chartierc7853442015-03-27 14:35:38 -07001626 ? DexCacheArraysLayout(GetInstructionSetPointerSize(instruction_set_), dex_file)
Vladimir Marko20f85592015-03-19 10:07:02 +00001627 : DexCacheArraysLayout();
1628}
1629
Vladimir Markobe0e5462014-02-26 11:24:15 +00001630void CompilerDriver::ProcessedInstanceField(bool resolved) {
1631 if (!resolved) {
1632 stats_->UnresolvedInstanceField();
1633 } else {
1634 stats_->ResolvedInstanceField();
1635 }
1636}
1637
1638void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1639 if (!resolved) {
1640 stats_->UnresolvedStaticField();
1641 } else if (local) {
1642 stats_->ResolvedLocalStaticField();
1643 } else {
1644 stats_->ResolvedStaticField();
1645 }
1646}
1647
Vladimir Markof096aad2014-01-23 15:51:58 +00001648void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
1649 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001650}
1651
Mathieu Chartierc7853442015-03-27 14:35:38 -07001652ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1653 const DexCompilationUnit* mUnit, bool is_put,
1654 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001655 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001656 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001657 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001658 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001659 {
Mathieu Chartier736b5602015-09-02 14:54:11 -07001660 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001661 Handle<mirror::ClassLoader> class_loader_handle(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001662 hs.NewHandle(soa.Decode<mirror::ClassLoader>(mUnit->GetClassLoader())));
Mathieu Chartier736b5602015-09-02 14:54:11 -07001663 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001664 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001665 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001666 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001667 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001668 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001669 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001670 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001671 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001672 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001673 ProcessedInstanceField(can_link);
1674 return can_link ? resolved_field : nullptr;
1675}
1676
1677bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1678 bool is_put, MemberOffset* field_offset,
1679 bool* is_volatile) {
1680 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001681 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001682
Mathieu Chartierc7853442015-03-27 14:35:38 -07001683 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001684 // Conservative defaults.
1685 *is_volatile = true;
1686 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001687 return false;
1688 } else {
1689 *is_volatile = resolved_field->IsVolatile();
1690 *field_offset = resolved_field->GetOffset();
1691 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001692 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001693}
1694
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001695void CompilerDriver::GetCodeAndMethodForDirectCall(const mirror::Class* referrer_class,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001696 ArtMethod* method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001697 uintptr_t* direct_code,
1698 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001699 // For direct and static methods compute possible direct_code and direct_method values, ie
1700 // an address for the Method* being invoked and an address of the code for that Method*.
1701 // For interface calls compute a value for direct_method that is the interface method being
1702 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001703 *direct_code = 0;
1704 *direct_method = 0;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001705 Runtime* const runtime = Runtime::Current();
1706 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001707 auto* cl = runtime->GetClassLinker();
Igor Murashkind6dee672014-10-16 18:36:16 -07001708 bool use_dex_cache = GetCompilerOptions().GetCompilePic(); // Off by default
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001709 const bool compiling_boot = heap->IsCompilingBoot();
Alex Lighta59dd802014-07-02 16:28:08 -07001710 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1711 const bool force_relocations = (compiling_boot ||
1712 GetCompilerOptions().GetIncludePatchInformation());
Elliott Hughes956af0f2014-12-11 14:34:28 -08001713 // TODO: support patching on all architectures.
1714 use_dex_cache = use_dex_cache || (force_relocations && !support_boot_image_fixup_);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001715 mirror::Class* declaring_class = method->GetDeclaringClass();
1716 bool method_code_in_boot = declaring_class->GetClassLoader() == nullptr;
Ian Rogers83883d72013-10-21 21:07:24 -07001717 if (!use_dex_cache) {
1718 if (!method_code_in_boot) {
1719 use_dex_cache = true;
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001720 } else if (method->IsStatic() &&
1721 declaring_class != referrer_class &&
1722 !declaring_class->IsInitialized()) {
1723 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1724 // class.
1725 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001726 }
Ian Rogers83883d72013-10-21 21:07:24 -07001727 }
Calin Juravleffc87072016-04-20 14:22:09 +01001728 if (runtime->UseJitCompilation()) {
Mathieu Chartier28a35882015-02-26 18:28:07 -08001729 // If we are the JIT, then don't allow a direct call to the interpreter bridge since this will
1730 // never be updated even after we compile the method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001731 if (cl->IsQuickToInterpreterBridge(
Mathieu Chartier28a35882015-02-26 18:28:07 -08001732 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)))) {
1733 use_dex_cache = true;
1734 }
1735 }
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001736
Alex Lighta59dd802014-07-02 16:28:08 -07001737 if (!use_dex_cache && force_relocations) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001738 bool is_in_image;
Vladimir Marko5f926052016-09-30 17:04:49 +00001739 if (IsBootImage()) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001740 is_in_image = IsImageClass(method->GetDeclaringClassDescriptor());
1741 } else {
1742 is_in_image = instruction_set_ != kX86 && instruction_set_ != kX86_64 &&
Vladimir Markoc08ab292015-06-22 14:35:42 +01001743 heap->FindSpaceFromObject(method->GetDeclaringClass(), false)->IsImageSpace() &&
1744 !cl->IsQuickToInterpreterBridge(
1745 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)));
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001746 }
1747 if (!is_in_image) {
Ian Rogers83883d72013-10-21 21:07:24 -07001748 // We can only branch directly to Methods that are resolved in the DexCache.
1749 // Otherwise we won't invoke the resolution trampoline.
1750 use_dex_cache = true;
1751 }
1752 }
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001753
1754 if (!use_dex_cache) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001755 bool method_in_image = false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001756 const std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
1757 for (gc::space::ImageSpace* image_space : image_spaces) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001758 const auto& method_section = image_space->GetImageHeader().GetMethodsSection();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001759 if (method_section.Contains(reinterpret_cast<uint8_t*>(method) - image_space->Begin())) {
1760 method_in_image = true;
1761 break;
1762 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001763 }
Calin Juravleffc87072016-04-20 14:22:09 +01001764 if (method_in_image || compiling_boot || runtime->UseJitCompilation()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001765 // 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 -08001766 // In the case where we are the JIT, we can always use direct pointers since we know where
1767 // the method and its code are / will be. We don't sharpen to interpreter bridge since we
1768 // check IsQuickToInterpreterBridge above.
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001769 CHECK(!method->IsAbstract());
Alex Lighta59dd802014-07-02 16:28:08 -07001770 *direct_method = force_relocations ? -1 : reinterpret_cast<uintptr_t>(method);
1771 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001772 } else {
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001773 // Set the code and rely on the dex cache for the method.
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001774 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001775 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001776 }
1777}
1778
Vladimir Marko2730db02014-01-27 11:15:17 +00001779const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1780 uint32_t method_idx) const {
1781 MethodReference ref(dex_file, method_idx);
1782 return verification_results_->GetVerifiedMethod(ref);
1783}
1784
1785bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001786 if (!compiler_options_->IsVerificationEnabled()) {
1787 // If we didn't verify, every cast has to be treated as non-safe.
1788 return false;
1789 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001790 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1791 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001792 if (result) {
1793 stats_->SafeCast();
1794 } else {
1795 stats_->NotASafeCast();
1796 }
1797 return result;
1798}
1799
Mathieu Chartier90443472015-07-16 20:32:27 -07001800class CompilationVisitor {
1801 public:
1802 virtual ~CompilationVisitor() {}
1803 virtual void Visit(size_t index) = 0;
1804};
1805
Brian Carlstrom7940e442013-07-12 13:46:57 -07001806class ParallelCompilationManager {
1807 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001808 ParallelCompilationManager(ClassLinker* class_linker,
1809 jobject class_loader,
1810 CompilerDriver* compiler,
1811 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001812 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001813 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001814 : index_(0),
1815 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001816 class_loader_(class_loader),
1817 compiler_(compiler),
1818 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001819 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001820 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001821
1822 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001823 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001824 return class_linker_;
1825 }
1826
1827 jobject GetClassLoader() const {
1828 return class_loader_;
1829 }
1830
1831 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001832 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001833 return compiler_;
1834 }
1835
1836 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001837 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001838 return dex_file_;
1839 }
1840
Andreas Gampede7b4362014-07-28 18:38:57 -07001841 const std::vector<const DexFile*>& GetDexFiles() const {
1842 return dex_files_;
1843 }
1844
Mathieu Chartier90443472015-07-16 20:32:27 -07001845 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1846 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001847 Thread* self = Thread::Current();
1848 self->AssertNoPendingException();
1849 CHECK_GT(work_units, 0U);
1850
Ian Rogers3e5cf302014-05-20 16:40:37 -07001851 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001852 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001853 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001854 }
1855 thread_pool_->StartWorkers(self);
1856
1857 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1858 // thread destructor's called below perform join).
1859 CHECK_NE(self->GetState(), kRunnable);
1860
1861 // Wait for all the worker threads to finish.
1862 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001863
1864 // And stop the workers accepting jobs.
1865 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001866 }
1867
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001868 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001869 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001870 }
1871
Brian Carlstrom7940e442013-07-12 13:46:57 -07001872 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001873 class ForAllClosure : public Task {
1874 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001875 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001876 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001877 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001878 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001879
1880 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001881 while (true) {
1882 const size_t index = manager_->NextIndex();
1883 if (UNLIKELY(index >= end_)) {
1884 break;
1885 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001886 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001887 self->AssertNoPendingException();
1888 }
1889 }
1890
1891 virtual void Finalize() {
1892 delete this;
1893 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001894
Brian Carlstrom7940e442013-07-12 13:46:57 -07001895 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001896 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001897 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001898 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001899 };
1900
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001901 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001902 ClassLinker* const class_linker_;
1903 const jobject class_loader_;
1904 CompilerDriver* const compiler_;
1905 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001906 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001907 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001908
1909 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001910};
1911
Jeff Hao0e49b422013-11-08 12:16:56 -08001912// A fast version of SkipClass above if the class pointer is available
1913// that avoids the expensive FindInClassPath search.
1914static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001915 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001916 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001917 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1918 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001919 if (class_loader == nullptr) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001920 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1921 << dex_file.GetLocation() << " previously found in "
1922 << original_dex_file.GetLocation();
1923 }
1924 return true;
1925 }
1926 return false;
1927}
1928
Mathieu Chartier70b63482014-06-27 17:19:04 -07001929static void CheckAndClearResolveException(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001930 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07001931 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001932 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001933 std::string temp;
1934 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1935 const char* expected_exceptions[] = {
1936 "Ljava/lang/IllegalAccessError;",
1937 "Ljava/lang/IncompatibleClassChangeError;",
1938 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001939 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07001940 "Ljava/lang/NoClassDefFoundError;",
1941 "Ljava/lang/NoSuchFieldError;",
1942 "Ljava/lang/NoSuchMethodError;"
1943 };
1944 bool found = false;
1945 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1946 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1947 found = true;
1948 }
1949 }
1950 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001951 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07001952 }
1953 self->ClearException();
1954}
1955
Mathieu Chartierb5d38612016-04-07 10:52:52 -07001956bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file,
1957 uint16_t class_def_idx) const {
1958 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
1959 const uint8_t* class_data = dex_file.GetClassData(class_def);
1960 if (class_data == nullptr) {
1961 // Empty class such as a marker interface.
1962 return false;
1963 }
1964 ClassDataItemIterator it(dex_file, class_data);
1965 while (it.HasNextStaticField()) {
1966 it.Next();
1967 }
1968 // We require a constructor barrier if there are final instance fields.
1969 while (it.HasNextInstanceField()) {
1970 if (it.MemberIsFinal()) {
1971 return true;
1972 }
1973 it.Next();
1974 }
1975 return false;
1976}
1977
Mathieu Chartier90443472015-07-16 20:32:27 -07001978class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
1979 public:
1980 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
1981 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001982
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001983 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001984 ATRACE_CALL();
1985 Thread* const self = Thread::Current();
1986 jobject jclass_loader = manager_->GetClassLoader();
1987 const DexFile& dex_file = *manager_->GetDexFile();
1988 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001989
Mathieu Chartier90443472015-07-16 20:32:27 -07001990 // If an instance field is final then we need to have a barrier on the return, static final
1991 // fields are assigned within the lock held for class initialization. Conservatively assume
1992 // constructor barriers are always required.
1993 bool requires_constructor_barrier = true;
1994
1995 // Method and Field are the worst. We can't resolve without either
1996 // context from the code use (to disambiguate virtual vs direct
1997 // method and instance vs static field) or from class
1998 // definitions. While the compiler will resolve what it can as it
1999 // needs it, here we try to resolve fields and methods used in class
2000 // definitions, since many of them many never be referenced by
2001 // generated code.
2002 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2003 ScopedObjectAccess soa(self);
2004 StackHandleScope<2> hs(soa.Self());
2005 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002006 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002007 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2008 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002009 // Resolve the class.
2010 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
2011 class_loader);
2012 bool resolve_fields_and_methods;
2013 if (klass == nullptr) {
2014 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
2015 // attempt to resolve methods and fields when there is no declaring class.
2016 CheckAndClearResolveException(soa.Self());
2017 resolve_fields_and_methods = false;
2018 } else {
2019 // We successfully resolved a class, should we skip it?
2020 if (SkipClass(jclass_loader, dex_file, klass)) {
2021 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002022 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002023 // We want to resolve the methods and fields eagerly.
2024 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07002025 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002026 // Note the class_data pointer advances through the headers,
2027 // static fields, instance fields, direct methods, and virtual
2028 // methods.
2029 const uint8_t* class_data = dex_file.GetClassData(class_def);
2030 if (class_data == nullptr) {
2031 // Empty class such as a marker interface.
2032 requires_constructor_barrier = false;
2033 } else {
2034 ClassDataItemIterator it(dex_file, class_data);
2035 while (it.HasNextStaticField()) {
2036 if (resolve_fields_and_methods) {
2037 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2038 dex_cache, class_loader, true);
2039 if (field == nullptr) {
2040 CheckAndClearResolveException(soa.Self());
2041 }
Ian Rogers68b56852014-08-29 20:19:11 -07002042 }
2043 it.Next();
2044 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002045 // We require a constructor barrier if there are final instance fields.
2046 requires_constructor_barrier = false;
2047 while (it.HasNextInstanceField()) {
2048 if (it.MemberIsFinal()) {
2049 requires_constructor_barrier = true;
2050 }
2051 if (resolve_fields_and_methods) {
2052 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2053 dex_cache, class_loader, false);
2054 if (field == nullptr) {
2055 CheckAndClearResolveException(soa.Self());
2056 }
Ian Rogers68b56852014-08-29 20:19:11 -07002057 }
2058 it.Next();
2059 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002060 if (resolve_fields_and_methods) {
2061 while (it.HasNextDirectMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002062 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002063 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2064 it.GetMethodInvokeType(class_def));
2065 if (method == nullptr) {
2066 CheckAndClearResolveException(soa.Self());
2067 }
2068 it.Next();
2069 }
2070 while (it.HasNextVirtualMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002071 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002072 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2073 it.GetMethodInvokeType(class_def));
2074 if (method == nullptr) {
2075 CheckAndClearResolveException(soa.Self());
2076 }
2077 it.Next();
2078 }
2079 DCHECK(!it.HasNext());
2080 }
2081 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002082 manager_->GetCompiler()->SetRequiresConstructorBarrier(self,
2083 &dex_file,
2084 class_def_index,
2085 requires_constructor_barrier);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002086 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002087
Mathieu Chartier90443472015-07-16 20:32:27 -07002088 private:
2089 const ParallelCompilationManager* const manager_;
2090};
2091
2092class ResolveTypeVisitor : public CompilationVisitor {
2093 public:
2094 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
2095 }
2096 virtual void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002097 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07002098 ScopedObjectAccess soa(Thread::Current());
2099 ClassLinker* class_linker = manager_->GetClassLinker();
2100 const DexFile& dex_file = *manager_->GetDexFile();
2101 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07002102 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002103 hs.NewHandle(soa.Decode<mirror::ClassLoader>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002104 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
2105 dex_file,
Mathieu Chartierf284d442016-06-02 11:48:30 -07002106 class_loader.Get())));
Mathieu Chartier90443472015-07-16 20:32:27 -07002107 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002108
Mathieu Chartier90443472015-07-16 20:32:27 -07002109 if (klass == nullptr) {
2110 soa.Self()->AssertPendingException();
2111 mirror::Throwable* exception = soa.Self()->GetException();
2112 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
2113 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
2114 // There's little point continuing compilation if the heap is exhausted.
2115 LOG(FATAL) << "Out of memory during type resolution for compilation";
2116 }
2117 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07002118 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002119 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002120
2121 private:
2122 const ParallelCompilationManager* const manager_;
2123};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002124
Andreas Gampeace0dc12016-01-20 13:33:13 -08002125void CompilerDriver::ResolveDexFile(jobject class_loader,
2126 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002127 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002128 ThreadPool* thread_pool,
2129 size_t thread_count,
2130 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002131 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2132
2133 // TODO: we could resolve strings here, although the string table is largely filled with class
2134 // and method names.
2135
Andreas Gampede7b4362014-07-28 18:38:57 -07002136 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2137 thread_pool);
Vladimir Marko5f926052016-09-30 17:04:49 +00002138 if (IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002139 // For images we resolve all types, such as array, whereas for applications just those with
2140 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002141 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002142 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002143 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002144 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002145
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002146 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002147 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002148 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002149}
2150
Andreas Gampeace0dc12016-01-20 13:33:13 -08002151void CompilerDriver::SetVerified(jobject class_loader,
2152 const std::vector<const DexFile*>& dex_files,
2153 TimingLogger* timings) {
2154 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07002155 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002156 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002157 SetVerifiedDexFile(class_loader,
2158 *dex_file,
2159 dex_files,
2160 parallel_thread_pool_.get(),
2161 parallel_thread_count_,
2162 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002163 }
2164}
2165
Andreas Gampeace0dc12016-01-20 13:33:13 -08002166void CompilerDriver::Verify(jobject class_loader,
2167 const std::vector<const DexFile*>& dex_files,
2168 TimingLogger* timings) {
2169 // Note: verification should not be pulling in classes anymore when compiling the boot image,
2170 // as all should have been resolved before. As such, doing this in parallel should still
2171 // be deterministic.
Mathieu Chartier90443472015-07-16 20:32:27 -07002172 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002173 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002174 VerifyDexFile(class_loader,
2175 *dex_file,
2176 dex_files,
2177 parallel_thread_pool_.get(),
2178 parallel_thread_count_,
2179 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002180 }
2181}
2182
Mathieu Chartier90443472015-07-16 20:32:27 -07002183class VerifyClassVisitor : public CompilationVisitor {
2184 public:
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002185 VerifyClassVisitor(const ParallelCompilationManager* manager, verifier::HardFailLogMode log_level)
Andreas Gampe7fe30232016-03-25 16:58:00 -07002186 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002187
Mathieu Chartier90443472015-07-16 20:32:27 -07002188 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2189 ATRACE_CALL();
2190 ScopedObjectAccess soa(Thread::Current());
2191 const DexFile& dex_file = *manager_->GetDexFile();
Mathieu Chartiera8077802016-03-16 19:08:31 -07002192 if (!manager_->GetCompiler()->ShouldVerifyClassBasedOnProfile(dex_file, class_def_index)) {
2193 // Skip verification since the class is not in the profile.
2194 return;
2195 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002196 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2197 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2198 ClassLinker* class_linker = manager_->GetClassLinker();
2199 jobject jclass_loader = manager_->GetClassLoader();
2200 StackHandleScope<3> hs(soa.Self());
2201 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002202 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002203 Handle<mirror::Class> klass(
2204 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2205 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002206 CHECK(soa.Self()->IsExceptionPending());
2207 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07002208
2209 /*
2210 * At compile time, we can still structurally verify the class even if FindClass fails.
2211 * This is to ensure the class is structurally sound for compilation. An unsound class
2212 * will be rejected by the verifier and later skipped during compilation in the compiler.
2213 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002214 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2215 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002216 std::string error_msg;
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002217 if (verifier::MethodVerifier::VerifyClass(soa.Self(),
2218 &dex_file,
2219 dex_cache,
2220 class_loader,
David Brazdil15fc7292016-09-02 14:13:18 +01002221 class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08002222 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002223 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07002224 log_level_,
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002225 &error_msg) ==
Mathieu Chartier90443472015-07-16 20:32:27 -07002226 verifier::MethodVerifier::kHardFailure) {
2227 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2228 << " because: " << error_msg;
2229 manager_->GetCompiler()->SetHadHardVerifierFailure();
2230 }
2231 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
2232 CHECK(klass->IsResolved()) << PrettyClass(klass.Get());
Andreas Gampe7fe30232016-03-25 16:58:00 -07002233 class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002234
2235 if (klass->IsErroneous()) {
2236 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2237 CHECK(soa.Self()->IsExceptionPending());
2238 soa.Self()->ClearException();
2239 manager_->GetCompiler()->SetHadHardVerifierFailure();
2240 }
2241
2242 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
2243 << PrettyDescriptor(klass.Get()) << ": state=" << klass->GetStatus();
2244
2245 // It is *very* problematic if there are verification errors in the boot classpath. For example,
2246 // we rely on things working OK without verification when the decryption dialog is brought up.
2247 // So abort in a debug build if we find this violated.
Vladimir Marko5f926052016-09-30 17:04:49 +00002248 DCHECK(!manager_->GetCompiler()->IsBootImage() || klass->IsVerified())
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002249 << "Boot classpath class " << PrettyClass(klass.Get()) << " failed to fully verify.";
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002250 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002251 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002252 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002253
2254 private:
2255 const ParallelCompilationManager* const manager_;
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002256 const verifier::HardFailLogMode log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002257};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002258
Andreas Gampeace0dc12016-01-20 13:33:13 -08002259void CompilerDriver::VerifyDexFile(jobject class_loader,
2260 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002261 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002262 ThreadPool* thread_pool,
2263 size_t thread_count,
2264 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002265 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002266 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002267 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2268 thread_pool);
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002269 verifier::HardFailLogMode log_level = GetCompilerOptions().AbortOnHardVerifierFailure()
2270 ? verifier::HardFailLogMode::kLogInternalFatal
2271 : verifier::HardFailLogMode::kLogWarning;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002272 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002273 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002274}
2275
Mathieu Chartier90443472015-07-16 20:32:27 -07002276class SetVerifiedClassVisitor : public CompilationVisitor {
2277 public:
2278 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2279
2280 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2281 ATRACE_CALL();
2282 ScopedObjectAccess soa(Thread::Current());
2283 const DexFile& dex_file = *manager_->GetDexFile();
2284 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2285 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2286 ClassLinker* class_linker = manager_->GetClassLinker();
2287 jobject jclass_loader = manager_->GetClassLoader();
2288 StackHandleScope<3> hs(soa.Self());
2289 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002290 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002291 Handle<mirror::Class> klass(
2292 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2293 // Class might have failed resolution. Then don't set it to verified.
2294 if (klass.Get() != nullptr) {
2295 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2296 // very wrong.
2297 if (klass->IsResolved()) {
2298 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
2299 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2300 // Set class status to verified.
2301 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self());
2302 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2303 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002304 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002305 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002306 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002307 }
2308 // Record the final class status if necessary.
2309 ClassReference ref(manager_->GetDexFile(), class_def_index);
2310 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002311 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002312 } else {
2313 Thread* self = soa.Self();
2314 DCHECK(self->IsExceptionPending());
2315 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002316 }
2317 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002318
2319 private:
2320 const ParallelCompilationManager* const manager_;
2321};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002322
Andreas Gampeace0dc12016-01-20 13:33:13 -08002323void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2324 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002325 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002326 ThreadPool* thread_pool,
2327 size_t thread_count,
2328 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002329 TimingLogger::ScopedTiming t("Verify Dex File", timings);
2330 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2331 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2332 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002333 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002334 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002335}
2336
Mathieu Chartier90443472015-07-16 20:32:27 -07002337class InitializeClassVisitor : public CompilationVisitor {
2338 public:
2339 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002340
Mathieu Chartier90443472015-07-16 20:32:27 -07002341 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2342 ATRACE_CALL();
2343 jobject jclass_loader = manager_->GetClassLoader();
2344 const DexFile& dex_file = *manager_->GetDexFile();
2345 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2346 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2347 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002348
Mathieu Chartier90443472015-07-16 20:32:27 -07002349 ScopedObjectAccess soa(Thread::Current());
2350 StackHandleScope<3> hs(soa.Self());
2351 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002352 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002353 Handle<mirror::Class> klass(
2354 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2355
2356 if (klass.Get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) {
2357 // Only try to initialize classes that were successfully verified.
2358 if (klass->IsVerified()) {
2359 // Attempt to initialize the class but bail if we either need to initialize the super-class
2360 // or static fields.
2361 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002362 if (!klass->IsInitialized()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002363 // We don't want non-trivial class initialization occurring on multiple threads due to
2364 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2365 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2366 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2367 // after first initializing its parents, whose locks are acquired. This leads to a
2368 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2369 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2370 // than use a special Object for the purpose we use the Class of java.lang.Class.
2371 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2372 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2373 // Attempt to initialize allowing initialization of parent classes but still not static
2374 // fields.
2375 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
2376 if (!klass->IsInitialized()) {
2377 // We need to initialize static fields, we only do this for image classes that aren't
2378 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Vladimir Marko5f926052016-09-30 17:04:49 +00002379 bool can_init_static_fields = manager_->GetCompiler()->IsBootImage() &&
Mathieu Chartier90443472015-07-16 20:32:27 -07002380 manager_->GetCompiler()->IsImageClass(descriptor) &&
2381 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2382 if (can_init_static_fields) {
2383 VLOG(compiler) << "Initializing: " << descriptor;
2384 // TODO multithreading support. We should ensure the current compilation thread has
2385 // exclusive access to the runtime and the transaction. To achieve this, we could use
2386 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2387 // checks in Thread::AssertThreadSuspensionIsAllowable.
2388 Runtime* const runtime = Runtime::Current();
2389 Transaction transaction;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002390
Mathieu Chartier90443472015-07-16 20:32:27 -07002391 // Run the class initializer in transaction mode.
2392 runtime->EnterTransactionMode(&transaction);
2393 const mirror::Class::Status old_status = klass->GetStatus();
2394 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2395 true);
2396 // TODO we detach transaction from runtime to indicate we quit the transactional
2397 // mode which prevents the GC from visiting objects modified during the transaction.
2398 // Ensure GC is not run so don't access freed objects when aborting transaction.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002399
Mathieu Chartier268764d2016-09-13 12:09:38 -07002400 ScopedAssertNoThreadSuspension ants("Transaction end");
Mathieu Chartier90443472015-07-16 20:32:27 -07002401 runtime->ExitTransactionMode();
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002402
Mathieu Chartier90443472015-07-16 20:32:27 -07002403 if (!success) {
2404 CHECK(soa.Self()->IsExceptionPending());
2405 mirror::Throwable* exception = soa.Self()->GetException();
2406 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2407 << exception->Dump();
2408 std::ostream* file_log = manager_->GetCompiler()->
2409 GetCompilerOptions().GetInitFailureOutput();
2410 if (file_log != nullptr) {
2411 *file_log << descriptor << "\n";
2412 *file_log << exception->Dump() << "\n";
2413 }
2414 soa.Self()->ClearException();
2415 transaction.Rollback();
2416 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002417 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002418 }
2419 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002420 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002421 }
2422 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002423 // Record the final class status if necessary.
2424 ClassReference ref(manager_->GetDexFile(), class_def_index);
2425 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002426 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002427 // Clear any class not found or verification exceptions.
2428 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002429 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002430
2431 private:
2432 const ParallelCompilationManager* const manager_;
2433};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002434
Andreas Gampeace0dc12016-01-20 13:33:13 -08002435void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2436 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002437 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002438 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002439 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002440
2441 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2442 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2443 ThreadPool* init_thread_pool = force_determinism
2444 ? single_thread_pool_.get()
2445 : parallel_thread_pool_.get();
2446 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2447
Brian Carlstrom7940e442013-07-12 13:46:57 -07002448 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002449 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002450 init_thread_pool);
Vladimir Marko5f926052016-09-30 17:04:49 +00002451 if (IsBootImage()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002452 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002453 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002454 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002455 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002456 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002457}
2458
Mathieu Chartier91288d82016-04-28 09:44:54 -07002459class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002460 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002461 virtual bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier91288d82016-04-28 09:44:54 -07002462 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2463 return true;
2464 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002465 if (klass->IsArrayClass()) {
2466 StackHandleScope<1> hs(Thread::Current());
2467 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(),
2468 hs.NewHandle(klass),
2469 true,
2470 true);
2471 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002472 // Create the conflict tables.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002473 FillIMTAndConflictTables(klass);
Nicolas Geoffray88f288e2016-06-29 08:17:52 +00002474 return true;
Nelli Kimbadee982016-05-13 13:08:53 +03002475 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002476
2477 private:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002478 void FillIMTAndConflictTables(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002479 if (!klass->ShouldHaveImt()) {
2480 return;
2481 }
2482 if (visited_classes_.find(klass) != visited_classes_.end()) {
2483 return;
2484 }
2485 if (klass->HasSuperClass()) {
2486 FillIMTAndConflictTables(klass->GetSuperClass());
2487 }
2488 if (!klass->IsTemp()) {
2489 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
2490 }
2491 visited_classes_.insert(klass);
2492 }
2493
2494 std::set<mirror::Class*> visited_classes_;
Mathieu Chartier085a0722016-04-01 17:33:31 -07002495};
2496
Brian Carlstrom7940e442013-07-12 13:46:57 -07002497void CompilerDriver::InitializeClasses(jobject class_loader,
2498 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002499 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002500 for (size_t i = 0; i != dex_files.size(); ++i) {
2501 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002502 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002503 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002504 }
Vladimir Marko5f926052016-09-30 17:04:49 +00002505 if (boot_image_ || app_image_) {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002506 // Make sure that we call EnsureIntiailized on all the array classes to call
2507 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2508 // changed at runtime resulting in more dirty image pages.
Mathieu Chartier91288d82016-04-28 09:44:54 -07002509 // Also create conflict tables.
2510 // Only useful if we are compiling an image (image_classes_ is not null).
Mathieu Chartier085a0722016-04-01 17:33:31 -07002511 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier91288d82016-04-28 09:44:54 -07002512 InitializeArrayClassesAndCreateConflictTablesVisitor visitor;
2513 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
Mathieu Chartier085a0722016-04-01 17:33:31 -07002514 }
Vladimir Marko5f926052016-09-30 17:04:49 +00002515 if (IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002516 // Prune garbage objects created during aborted transactions.
2517 Runtime::Current()->GetHeap()->CollectGarbage(true);
2518 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002519}
2520
Andreas Gampeace0dc12016-01-20 13:33:13 -08002521void CompilerDriver::Compile(jobject class_loader,
2522 const std::vector<const DexFile*>& dex_files,
2523 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002524 if (kDebugProfileGuidedCompilation) {
2525 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2526 ((profile_compilation_info_ == nullptr)
2527 ? "null"
2528 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002529 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002530
2531 DCHECK(current_dex_to_dex_methods_ == nullptr);
2532 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002533 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002534 CompileDexFile(class_loader,
2535 *dex_file,
2536 dex_files,
2537 parallel_thread_pool_.get(),
2538 parallel_thread_count_,
2539 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002540 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2541 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2542 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002543 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002544 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002545
2546 ArrayRef<DexFileMethodSet> dex_to_dex_references;
2547 {
2548 // From this point on, we shall not modify dex_to_dex_references_, so
2549 // just grab a reference to it that we use without holding the mutex.
2550 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
2551 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
2552 }
2553 for (const auto& method_set : dex_to_dex_references) {
2554 current_dex_to_dex_methods_ = &method_set.GetMethodIndexes();
2555 CompileDexFile(class_loader,
2556 method_set.GetDexFile(),
2557 dex_files,
2558 parallel_thread_pool_.get(),
2559 parallel_thread_count_,
2560 timings);
2561 }
2562 current_dex_to_dex_methods_ = nullptr;
2563
Andreas Gampe8d295f82015-01-20 14:50:21 -08002564 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002565}
2566
Mathieu Chartier90443472015-07-16 20:32:27 -07002567class CompileClassVisitor : public CompilationVisitor {
2568 public:
2569 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2570
2571 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2572 ATRACE_CALL();
2573 const DexFile& dex_file = *manager_->GetDexFile();
2574 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2575 ClassLinker* class_linker = manager_->GetClassLinker();
2576 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002577 ClassReference ref(&dex_file, class_def_index);
2578 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2579 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002580 return;
2581 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002582 // Use a scoped object access to perform to the quick SkipClass check.
2583 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2584 ScopedObjectAccess soa(Thread::Current());
2585 StackHandleScope<3> hs(soa.Self());
2586 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002587 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier736b5602015-09-02 14:54:11 -07002588 Handle<mirror::Class> klass(
2589 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2590 Handle<mirror::DexCache> dex_cache;
2591 if (klass.Get() == nullptr) {
2592 soa.Self()->AssertPendingException();
2593 soa.Self()->ClearException();
2594 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2595 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2596 return;
2597 } else {
2598 dex_cache = hs.NewHandle(klass->GetDexCache());
2599 }
2600
Mathieu Chartier90443472015-07-16 20:32:27 -07002601 const uint8_t* class_data = dex_file.GetClassData(class_def);
2602 if (class_data == nullptr) {
2603 // empty class, probably a marker interface
2604 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002605 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002606
Mathieu Chartier736b5602015-09-02 14:54:11 -07002607 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002608 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002609
Mathieu Chartier90443472015-07-16 20:32:27 -07002610 CompilerDriver* const driver = manager_->GetCompiler();
2611
2612 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002613 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002614 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002615
Mathieu Chartier90443472015-07-16 20:32:27 -07002616 ClassDataItemIterator it(dex_file, class_data);
2617 // Skip fields
2618 while (it.HasNextStaticField()) {
2619 it.Next();
2620 }
2621 while (it.HasNextInstanceField()) {
2622 it.Next();
2623 }
2624
2625 bool compilation_enabled = driver->IsClassToCompile(
2626 dex_file.StringByTypeIdx(class_def.class_idx_));
2627
2628 // Compile direct methods
2629 int64_t previous_direct_method_idx = -1;
2630 while (it.HasNextDirectMethod()) {
2631 uint32_t method_idx = it.GetMemberIndex();
2632 if (method_idx == previous_direct_method_idx) {
2633 // smali can create dex files with two encoded_methods sharing the same method_idx
2634 // http://code.google.com/p/smali/issues/detail?id=119
2635 it.Next();
2636 continue;
2637 }
2638 previous_direct_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002639 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002640 it.GetMethodInvokeType(class_def), class_def_index,
2641 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002642 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002643 it.Next();
2644 }
2645 // Compile virtual methods
2646 int64_t previous_virtual_method_idx = -1;
2647 while (it.HasNextVirtualMethod()) {
2648 uint32_t method_idx = it.GetMemberIndex();
2649 if (method_idx == previous_virtual_method_idx) {
2650 // smali can create dex files with two encoded_methods sharing the same method_idx
2651 // http://code.google.com/p/smali/issues/detail?id=119
2652 it.Next();
2653 continue;
2654 }
2655 previous_virtual_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002656 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002657 it.GetMethodInvokeType(class_def), class_def_index,
2658 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002659 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002660 it.Next();
2661 }
2662 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002663 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002664
2665 private:
2666 const ParallelCompilationManager* const manager_;
2667};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002668
Andreas Gampeace0dc12016-01-20 13:33:13 -08002669void CompilerDriver::CompileDexFile(jobject class_loader,
2670 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002671 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002672 ThreadPool* thread_pool,
2673 size_t thread_count,
2674 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002675 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002676 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002677 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002678 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002679 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002680}
2681
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002682void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2683 CompiledMethod* const compiled_method,
2684 size_t non_relative_linker_patch_count) {
2685 DCHECK(GetCompiledMethod(method_ref) == nullptr)
2686 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
2687 {
2688 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2689 compiled_methods_.Put(method_ref, compiled_method);
2690 non_relative_linker_patch_count_ += non_relative_linker_patch_count;
Ian Rogersa4a3f402014-10-20 18:10:34 -07002691 }
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002692 DCHECK(GetCompiledMethod(method_ref) != nullptr)
2693 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002694}
2695
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002696void CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2697 CompiledMethod* compiled_method = nullptr;
2698 {
2699 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2700 auto it = compiled_methods_.find(method_ref);
2701 if (it != compiled_methods_.end()) {
2702 compiled_method = it->second;
2703 compiled_methods_.erase(it);
2704 }
2705 }
2706 if (compiled_method != nullptr) {
2707 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, compiled_method);
2708 }
2709}
2710
Brian Carlstrom7940e442013-07-12 13:46:57 -07002711CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
2712 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2713 ClassTable::const_iterator it = compiled_classes_.find(ref);
2714 if (it == compiled_classes_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002715 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002716 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002717 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002718 return it->second;
2719}
2720
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002721void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2722 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2723 auto it = compiled_classes_.find(ref);
2724 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2725 // An entry doesn't exist or the status is lower than the new status.
2726 if (it != compiled_classes_.end()) {
2727 CHECK_GT(status, it->second->GetStatus());
2728 delete it->second;
2729 }
2730 switch (status) {
2731 case mirror::Class::kStatusNotReady:
2732 case mirror::Class::kStatusError:
2733 case mirror::Class::kStatusRetryVerificationAtRuntime:
2734 case mirror::Class::kStatusVerified:
2735 case mirror::Class::kStatusInitialized:
Mathieu Chartiera8077802016-03-16 19:08:31 -07002736 case mirror::Class::kStatusResolved:
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002737 break; // Expected states.
2738 default:
2739 LOG(FATAL) << "Unexpected class status for class "
2740 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2741 << " of " << status;
2742 }
2743 CompiledClass* compiled_class = new CompiledClass(status);
2744 compiled_classes_.Overwrite(ref, compiled_class);
2745 }
2746}
2747
Brian Carlstrom7940e442013-07-12 13:46:57 -07002748CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2749 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2750 MethodTable::const_iterator it = compiled_methods_.find(ref);
2751 if (it == compiled_methods_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002752 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002753 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002754 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002755 return it->second;
2756}
2757
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002758bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2759 uint16_t class_def_idx,
2760 const DexFile& dex_file) const {
2761 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2762 if (verified_method != nullptr) {
2763 return !verified_method->HasVerificationFailures();
2764 }
2765
2766 // If we can't find verification metadata, check if this is a system class (we trust that system
2767 // classes have their methods verified). If it's not, be conservative and assume the method
2768 // has not been verified successfully.
2769
2770 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2771 // even if methods are not found in the verification cache.
2772 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2773 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2774 Thread* self = Thread::Current();
2775 ScopedObjectAccess soa(self);
2776 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2777 if (!is_system_class) {
2778 self->ClearException();
2779 }
2780 return is_system_class;
2781}
2782
Vladimir Markof4da6752014-08-01 19:04:18 +01002783size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
2784 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2785 return non_relative_linker_patch_count_;
2786}
2787
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002788void CompilerDriver::SetRequiresConstructorBarrier(Thread* self,
2789 const DexFile* dex_file,
2790 uint16_t class_def_index,
2791 bool requires) {
2792 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2793 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002794}
2795
Mathieu Chartier371bd832016-04-07 10:19:48 -07002796bool CompilerDriver::RequiresConstructorBarrier(Thread* self,
2797 const DexFile* dex_file,
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002798 uint16_t class_def_index) {
2799 ClassReference class_ref(dex_file, class_def_index);
2800 {
2801 ReaderMutexLock mu(self, requires_constructor_barrier_lock_);
2802 auto it = requires_constructor_barrier_.find(class_ref);
2803 if (it != requires_constructor_barrier_.end()) {
2804 return it->second;
2805 }
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002806 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002807 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2808 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index);
2809 requires_constructor_barrier_.emplace(class_ref, requires);
2810 return requires;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002811}
2812
Andreas Gampe8d295f82015-01-20 14:50:21 -08002813std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002814 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002815 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002816 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002817 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002818 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002819#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002820 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002821 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2822 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002823 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2824 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002825#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002826 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002827 return oss.str();
2828}
2829
Jeff Haodcdc85b2015-12-04 14:06:18 -08002830bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
2831 const DexFile* inlined_into) const {
2832 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
2833 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00002834 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
2835 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002836 return false;
2837 }
2838
2839 return true;
2840}
2841
Andreas Gampeace0dc12016-01-20 13:33:13 -08002842void CompilerDriver::InitializeThreadPools() {
2843 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2844 parallel_thread_pool_.reset(
2845 new ThreadPool("Compiler driver thread pool", parallel_count));
2846 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2847}
2848
2849void CompilerDriver::FreeThreadPools() {
2850 parallel_thread_pool_.reset();
2851 single_thread_pool_.reset();
2852}
2853
Brian Carlstrom7940e442013-07-12 13:46:57 -07002854} // namespace art