blob: 4c0095d70a48647134d7ecda3943315010582f05 [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"
Vladimir Marko492a7fa2016-06-01 18:38:43 +010029#include "base/bit_vector.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070030#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080031#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010032#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070033#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010034#include "class_linker-inl.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070035#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000036#include "compiled_method.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000037#include "compiler.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000038#include "compiler_driver-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070039#include "dex_compilation_unit.h"
40#include "dex_file-inl.h"
Andreas Gampeace0dc12016-01-20 13:33:13 -080041#include "dex_instruction-inl.h"
Andreas Gampe5eb0d382015-07-23 01:19:26 -070042#include "dex/dex_to_dex_compiler.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000043#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000044#include "dex/verified_method.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000045#include "dex/quick/dex_file_method_inliner.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080046#include "dex/quick/dex_file_to_method_inliner_map.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080047#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070048#include "jni_internal.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070049#include "object_lock.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "runtime.h"
51#include "gc/accounting/card_table-inl.h"
52#include "gc/accounting/heap_bitmap.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070053#include "gc/space/image_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "gc/space/space.h"
55#include "mirror/class_loader.h"
56#include "mirror/class-inl.h"
57#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "mirror/object-inl.h"
59#include "mirror/object_array-inl.h"
60#include "mirror/throwable.h"
61#include "scoped_thread_state_change.h"
62#include "ScopedLocalRef.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070063#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "thread.h"
Andreas Gampeb0f370e2014-09-25 22:51:40 -070065#include "thread_list.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070067#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010068#include "transaction.h"
Vladimir Marko492a7fa2016-06-01 18:38:43 +010069#include "utils/array_ref.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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070074
Brian Carlstrom7940e442013-07-12 13:46:57 -070075namespace art {
76
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070077static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
78
Andreas Gampe70bef0d2015-04-15 02:37:28 -070079// Whether classes-to-compile and methods-to-compile are only applied to the boot image, or, when
80// given, too all compilations.
Andreas Gampeb1fcead2015-04-20 18:53:51 -070081static constexpr bool kRestrictCompilationFiltersToImage = true;
82
Calin Juravle226501b2015-12-11 14:41:31 +000083// Print additional info during profile guided compilation.
84static constexpr bool kDebugProfileGuidedCompilation = false;
85
Brian Carlstrom7940e442013-07-12 13:46:57 -070086static double Percentage(size_t x, size_t y) {
87 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
88}
89
90static void DumpStat(size_t x, size_t y, const char* str) {
91 if (x == 0 && y == 0) {
92 return;
93 }
Ian Rogerse732ef12013-10-09 15:22:24 -070094 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -070095}
96
Vladimir Markof096aad2014-01-23 15:51:58 +000097class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -070098 public:
99 AOTCompilationStats()
100 : stats_lock_("AOT compilation statistics lock"),
101 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
102 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
103 resolved_types_(0), unresolved_types_(0),
104 resolved_instance_fields_(0), unresolved_instance_fields_(0),
105 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
106 type_based_devirtualization_(0),
107 safe_casts_(0), not_safe_casts_(0) {
108 for (size_t i = 0; i <= kMaxInvokeType; i++) {
109 resolved_methods_[i] = 0;
110 unresolved_methods_[i] = 0;
111 virtual_made_direct_[i] = 0;
112 direct_calls_to_boot_[i] = 0;
113 direct_methods_to_boot_[i] = 0;
114 }
115 }
116
117 void Dump() {
118 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
119 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
120 DumpStat(resolved_types_, unresolved_types_, "types resolved");
121 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
122 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
123 "static fields resolved");
124 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
125 "static fields local to a class");
126 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
127 // Note, the code below subtracts the stat value so that when added to the stat value we have
128 // 100% of samples. TODO: clean this up.
129 DumpStat(type_based_devirtualization_,
130 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
131 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
132 type_based_devirtualization_,
133 "virtual/interface calls made direct based on type information");
134
135 for (size_t i = 0; i <= kMaxInvokeType; i++) {
136 std::ostringstream oss;
137 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
138 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
139 if (virtual_made_direct_[i] > 0) {
140 std::ostringstream oss2;
141 oss2 << static_cast<InvokeType>(i) << " methods made direct";
142 DumpStat(virtual_made_direct_[i],
143 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
144 oss2.str().c_str());
145 }
146 if (direct_calls_to_boot_[i] > 0) {
147 std::ostringstream oss2;
148 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
149 DumpStat(direct_calls_to_boot_[i],
150 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
151 oss2.str().c_str());
152 }
153 if (direct_methods_to_boot_[i] > 0) {
154 std::ostringstream oss2;
155 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
156 DumpStat(direct_methods_to_boot_[i],
157 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
158 oss2.str().c_str());
159 }
160 }
161 }
162
163// Allow lossy statistics in non-debug builds.
164#ifndef NDEBUG
165#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
166#else
167#define STATS_LOCK()
168#endif
169
Mathieu Chartier90443472015-07-16 20:32:27 -0700170 void TypeInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700171 STATS_LOCK();
172 types_in_dex_cache_++;
173 }
174
Mathieu Chartier90443472015-07-16 20:32:27 -0700175 void TypeNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700176 STATS_LOCK();
177 types_not_in_dex_cache_++;
178 }
179
Mathieu Chartier90443472015-07-16 20:32:27 -0700180 void StringInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700181 STATS_LOCK();
182 strings_in_dex_cache_++;
183 }
184
Mathieu Chartier90443472015-07-16 20:32:27 -0700185 void StringNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700186 STATS_LOCK();
187 strings_not_in_dex_cache_++;
188 }
189
Mathieu Chartier90443472015-07-16 20:32:27 -0700190 void TypeDoesntNeedAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700191 STATS_LOCK();
192 resolved_types_++;
193 }
194
Mathieu Chartier90443472015-07-16 20:32:27 -0700195 void TypeNeedsAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700196 STATS_LOCK();
197 unresolved_types_++;
198 }
199
Mathieu Chartier90443472015-07-16 20:32:27 -0700200 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700201 STATS_LOCK();
202 resolved_instance_fields_++;
203 }
204
Mathieu Chartier90443472015-07-16 20:32:27 -0700205 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700206 STATS_LOCK();
207 unresolved_instance_fields_++;
208 }
209
Mathieu Chartier90443472015-07-16 20:32:27 -0700210 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700211 STATS_LOCK();
212 resolved_local_static_fields_++;
213 }
214
Mathieu Chartier90443472015-07-16 20:32:27 -0700215 void ResolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700216 STATS_LOCK();
217 resolved_static_fields_++;
218 }
219
Mathieu Chartier90443472015-07-16 20:32:27 -0700220 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700221 STATS_LOCK();
222 unresolved_static_fields_++;
223 }
224
225 // Indicate that type information from the verifier led to devirtualization.
Mathieu Chartier90443472015-07-16 20:32:27 -0700226 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700227 STATS_LOCK();
228 type_based_devirtualization_++;
229 }
230
231 // Indicate that a method of the given type was resolved at compile time.
Mathieu Chartier90443472015-07-16 20:32:27 -0700232 void ResolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700233 DCHECK_LE(type, kMaxInvokeType);
234 STATS_LOCK();
235 resolved_methods_[type]++;
236 }
237
238 // Indicate that a method of the given type was unresolved at compile time as it was in an
239 // unknown dex file.
Mathieu Chartier90443472015-07-16 20:32:27 -0700240 void UnresolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700241 DCHECK_LE(type, kMaxInvokeType);
242 STATS_LOCK();
243 unresolved_methods_[type]++;
244 }
245
246 // Indicate that a type of virtual method dispatch has been converted into a direct method
247 // dispatch.
Mathieu Chartier90443472015-07-16 20:32:27 -0700248 void VirtualMadeDirect(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700249 DCHECK(type == kVirtual || type == kInterface || type == kSuper);
250 STATS_LOCK();
251 virtual_made_direct_[type]++;
252 }
253
254 // Indicate that a method of the given type was able to call directly into boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700255 void DirectCallsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700256 DCHECK_LE(type, kMaxInvokeType);
257 STATS_LOCK();
258 direct_calls_to_boot_[type]++;
259 }
260
261 // Indicate that a method of the given type was able to be resolved directly from boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700262 void DirectMethodsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700263 DCHECK_LE(type, kMaxInvokeType);
264 STATS_LOCK();
265 direct_methods_to_boot_[type]++;
266 }
267
Mathieu Chartier90443472015-07-16 20:32:27 -0700268 void ProcessedInvoke(InvokeType type, int flags) REQUIRES(!stats_lock_) {
Vladimir Markof096aad2014-01-23 15:51:58 +0000269 STATS_LOCK();
270 if (flags == 0) {
271 unresolved_methods_[type]++;
272 } else {
273 DCHECK_NE((flags & kFlagMethodResolved), 0);
274 resolved_methods_[type]++;
275 if ((flags & kFlagVirtualMadeDirect) != 0) {
276 virtual_made_direct_[type]++;
277 if ((flags & kFlagPreciseTypeDevirtualization) != 0) {
278 type_based_devirtualization_++;
279 }
280 } else {
281 DCHECK_EQ((flags & kFlagPreciseTypeDevirtualization), 0);
282 }
283 if ((flags & kFlagDirectCallToBoot) != 0) {
284 direct_calls_to_boot_[type]++;
285 }
286 if ((flags & kFlagDirectMethodToBoot) != 0) {
287 direct_methods_to_boot_[type]++;
288 }
289 }
290 }
291
Brian Carlstrom7940e442013-07-12 13:46:57 -0700292 // A check-cast could be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700293 void SafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700294 STATS_LOCK();
295 safe_casts_++;
296 }
297
298 // A check-cast couldn't be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700299 void NotASafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700300 STATS_LOCK();
301 not_safe_casts_++;
302 }
303
304 private:
305 Mutex stats_lock_;
306
307 size_t types_in_dex_cache_;
308 size_t types_not_in_dex_cache_;
309
310 size_t strings_in_dex_cache_;
311 size_t strings_not_in_dex_cache_;
312
313 size_t resolved_types_;
314 size_t unresolved_types_;
315
316 size_t resolved_instance_fields_;
317 size_t unresolved_instance_fields_;
318
319 size_t resolved_local_static_fields_;
320 size_t resolved_static_fields_;
321 size_t unresolved_static_fields_;
322 // Type based devirtualization for invoke interface and virtual.
323 size_t type_based_devirtualization_;
324
325 size_t resolved_methods_[kMaxInvokeType + 1];
326 size_t unresolved_methods_[kMaxInvokeType + 1];
327 size_t virtual_made_direct_[kMaxInvokeType + 1];
328 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
329 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
330
331 size_t safe_casts_;
332 size_t not_safe_casts_;
333
334 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
335};
336
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100337class CompilerDriver::DexFileMethodSet {
338 public:
339 explicit DexFileMethodSet(const DexFile& dex_file)
340 : dex_file_(dex_file),
341 method_indexes_(dex_file.NumMethodIds(), false, Allocator::GetMallocAllocator()) {
342 }
343 DexFileMethodSet(DexFileMethodSet&& other) = default;
344
345 const DexFile& GetDexFile() const { return dex_file_; }
346
347 BitVector& GetMethodIndexes() { return method_indexes_; }
348 const BitVector& GetMethodIndexes() const { return method_indexes_; }
349
350 private:
351 const DexFile& dex_file_;
352 BitVector method_indexes_;
353};
354
Jeff Haodcdc85b2015-12-04 14:06:18 -0800355CompilerDriver::CompilerDriver(
356 const CompilerOptions* compiler_options,
357 VerificationResults* verification_results,
358 DexFileToMethodInlinerMap* method_inliner_map,
359 Compiler::Kind compiler_kind,
360 InstructionSet instruction_set,
361 const InstructionSetFeatures* instruction_set_features,
Vladimir Marko944da602016-02-19 12:27:55 +0000362 bool boot_image,
Mathieu Chartier91288d82016-04-28 09:44:54 -0700363 bool app_image,
Vladimir Marko944da602016-02-19 12:27:55 +0000364 std::unordered_set<std::string>* image_classes,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800365 std::unordered_set<std::string>* compiled_classes,
366 std::unordered_set<std::string>* compiled_methods,
Vladimir Marko944da602016-02-19 12:27:55 +0000367 size_t thread_count,
368 bool dump_stats,
369 bool dump_passes,
370 CumulativeLogger* timer,
371 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200372 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000373 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800374 verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000375 method_inliner_map_(method_inliner_map),
Ian Rogers72d32622014-05-06 16:20:11 -0700376 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700377 compiler_kind_(compiler_kind),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700378 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700379 instruction_set_features_(instruction_set_features),
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700380 requires_constructor_barrier_lock_("constructor barrier lock"),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700381 compiled_classes_lock_("compiled classes lock"),
382 compiled_methods_lock_("compiled method lock"),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800383 compiled_methods_(MethodTable::key_compare()),
Vladimir Markof4da6752014-08-01 19:04:18 +0100384 non_relative_linker_patch_count_(0u),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800385 boot_image_(boot_image),
Mathieu Chartier91288d82016-04-28 09:44:54 -0700386 app_image_(app_image),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700387 image_classes_(image_classes),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800388 classes_to_compile_(compiled_classes),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700389 methods_to_compile_(compiled_methods),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800390 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800391 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700392 stats_(new AOTCompilationStats),
393 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000394 dump_passes_(dump_passes),
395 timings_logger_(timer),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700396 compiler_context_(nullptr),
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700397 support_boot_image_fixup_(instruction_set != kMips64),
Vladimir Markod1eaf0d2015-10-29 12:18:29 +0000398 dex_files_for_oat_file_(nullptr),
Calin Juravle998c2162015-12-21 15:39:33 +0200399 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000400 profile_compilation_info_(profile_compilation_info),
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100401 max_arena_alloc_(0),
402 dex_to_dex_references_lock_("dex-to-dex references lock"),
403 dex_to_dex_references_(),
404 current_dex_to_dex_methods_(nullptr) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800405 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom6449c622014-02-10 23:48:36 -0800406 DCHECK(method_inliner_map_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700407
Ian Rogers72d32622014-05-06 16:20:11 -0700408 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700409
Mathieu Chartiera8077802016-03-16 19:08:31 -0700410 if (compiler_options->VerifyOnlyProfile()) {
411 CHECK(profile_compilation_info_ != nullptr) << "Requires profile";
412 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800413 if (boot_image_) {
414 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image";
415 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700416}
417
418CompilerDriver::~CompilerDriver() {
419 Thread* self = Thread::Current();
420 {
421 MutexLock mu(self, compiled_classes_lock_);
422 STLDeleteValues(&compiled_classes_);
423 }
424 {
425 MutexLock mu(self, compiled_methods_lock_);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800426 for (auto& pair : compiled_methods_) {
427 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, pair.second);
428 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700429 }
Ian Rogers72d32622014-05-06 16:20:11 -0700430 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700431}
432
Vladimir Marko35831e82015-09-11 11:59:18 +0100433
Ian Rogersdd7624d2014-03-14 17:43:00 -0700434#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700435 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700436 return CreateTrampoline64(instruction_set_, abi, \
437 type ## _ENTRYPOINT_OFFSET(8, offset)); \
438 } else { \
439 return CreateTrampoline32(instruction_set_, abi, \
440 type ## _ENTRYPOINT_OFFSET(4, offset)); \
441 }
442
Vladimir Marko93205e32016-04-13 11:59:46 +0100443std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700444 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700445}
446
Vladimir Marko93205e32016-04-13 11:59:46 +0100447std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
448 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700449 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800450}
451
Vladimir Marko93205e32016-04-13 11:59:46 +0100452std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
453 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700454 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700455}
456
Vladimir Marko93205e32016-04-13 11:59:46 +0100457std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
458 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700459 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700460}
461
Vladimir Marko93205e32016-04-13 11:59:46 +0100462std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
463 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700464 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700465}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700466#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700467
468void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700469 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800470 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700471 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800472
473 InitializeThreadPools();
474
Andreas Gampe8d295f82015-01-20 14:50:21 -0800475 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
Andreas Gampe740667a2015-09-15 17:55:06 -0700476 // Precompile:
477 // 1) Load image classes
478 // 2) Resolve all classes
479 // 3) Attempt to verify all classes
480 // 4) Attempt to initialize image classes, and trivially initialized classes
Andreas Gampeace0dc12016-01-20 13:33:13 -0800481 PreCompile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700482 // Compile:
483 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
484 // compilation.
485 if (!GetCompilerOptions().VerifyAtRuntime()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800486 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700487 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700488 if (dump_stats_) {
489 stats_->Dump();
490 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800491
492 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700493}
494
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700495static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
496 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
497 const DexFile& dex_file, const DexFile::ClassDef& class_def)
498 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800499 auto* const runtime = Runtime::Current();
Calin Juravleffc87072016-04-20 14:22:09 +0100500 if (runtime->UseJitCompilation() || driver.GetCompilerOptions().VerifyAtRuntime()) {
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700501 // Verify at runtime shouldn't dex to dex since we didn't resolve of verify.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700502 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800503 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700504 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800505 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800506 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700507 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700508 CHECK(self->IsExceptionPending());
509 self->ClearException();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700510 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700511 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700512 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
513 // references with actual offsets. We cannot re-verify such instructions.
514 //
515 // We store the verification information in the class status in the oat file, which the linker
516 // can validate (checksums) and use to skip load-time verification. It is thus safe to
517 // optimize when a class has been fully verified before.
518 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200519 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700520 return optimizer::DexToDexCompilationLevel::kOptimize;
Sebastien Hertz75021222013-07-16 18:34:50 +0200521 } else if (klass->IsCompileTimeVerified()) {
522 // Class verification has soft-failed. Anyway, ensure at least correctness.
523 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700524 return optimizer::DexToDexCompilationLevel::kRequired;
Sebastien Hertz75021222013-07-16 18:34:50 +0200525 } else {
526 // Class verification has failed: do not run DEX-to-DEX compilation.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700527 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
528 }
529}
530
531static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
532 Thread* self,
533 const CompilerDriver& driver,
534 jobject jclass_loader,
535 const DexFile& dex_file,
536 const DexFile::ClassDef& class_def) {
537 ScopedObjectAccess soa(self);
538 StackHandleScope<1> hs(soa.Self());
539 Handle<mirror::ClassLoader> class_loader(
540 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
541 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
542}
543
544// Does the runtime for the InstructionSet provide an implementation returned by
545// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
546static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
547 switch (isa) {
548 case kArm:
549 case kArm64:
550 case kThumb2:
551 case kMips:
552 case kMips64:
553 case kX86:
554 case kX86_64: return true;
555 default: return false;
556 }
557}
558
559static void CompileMethod(Thread* self,
560 CompilerDriver* driver,
561 const DexFile::CodeItem* code_item,
562 uint32_t access_flags,
563 InvokeType invoke_type,
564 uint16_t class_def_idx,
565 uint32_t method_idx,
566 jobject class_loader,
567 const DexFile& dex_file,
568 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700569 bool compilation_enabled,
570 Handle<mirror::DexCache> dex_cache)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700571 REQUIRES(!driver->compiled_methods_lock_) {
572 DCHECK(driver != nullptr);
573 CompiledMethod* compiled_method = nullptr;
574 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
575 MethodReference method_ref(&dex_file, method_idx);
576
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100577 if (driver->GetCurrentDexToDexMethods() != nullptr) {
578 // This is the second pass when we dex-to-dex compile previously marked methods.
579 // TODO: Refactor the compilation to avoid having to distinguish the two passes
580 // here. That should be done on a higher level. http://b/29089975
581 if (driver->GetCurrentDexToDexMethods()->IsBitSet(method_idx)) {
582 const VerifiedMethod* verified_method =
583 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
584 // Do not optimize if a VerifiedMethod is missing. SafeCast elision,
585 // for example, relies on it.
586 compiled_method = optimizer::ArtCompileDEX(
587 driver,
588 code_item,
589 access_flags,
590 invoke_type,
591 class_def_idx,
592 method_idx,
593 class_loader,
594 dex_file,
595 (verified_method != nullptr)
596 ? dex_to_dex_compilation_level
597 : optimizer::DexToDexCompilationLevel::kRequired);
598 }
599 } else if ((access_flags & kAccNative) != 0) {
Vladimir Markof6d1e0f2016-05-23 15:32:42 +0100600 // Are we extracting only and have support for generic JNI down calls?
601 if (!driver->GetCompilerOptions().IsJniCompilationEnabled() &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700602 InstructionSetHasGenericJniStub(driver->GetInstructionSet())) {
603 // Leaving this empty will trigger the generic JNI version
604 } else {
605 compiled_method = driver->GetCompiler()->JniCompile(access_flags, method_idx, dex_file);
606 CHECK(compiled_method != nullptr);
607 }
608 } else if ((access_flags & kAccAbstract) != 0) {
609 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000610 } else {
Andreas Gampe0760a812015-08-26 17:12:51 -0700611 const VerifiedMethod* verified_method =
612 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700613 bool compile = compilation_enabled &&
614 // Basic checks, e.g., not <clinit>.
615 driver->GetVerificationResults()
616 ->IsCandidateForCompilation(method_ref, access_flags) &&
617 // Did not fail to create VerifiedMethod metadata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700618 verified_method != nullptr &&
619 // Do not have failures that should punt to the interpreter.
620 !verified_method->HasRuntimeThrow() &&
621 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700622 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700623 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000624 driver->IsMethodToCompile(method_ref) &&
625 driver->ShouldCompileBasedOnProfile(method_ref);
626
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700627 if (compile) {
628 // NOTE: if compiler declines to compile this method, it will return null.
629 compiled_method = driver->GetCompiler()->Compile(code_item, access_flags, invoke_type,
630 class_def_idx, method_idx, class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700631 dex_file, dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700632 }
633 if (compiled_method == nullptr &&
634 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100635 DCHECK(!Runtime::Current()->UseJitCompilation());
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700636 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100637 driver->MarkForDexToDexCompilation(self, method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700638 }
639 }
640 if (kTimeCompileMethod) {
641 uint64_t duration_ns = NanoTime() - start_ns;
642 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
643 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
644 << " took " << PrettyDuration(duration_ns);
645 }
646 }
647
648 if (compiled_method != nullptr) {
649 // Count non-relative linker patches.
650 size_t non_relative_linker_patch_count = 0u;
651 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
652 if (!patch.IsPcRelative()) {
653 ++non_relative_linker_patch_count;
654 }
655 }
656 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
657 // When compiling with PIC, there should be zero non-relative linker patches
658 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
659
660 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
661 }
662
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700663 if (self->IsExceptionPending()) {
664 ScopedObjectAccess soa(self);
665 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
666 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200667 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700668}
669
Mathieu Chartiere401d142015-04-22 13:56:20 -0700670void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700671 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700672 jobject jclass_loader;
673 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700674 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800675 uint32_t method_idx = method->GetDexMethodIndex();
676 uint32_t access_flags = method->GetAccessFlags();
677 InvokeType invoke_type = method->GetInvokeType();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700678 StackHandleScope<1> hs(self);
679 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700680 {
681 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800682 ScopedLocalRef<jobject> local_class_loader(
683 soa.Env(), soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700684 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
685 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700686 dex_file = method->GetDexFile();
687 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700688 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800689 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700690
691 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700692 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700693
694 std::vector<const DexFile*> dex_files;
695 dex_files.push_back(dex_file);
696
Andreas Gampeace0dc12016-01-20 13:33:13 -0800697 InitializeThreadPools();
698
699 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700700
Brian Carlstrom7940e442013-07-12 13:46:57 -0700701 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700702 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
703 GetDexToDexCompilationLevel(self,
704 *this,
705 jclass_loader,
706 *dex_file,
707 dex_file->GetClassDef(class_def_idx));
708
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100709 DCHECK(current_dex_to_dex_methods_ == nullptr);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700710 CompileMethod(self,
711 this,
712 code_item,
713 access_flags,
714 invoke_type,
715 class_def_idx,
716 method_idx,
717 jclass_loader,
718 *dex_file,
719 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700720 true,
721 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700722
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100723 ArrayRef<DexFileMethodSet> dex_to_dex_references;
724 {
725 // From this point on, we shall not modify dex_to_dex_references_, so
726 // just grab a reference to it that we use without holding the mutex.
727 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
728 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
729 }
730 if (!dex_to_dex_references.empty()) {
731 DCHECK_EQ(dex_to_dex_references.size(), 1u);
732 DCHECK(&dex_to_dex_references[0].GetDexFile() == dex_file);
733 current_dex_to_dex_methods_ = &dex_to_dex_references.front().GetMethodIndexes();
734 DCHECK(current_dex_to_dex_methods_->IsBitSet(method_idx));
735 DCHECK_EQ(current_dex_to_dex_methods_->NumSetBits(), 1u);
736 CompileMethod(self,
737 this,
738 code_item,
739 access_flags,
740 invoke_type,
741 class_def_idx,
742 method_idx,
743 jclass_loader,
744 *dex_file,
745 dex_to_dex_compilation_level,
746 true,
747 dex_cache);
748 current_dex_to_dex_methods_ = nullptr;
749 }
750
Andreas Gampeace0dc12016-01-20 13:33:13 -0800751 FreeThreadPools();
752
Brian Carlstrom7940e442013-07-12 13:46:57 -0700753 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800754}
755
Andreas Gampeace0dc12016-01-20 13:33:13 -0800756void CompilerDriver::Resolve(jobject class_loader,
757 const std::vector<const DexFile*>& dex_files,
758 TimingLogger* timings) {
759 // Resolution allocates classes and needs to run single-threaded to be deterministic.
760 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
761 ThreadPool* resolve_thread_pool = force_determinism
762 ? single_thread_pool_.get()
763 : parallel_thread_pool_.get();
764 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
765
Brian Carlstrom7940e442013-07-12 13:46:57 -0700766 for (size_t i = 0; i != dex_files.size(); ++i) {
767 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700768 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800769 ResolveDexFile(class_loader,
770 *dex_file,
771 dex_files,
772 resolve_thread_pool,
773 resolve_thread_count,
774 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700775 }
776}
777
Andreas Gampeace0dc12016-01-20 13:33:13 -0800778// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
779// this is single-threaded for simplicity.
780// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
781// stable order.
782
783static void ResolveConstStrings(CompilerDriver* driver,
784 const DexFile& dex_file,
785 const DexFile::CodeItem* code_item) {
786 if (code_item == nullptr) {
787 // Abstract or native method.
788 return;
789 }
790
791 const uint16_t* code_ptr = code_item->insns_;
792 const uint16_t* code_end = code_item->insns_ + code_item->insns_size_in_code_units_;
793
794 while (code_ptr < code_end) {
795 const Instruction* inst = Instruction::At(code_ptr);
796 switch (inst->Opcode()) {
797 case Instruction::CONST_STRING: {
798 uint32_t string_index = inst->VRegB_21c();
799 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
800 break;
801 }
802 case Instruction::CONST_STRING_JUMBO: {
803 uint32_t string_index = inst->VRegB_31c();
804 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
805 break;
806 }
807
808 default:
809 break;
810 }
811
812 code_ptr += inst->SizeInCodeUnits();
813 }
814}
815
816static void ResolveConstStrings(CompilerDriver* driver,
817 const std::vector<const DexFile*>& dex_files,
818 TimingLogger* timings) {
819 for (const DexFile* dex_file : dex_files) {
820 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
821
822 size_t class_def_count = dex_file->NumClassDefs();
823 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
824 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
825
826 const uint8_t* class_data = dex_file->GetClassData(class_def);
827 if (class_data == nullptr) {
828 // empty class, probably a marker interface
829 continue;
830 }
831
832 ClassDataItemIterator it(*dex_file, class_data);
833 // Skip fields
834 while (it.HasNextStaticField()) {
835 it.Next();
836 }
837 while (it.HasNextInstanceField()) {
838 it.Next();
839 }
840
841 bool compilation_enabled = driver->IsClassToCompile(
842 dex_file->StringByTypeIdx(class_def.class_idx_));
843 if (!compilation_enabled) {
844 // Compilation is skipped, do not resolve const-string in code of this class.
845 // TODO: Make sure that inlining honors this.
846 continue;
847 }
848
849 // Direct methods.
850 int64_t previous_direct_method_idx = -1;
851 while (it.HasNextDirectMethod()) {
852 uint32_t method_idx = it.GetMemberIndex();
853 if (method_idx == previous_direct_method_idx) {
854 // smali can create dex files with two encoded_methods sharing the same method_idx
855 // http://code.google.com/p/smali/issues/detail?id=119
856 it.Next();
857 continue;
858 }
859 previous_direct_method_idx = method_idx;
860 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
861 it.Next();
862 }
863 // Virtual methods.
864 int64_t previous_virtual_method_idx = -1;
865 while (it.HasNextVirtualMethod()) {
866 uint32_t method_idx = it.GetMemberIndex();
867 if (method_idx == previous_virtual_method_idx) {
868 // smali can create dex files with two encoded_methods sharing the same method_idx
869 // http://code.google.com/p/smali/issues/detail?id=119
870 it.Next();
871 continue;
872 }
873 previous_virtual_method_idx = method_idx;
874 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
875 it.Next();
876 }
877 DCHECK(!it.HasNext());
878 }
879 }
880}
881
882inline void CompilerDriver::CheckThreadPools() {
883 DCHECK(parallel_thread_pool_ != nullptr);
884 DCHECK(single_thread_pool_ != nullptr);
885}
886
887void CompilerDriver::PreCompile(jobject class_loader,
888 const std::vector<const DexFile*>& dex_files,
889 TimingLogger* timings) {
890 CheckThreadPools();
891
Brian Carlstrom7940e442013-07-12 13:46:57 -0700892 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800893 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700894
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700895 const bool verification_enabled = compiler_options_->IsVerificationEnabled();
896 const bool never_verify = compiler_options_->NeverVerify();
Mathieu Chartiera8077802016-03-16 19:08:31 -0700897 const bool verify_only_profile = compiler_options_->VerifyOnlyProfile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700898
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700899 // We need to resolve for never_verify since it needs to run dex to dex to add the
900 // RETURN_VOID_NO_BARRIER.
Mathieu Chartiera8077802016-03-16 19:08:31 -0700901 // Let the verifier resolve as needed for the verify_only_profile case.
902 if ((never_verify || verification_enabled) && !verify_only_profile) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800903 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700904 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
905 }
906
907 if (never_verify) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800908 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800909 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700910 }
911
912 if (!verification_enabled) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700913 return;
914 }
915
Andreas Gampeace0dc12016-01-20 13:33:13 -0800916 if (GetCompilerOptions().IsForceDeterminism() && IsBootImage()) {
917 // Resolve strings from const-string. Do this now to have a deterministic image.
918 ResolveConstStrings(this, dex_files, timings);
919 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
920 }
921
922 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800923 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700924
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800925 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
926 LOG(FATAL) << "Had a hard failure verifying all classes, and was asked to abort in such "
927 << "situations. Please check the log.";
928 }
929
Andreas Gampeace0dc12016-01-20 13:33:13 -0800930 InitializeClasses(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800931 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700932
933 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800934 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700935}
936
Ian Rogersdfb325e2013-10-30 01:00:44 -0700937bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800938 if (image_classes_ != nullptr) {
939 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -0700940 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700941 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800942 // No set of image classes, assume we include all the classes.
943 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
944 return !IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700945}
946
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800947bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800948 if (kRestrictCompilationFiltersToImage && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800949 return true;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800950 }
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700951
952 if (classes_to_compile_ == nullptr) {
953 return true;
954 }
955 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800956}
957
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700958bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800959 if (kRestrictCompilationFiltersToImage && !IsBootImage()) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700960 return true;
961 }
962
963 if (methods_to_compile_ == nullptr) {
964 return true;
965 }
966
967 std::string tmp = PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
968 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
969}
970
Calin Juravle226501b2015-12-11 14:41:31 +0000971bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
972 if (profile_compilation_info_ == nullptr) {
973 // If we miss profile information it means that we don't do a profile guided compilation.
974 // Return true, and let the other filters decide if the method should be compiled.
975 return true;
976 }
977 bool result = profile_compilation_info_->ContainsMethod(method_ref);
978
979 if (kDebugProfileGuidedCompilation) {
980 LOG(INFO) << "[ProfileGuidedCompilation] "
981 << (result ? "Compiled" : "Skipped") << " method:"
982 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
983 }
984 return result;
985}
986
Mathieu Chartiera8077802016-03-16 19:08:31 -0700987bool CompilerDriver::ShouldVerifyClassBasedOnProfile(const DexFile& dex_file,
988 uint16_t class_idx) const {
989 if (!compiler_options_->VerifyOnlyProfile()) {
990 // No profile, verify everything.
991 return true;
992 }
993 DCHECK(profile_compilation_info_ != nullptr);
994 bool result = profile_compilation_info_->ContainsClass(dex_file, class_idx);
995 if (kDebugProfileGuidedCompilation) {
996 LOG(INFO) << "[ProfileGuidedCompilation] "
997 << (result ? "Verified" : "Skipped") << " method:"
998 << dex_file.GetClassDescriptor(dex_file.GetClassDef(class_idx));
999 }
1000 return result;
1001}
1002
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001003class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
1004 public:
Chih-Hung Hsieh471118e2016-04-29 14:27:41 -07001005 explicit ResolveCatchBlockExceptionsClassVisitor(
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001006 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve)
1007 : exceptions_to_resolve_(exceptions_to_resolve) {}
1008
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001009 virtual bool operator()(mirror::Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001010 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Alex Lighte64300b2015-12-15 15:02:47 -08001011 for (auto& m : c->GetMethods(pointer_size)) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001012 ResolveExceptionsForMethod(&m, pointer_size);
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001013 }
1014 return true;
1015 }
1016
1017 private:
Vladimir Marko05792b92015-08-03 11:56:49 +01001018 void ResolveExceptionsForMethod(ArtMethod* method_handle, size_t pointer_size)
1019 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001020 const DexFile::CodeItem* code_item = method_handle->GetCodeItem();
1021 if (code_item == nullptr) {
1022 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -07001023 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001024 if (code_item->tries_size_ == 0) {
1025 return; // nothing to process
1026 }
1027 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
1028 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
1029 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1030 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
1031 bool has_catch_all = false;
1032 if (encoded_catch_handler_size <= 0) {
1033 encoded_catch_handler_size = -encoded_catch_handler_size;
1034 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001035 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001036 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
1037 uint16_t encoded_catch_handler_handlers_type_idx =
1038 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1039 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko05792b92015-08-03 11:56:49 +01001040 if (!method_handle->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx,
1041 pointer_size)) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001042 exceptions_to_resolve_.emplace(encoded_catch_handler_handlers_type_idx,
1043 method_handle->GetDexFile());
1044 }
1045 // ignore address associated with catch handler
1046 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1047 }
1048 if (has_catch_all) {
1049 // ignore catch all address
1050 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1051 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001052 }
1053 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001054
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001055 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve_;
1056};
1057
1058class RecordImageClassesVisitor : public ClassVisitor {
1059 public:
1060 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
1061 : image_classes_(image_classes) {}
1062
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001063 bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001064 std::string temp;
1065 image_classes_->insert(klass->GetDescriptor(&temp));
1066 return true;
1067 }
1068
1069 private:
1070 std::unordered_set<std::string>* const image_classes_;
1071};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001072
1073// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001074void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001075 CHECK(timings != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001076 if (!IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001077 return;
1078 }
1079
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001080 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001081 // Make a first class to load all classes explicitly listed in the file
1082 Thread* self = Thread::Current();
1083 ScopedObjectAccess soa(self);
1084 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001085 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001086 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001087 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001088 StackHandleScope<1> hs(self);
1089 Handle<mirror::Class> klass(
1090 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001091 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001092 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001093 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001094 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001095 } else {
1096 ++it;
1097 }
1098 }
1099
1100 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1101 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1102 // Do this here so that exception classes appear to have been specified image classes.
Ian Rogers700a4022014-05-19 16:49:03 -07001103 std::set<std::pair<uint16_t, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001104 StackHandleScope<1> hs(self);
1105 Handle<mirror::Class> java_lang_Throwable(
1106 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001107 do {
1108 unresolved_exception_types.clear();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001109 ResolveCatchBlockExceptionsClassVisitor visitor(unresolved_exception_types);
1110 class_linker->VisitClasses(&visitor);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001111 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
1112 uint16_t exception_type_idx = exception_type.first;
1113 const DexFile* dex_file = exception_type.second;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001114 StackHandleScope<2> hs2(self);
Mathieu Chartierf284d442016-06-02 11:48:30 -07001115 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file,
1116 nullptr)));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001117 Handle<mirror::Class> klass(hs2.NewHandle(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001118 class_linker->ResolveType(*dex_file,
1119 exception_type_idx,
1120 dex_cache,
1121 ScopedNullHandle<mirror::ClassLoader>())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001122 if (klass.Get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001123 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1124 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1125 LOG(FATAL) << "Failed to resolve class " << descriptor;
1126 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001127 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001128 }
1129 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1130 // more are found
1131 } while (!unresolved_exception_types.empty());
1132
1133 // We walk the roots looking for classes so that we'll pick up the
1134 // above classes plus any classes them depend on such super
1135 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001136 RecordImageClassesVisitor visitor(image_classes_.get());
1137 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001138
1139 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001140}
1141
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001142static void MaybeAddToImageClasses(Handle<mirror::Class> c,
1143 std::unordered_set<std::string>* image_classes)
Mathieu Chartier90443472015-07-16 20:32:27 -07001144 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001145 Thread* self = Thread::Current();
1146 StackHandleScope<1> hs(self);
1147 // Make a copy of the handle so that we don't clobber it doing Assign.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001148 MutableHandle<mirror::Class> klass(hs.NewHandle(c.Get()));
Ian Rogers1ff3c982014-08-12 02:30:58 -07001149 std::string temp;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001150 const size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001151 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001152 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001153 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1154 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001155 if (!result.second) { // Previously inserted.
1156 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001157 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001158 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Mathieu Chartierf8322842014-05-16 10:59:25 -07001159 for (size_t i = 0; i < klass->NumDirectInterfaces(); ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001160 StackHandleScope<1> hs2(self);
1161 MaybeAddToImageClasses(hs2.NewHandle(mirror::Class::GetDirectInterface(self, klass, i)),
Mathieu Chartierf8322842014-05-16 10:59:25 -07001162 image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001163 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001164 for (auto& m : c->GetVirtualMethods(pointer_size)) {
Alex Light36121492016-02-22 13:43:29 -08001165 StackHandleScope<1> hs2(self);
1166 MaybeAddToImageClasses(hs2.NewHandle(m.GetDeclaringClass()), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001167 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001168 if (klass->IsArrayClass()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001169 StackHandleScope<1> hs2(self);
1170 MaybeAddToImageClasses(hs2.NewHandle(klass->GetComponentType()), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001171 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001172 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001173 }
1174}
1175
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001176// Keeps all the data for the update together. Also doubles as the reference visitor.
1177// Note: we can use object pointers because we suspend all threads.
1178class ClinitImageUpdate {
1179 public:
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001180 static ClinitImageUpdate* Create(std::unordered_set<std::string>* image_class_descriptors,
1181 Thread* self, ClassLinker* linker, std::string* error_msg) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001182 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(image_class_descriptors, self,
1183 linker));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001184 if (res->dex_cache_class_ == nullptr) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001185 *error_msg = "Could not find DexCache class.";
1186 return nullptr;
1187 }
1188
1189 return res.release();
1190 }
1191
1192 ~ClinitImageUpdate() {
1193 // Allow others to suspend again.
1194 self_->EndAssertNoThreadSuspension(old_cause_);
1195 }
1196
1197 // Visitor for VisitReferences.
1198 void operator()(mirror::Object* object, MemberOffset field_offset, bool /* is_static */) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001199 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001200 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1201 if (ref != nullptr) {
1202 VisitClinitClassesObject(ref);
1203 }
1204 }
1205
1206 // java.lang.Reference visitor for VisitReferences.
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001207 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref ATTRIBUTE_UNUSED)
1208 const {}
1209
1210 // Ignore class native roots.
1211 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1212 const {}
1213 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001214
Mathieu Chartier90443472015-07-16 20:32:27 -07001215 void Walk() SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001216 // Use the initial classes as roots for a search.
1217 for (mirror::Class* klass_root : image_classes_) {
1218 VisitClinitClassesObject(klass_root);
1219 }
1220 }
1221
1222 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001223 class FindImageClassesVisitor : public ClassVisitor {
1224 public:
1225 explicit FindImageClassesVisitor(ClinitImageUpdate* data) : data_(data) {}
1226
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001227 bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001228 std::string temp;
1229 const char* name = klass->GetDescriptor(&temp);
1230 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
1231 data_->image_classes_.push_back(klass);
1232 } else {
1233 // Check whether it is initialized and has a clinit. They must be kept, too.
1234 if (klass->IsInitialized() && klass->FindClassInitializer(
1235 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
1236 data_->image_classes_.push_back(klass);
1237 }
1238 }
1239 return true;
1240 }
1241
1242 private:
1243 ClinitImageUpdate* const data_;
1244 };
1245
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001246 ClinitImageUpdate(std::unordered_set<std::string>* image_class_descriptors, Thread* self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001247 ClassLinker* linker)
Mathieu Chartier90443472015-07-16 20:32:27 -07001248 SHARED_REQUIRES(Locks::mutator_lock_) :
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001249 image_class_descriptors_(image_class_descriptors), self_(self) {
1250 CHECK(linker != nullptr);
1251 CHECK(image_class_descriptors != nullptr);
1252
1253 // Make sure nobody interferes with us.
1254 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1255
1256 // Find the interesting classes.
Andreas Gampedc8b63c2014-12-02 14:39:52 -08001257 dex_cache_class_ = linker->LookupClass(self, "Ljava/lang/DexCache;",
1258 ComputeModifiedUtf8Hash("Ljava/lang/DexCache;"), nullptr);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001259
1260 // Find all the already-marked classes.
1261 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001262 FindImageClassesVisitor visitor(this);
1263 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001264 }
1265
1266 void VisitClinitClassesObject(mirror::Object* object) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001267 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001268 DCHECK(object != nullptr);
1269 if (marked_objects_.find(object) != marked_objects_.end()) {
1270 // Already processed.
1271 return;
1272 }
1273
1274 // Mark it.
1275 marked_objects_.insert(object);
1276
1277 if (object->IsClass()) {
1278 // If it is a class, add it.
1279 StackHandleScope<1> hs(self_);
1280 MaybeAddToImageClasses(hs.NewHandle(object->AsClass()), image_class_descriptors_);
1281 } else {
1282 // Else visit the object's class.
1283 VisitClinitClassesObject(object->GetClass());
1284 }
1285
Mathieu Chartiere401d142015-04-22 13:56:20 -07001286 // If it is not a DexCache, visit all references.
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001287 mirror::Class* klass = object->GetClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001288 if (klass != dex_cache_class_) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001289 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001290 }
1291 }
1292
1293 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001294 std::unordered_set<std::string>* const image_class_descriptors_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001295 std::vector<mirror::Class*> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001296 const mirror::Class* dex_cache_class_;
1297 Thread* const self_;
1298 const char* old_cause_;
1299
1300 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1301};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001302
Ian Rogers3d504072014-03-01 09:16:49 -08001303void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001304 if (IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001305 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001306
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001307 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001308
1309 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001310 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001311
1312 std::string error_msg;
1313 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(image_classes_.get(),
1314 Thread::Current(),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001315 runtime->GetClassLinker(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001316 &error_msg));
1317 CHECK(update.get() != nullptr) << error_msg; // TODO: Soft failure?
1318
1319 // Do the marking.
1320 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001321 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001322}
1323
Vladimir Marko07785bb2015-06-15 18:52:54 +01001324bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1325 Runtime* runtime = Runtime::Current();
1326 if (!runtime->IsAotCompiler()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001327 DCHECK(runtime->UseJitCompilation());
Vladimir Marko07785bb2015-06-15 18:52:54 +01001328 // Having the klass reference here implies that the klass is already loaded.
1329 return true;
1330 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001331 if (!IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001332 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1333 // loaded because we don't even know what class loader will be used to load them.
1334 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1335 return class_in_image;
1336 }
1337 std::string temp;
1338 const char* descriptor = klass->GetDescriptor(&temp);
1339 return IsImageClass(descriptor);
1340}
1341
Vladimir Marko492a7fa2016-06-01 18:38:43 +01001342void CompilerDriver::MarkForDexToDexCompilation(Thread* self, const MethodReference& method_ref) {
1343 MutexLock lock(self, dex_to_dex_references_lock_);
1344 // Since we're compiling one dex file at a time, we need to look for the
1345 // current dex file entry only at the end of dex_to_dex_references_.
1346 if (dex_to_dex_references_.empty() ||
1347 &dex_to_dex_references_.back().GetDexFile() != method_ref.dex_file) {
1348 dex_to_dex_references_.emplace_back(*method_ref.dex_file);
1349 }
1350 dex_to_dex_references_.back().GetMethodIndexes().SetBit(method_ref.dex_method_index);
1351}
1352
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001353bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(Handle<mirror::DexCache> dex_cache,
1354 uint32_t type_idx) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001355 bool result = false;
1356 if ((IsBootImage() &&
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001357 IsImageClass(dex_cache->GetDexFile()->StringDataByIdx(
1358 dex_cache->GetDexFile()->GetTypeId(type_idx).descriptor_idx_))) ||
Calin Juravleffc87072016-04-20 14:22:09 +01001359 Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001360 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1361 result = (resolved_class != nullptr);
1362 }
1363
1364 if (result) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001365 stats_->TypeInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001366 } else {
1367 stats_->TypeNotInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001368 }
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001369 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001370}
1371
1372bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
1373 uint32_t string_idx) {
1374 // See also Compiler::ResolveDexFile
1375
1376 bool result = false;
Calin Juravleffc87072016-04-20 14:22:09 +01001377 if (IsBootImage() || Runtime::Current()->UseJitCompilation()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001378 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001379 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001380 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1381 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1382 soa.Self(), dex_file, false)));
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001383 if (IsBootImage()) {
1384 // We resolve all const-string strings when building for the image.
1385 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1386 result = true;
1387 } else {
1388 // Just check whether the dex cache already has the string.
Calin Juravleffc87072016-04-20 14:22:09 +01001389 DCHECK(Runtime::Current()->UseJitCompilation());
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001390 result = (dex_cache->GetResolvedString(string_idx) != nullptr);
1391 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001392 }
1393 if (result) {
1394 stats_->StringInDexCache();
1395 } else {
1396 stats_->StringNotInDexCache();
1397 }
1398 return result;
1399}
1400
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001401bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx,
1402 Handle<mirror::DexCache> dex_cache,
1403 uint32_t type_idx) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001404 // Get type from dex cache assuming it was populated by the verifier
1405 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001406 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001407 stats_->TypeNeedsAccessCheck();
1408 return false; // Unknown class needs access checks.
1409 }
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001410 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001411 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1412 if (!is_accessible) {
1413 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1414 if (referrer_class == nullptr) {
1415 stats_->TypeNeedsAccessCheck();
1416 return false; // Incomplete referrer knowledge needs access check.
1417 }
1418 // Perform access check, will return true if access is ok or false if we're going to have to
1419 // check this at runtime (for example for class loaders).
1420 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001421 }
David Brazdil38f64d32016-01-18 17:13:41 +00001422 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001423 stats_->TypeDoesntNeedAccessCheck();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001424 } else {
1425 stats_->TypeNeedsAccessCheck();
1426 }
David Brazdil38f64d32016-01-18 17:13:41 +00001427 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001428}
1429
1430bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001431 Handle<mirror::DexCache> dex_cache,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001432 uint32_t type_idx,
1433 bool* finalizable) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001434 // Get type from dex cache assuming it was populated by the verifier.
1435 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001436 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001437 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001438 // Be conservative.
1439 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001440 return false; // Unknown class needs access checks.
1441 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001442 *finalizable = resolved_class->IsFinalizable();
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001443 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001444 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1445 if (!is_accessible) {
1446 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1447 if (referrer_class == nullptr) {
1448 stats_->TypeNeedsAccessCheck();
1449 return false; // Incomplete referrer knowledge needs access check.
1450 }
1451 // Perform access and instantiable checks, will return true if access is ok or false if we're
1452 // going to have to check this at runtime (for example for class loaders).
1453 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001454 }
David Brazdil38f64d32016-01-18 17:13:41 +00001455 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001456 if (result) {
1457 stats_->TypeDoesntNeedAccessCheck();
1458 } else {
1459 stats_->TypeNeedsAccessCheck();
1460 }
1461 return result;
1462}
1463
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001464bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
1465 bool* is_type_initialized, bool* use_direct_type_ptr,
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001466 uintptr_t* direct_type_ptr, bool* out_is_finalizable) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001467 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001468 Runtime* runtime = Runtime::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001469 mirror::DexCache* dex_cache = runtime->GetClassLinker()->FindDexCache(
1470 soa.Self(), dex_file, false);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001471 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1472 if (resolved_class == nullptr) {
1473 return false;
1474 }
Igor Murashkind6dee672014-10-16 18:36:16 -07001475 if (GetCompilerOptions().GetCompilePic()) {
1476 // Do not allow a direct class pointer to be used when compiling for position-independent
1477 return false;
1478 }
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001479 *out_is_finalizable = resolved_class->IsFinalizable();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001480 gc::Heap* heap = runtime->GetHeap();
1481 const bool compiling_boot = heap->IsCompilingBoot();
Alex Light6e183f22014-07-18 14:57:04 -07001482 const bool support_boot_image_fixup = GetSupportBootImageFixup();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001483 if (compiling_boot) {
1484 // boot -> boot class pointers.
1485 // True if the class is in the image at boot compiling time.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001486 const bool is_image_class = IsBootImage() && IsImageClass(
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001487 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
1488 // True if pc relative load works.
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001489 if (is_image_class && support_boot_image_fixup) {
1490 *is_type_initialized = resolved_class->IsInitialized();
1491 *use_direct_type_ptr = false;
1492 *direct_type_ptr = 0;
1493 return true;
1494 } else {
1495 return false;
1496 }
Calin Juravleffc87072016-04-20 14:22:09 +01001497 } else if (runtime->UseJitCompilation() && !heap->IsMovableObject(resolved_class)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001498 *is_type_initialized = resolved_class->IsInitialized();
1499 // If the class may move around, then don't embed it as a direct pointer.
1500 *use_direct_type_ptr = true;
1501 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1502 return true;
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001503 } else {
1504 // True if the class is in the image at app compiling time.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001505 const bool class_in_image = heap->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
Alex Light6e183f22014-07-18 14:57:04 -07001506 if (class_in_image && support_boot_image_fixup) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001507 // boot -> app class pointers.
1508 *is_type_initialized = resolved_class->IsInitialized();
Alex Lighta59dd802014-07-02 16:28:08 -07001509 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1510 *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001511 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1512 return true;
1513 } else {
1514 // app -> app class pointers.
1515 // Give up because app does not have an image and class
1516 // isn't created at compile time. TODO: implement this
1517 // if/when each app gets an image.
1518 return false;
1519 }
1520 }
1521}
1522
Fred Shihe7f82e22014-08-06 10:46:37 -07001523bool CompilerDriver::CanEmbedReferenceTypeInCode(ClassReference* ref,
1524 bool* use_direct_ptr,
1525 uintptr_t* direct_type_ptr) {
1526 CHECK(ref != nullptr);
1527 CHECK(use_direct_ptr != nullptr);
1528 CHECK(direct_type_ptr != nullptr);
1529
1530 ScopedObjectAccess soa(Thread::Current());
1531 mirror::Class* reference_class = mirror::Reference::GetJavaLangRefReference();
Andreas Gampe928f72b2014-09-09 19:53:48 -07001532 bool is_initialized = false;
Fred Shihe7f82e22014-08-06 10:46:37 -07001533 bool unused_finalizable;
1534 // Make sure we have a finished Reference class object before attempting to use it.
1535 if (!CanEmbedTypeInCode(*reference_class->GetDexCache()->GetDexFile(),
1536 reference_class->GetDexTypeIndex(), &is_initialized,
1537 use_direct_ptr, direct_type_ptr, &unused_finalizable) ||
1538 !is_initialized) {
1539 return false;
1540 }
1541 ref->first = &reference_class->GetDexFile();
1542 ref->second = reference_class->GetDexClassDefIndex();
1543 return true;
1544}
1545
1546uint32_t CompilerDriver::GetReferenceSlowFlagOffset() const {
1547 ScopedObjectAccess soa(Thread::Current());
1548 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1549 DCHECK(klass->IsInitialized());
1550 return klass->GetSlowPathFlagOffset().Uint32Value();
1551}
1552
1553uint32_t CompilerDriver::GetReferenceDisableFlagOffset() const {
1554 ScopedObjectAccess soa(Thread::Current());
1555 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1556 DCHECK(klass->IsInitialized());
1557 return klass->GetDisableIntrinsicFlagOffset().Uint32Value();
1558}
1559
Vladimir Marko20f85592015-03-19 10:07:02 +00001560DexCacheArraysLayout CompilerDriver::GetDexCacheArraysLayout(const DexFile* dex_file) {
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001561 return ContainsElement(GetDexFilesForOatFile(), dex_file)
Mathieu Chartierc7853442015-03-27 14:35:38 -07001562 ? DexCacheArraysLayout(GetInstructionSetPointerSize(instruction_set_), dex_file)
Vladimir Marko20f85592015-03-19 10:07:02 +00001563 : DexCacheArraysLayout();
1564}
1565
Vladimir Markobe0e5462014-02-26 11:24:15 +00001566void CompilerDriver::ProcessedInstanceField(bool resolved) {
1567 if (!resolved) {
1568 stats_->UnresolvedInstanceField();
1569 } else {
1570 stats_->ResolvedInstanceField();
1571 }
1572}
1573
1574void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1575 if (!resolved) {
1576 stats_->UnresolvedStaticField();
1577 } else if (local) {
1578 stats_->ResolvedLocalStaticField();
1579 } else {
1580 stats_->ResolvedStaticField();
1581 }
1582}
1583
Vladimir Markof096aad2014-01-23 15:51:58 +00001584void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
1585 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001586}
1587
Mathieu Chartierc7853442015-03-27 14:35:38 -07001588ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1589 const DexCompilationUnit* mUnit, bool is_put,
1590 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001591 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001592 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001593 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001594 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001595 {
Mathieu Chartier736b5602015-09-02 14:54:11 -07001596 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001597 Handle<mirror::ClassLoader> class_loader_handle(
1598 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartier736b5602015-09-02 14:54:11 -07001599 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001600 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001601 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001602 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001603 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001604 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001605 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001606 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001607 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001608 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001609 ProcessedInstanceField(can_link);
1610 return can_link ? resolved_field : nullptr;
1611}
1612
1613bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1614 bool is_put, MemberOffset* field_offset,
1615 bool* is_volatile) {
1616 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001617 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001618
Mathieu Chartierc7853442015-03-27 14:35:38 -07001619 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001620 // Conservative defaults.
1621 *is_volatile = true;
1622 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001623 return false;
1624 } else {
1625 *is_volatile = resolved_field->IsVolatile();
1626 *field_offset = resolved_field->GetOffset();
1627 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001628 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001629}
1630
Ian Rogers83883d72013-10-21 21:07:24 -07001631void CompilerDriver::GetCodeAndMethodForDirectCall(InvokeType* type, InvokeType sharp_type,
1632 bool no_guarantee_of_dex_cache_entry,
Igor Murashkind6dee672014-10-16 18:36:16 -07001633 const mirror::Class* referrer_class,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001634 ArtMethod* method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001635 int* stats_flags,
Ian Rogers83883d72013-10-21 21:07:24 -07001636 MethodReference* target_method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001637 uintptr_t* direct_code,
1638 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001639 // For direct and static methods compute possible direct_code and direct_method values, ie
1640 // an address for the Method* being invoked and an address of the code for that Method*.
1641 // For interface calls compute a value for direct_method that is the interface method being
1642 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001643 *direct_code = 0;
1644 *direct_method = 0;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001645 Runtime* const runtime = Runtime::Current();
1646 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001647 auto* cl = runtime->GetClassLinker();
1648 const auto pointer_size = cl->GetImagePointerSize();
Igor Murashkind6dee672014-10-16 18:36:16 -07001649 bool use_dex_cache = GetCompilerOptions().GetCompilePic(); // Off by default
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001650 const bool compiling_boot = heap->IsCompilingBoot();
Alex Lighta59dd802014-07-02 16:28:08 -07001651 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1652 const bool force_relocations = (compiling_boot ||
1653 GetCompilerOptions().GetIncludePatchInformation());
Elliott Hughes956af0f2014-12-11 14:34:28 -08001654 if (sharp_type != kStatic && sharp_type != kDirect) {
1655 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001656 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001657 // TODO: support patching on all architectures.
1658 use_dex_cache = use_dex_cache || (force_relocations && !support_boot_image_fixup_);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001659 mirror::Class* declaring_class = method->GetDeclaringClass();
1660 bool method_code_in_boot = declaring_class->GetClassLoader() == nullptr;
Ian Rogers83883d72013-10-21 21:07:24 -07001661 if (!use_dex_cache) {
1662 if (!method_code_in_boot) {
1663 use_dex_cache = true;
1664 } else {
Brian Carlstrom14247b62015-01-31 21:35:32 -08001665 bool has_clinit_trampoline =
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001666 method->IsStatic() && !declaring_class->IsInitialized();
1667 if (has_clinit_trampoline && declaring_class != referrer_class) {
Ian Rogers83883d72013-10-21 21:07:24 -07001668 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1669 // class.
1670 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001671 }
1672 }
Ian Rogers83883d72013-10-21 21:07:24 -07001673 }
Calin Juravleffc87072016-04-20 14:22:09 +01001674 if (runtime->UseJitCompilation()) {
Mathieu Chartier28a35882015-02-26 18:28:07 -08001675 // If we are the JIT, then don't allow a direct call to the interpreter bridge since this will
1676 // never be updated even after we compile the method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001677 if (cl->IsQuickToInterpreterBridge(
Mathieu Chartier28a35882015-02-26 18:28:07 -08001678 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)))) {
1679 use_dex_cache = true;
1680 }
1681 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001682 if (method_code_in_boot) {
1683 *stats_flags |= kFlagDirectCallToBoot | kFlagDirectMethodToBoot;
Ian Rogers83883d72013-10-21 21:07:24 -07001684 }
Alex Lighta59dd802014-07-02 16:28:08 -07001685 if (!use_dex_cache && force_relocations) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001686 bool is_in_image;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001687 if (IsBootImage()) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001688 is_in_image = IsImageClass(method->GetDeclaringClassDescriptor());
1689 } else {
1690 is_in_image = instruction_set_ != kX86 && instruction_set_ != kX86_64 &&
Vladimir Markoc08ab292015-06-22 14:35:42 +01001691 heap->FindSpaceFromObject(method->GetDeclaringClass(), false)->IsImageSpace() &&
1692 !cl->IsQuickToInterpreterBridge(
1693 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)));
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001694 }
1695 if (!is_in_image) {
Ian Rogers83883d72013-10-21 21:07:24 -07001696 // We can only branch directly to Methods that are resolved in the DexCache.
1697 // Otherwise we won't invoke the resolution trampoline.
1698 use_dex_cache = true;
1699 }
1700 }
1701 // The method is defined not within this dex file. We need a dex cache slot within the current
1702 // dex file or direct pointers.
1703 bool must_use_direct_pointers = false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001704 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
1705 if (target_method->dex_file == dex_cache->GetDexFile() &&
Calin Juravleffc87072016-04-20 14:22:09 +01001706 !(runtime->UseJitCompilation() && dex_cache->GetResolvedMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001707 method->GetDexMethodIndex(), pointer_size) == nullptr)) {
Ian Rogers83883d72013-10-21 21:07:24 -07001708 target_method->dex_method_index = method->GetDexMethodIndex();
1709 } else {
Ian Rogers83883d72013-10-21 21:07:24 -07001710 if (no_guarantee_of_dex_cache_entry) {
1711 // See if the method is also declared in this dex cache.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001712 uint32_t dex_method_idx = method->FindDexMethodIndexInOtherDexFile(
1713 *target_method->dex_file, target_method->dex_method_index);
Ian Rogers83883d72013-10-21 21:07:24 -07001714 if (dex_method_idx != DexFile::kDexNoIndex) {
1715 target_method->dex_method_index = dex_method_idx;
1716 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001717 if (force_relocations && !use_dex_cache) {
Jeff Hao49161ce2014-03-12 11:05:25 -07001718 target_method->dex_method_index = method->GetDexMethodIndex();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001719 target_method->dex_file = dex_cache->GetDexFile();
Jeff Hao49161ce2014-03-12 11:05:25 -07001720 }
Ian Rogers83883d72013-10-21 21:07:24 -07001721 must_use_direct_pointers = true;
1722 }
1723 }
1724 }
1725 if (use_dex_cache) {
1726 if (must_use_direct_pointers) {
1727 // Fail. Test above showed the only safe dispatch was via the dex cache, however, the direct
1728 // pointers are required as the dex cache lacks an appropriate entry.
1729 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1730 } else {
1731 *type = sharp_type;
1732 }
1733 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001734 bool method_in_image = false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001735 const std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
1736 for (gc::space::ImageSpace* image_space : image_spaces) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001737 const auto& method_section = image_space->GetImageHeader().GetMethodsSection();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001738 if (method_section.Contains(reinterpret_cast<uint8_t*>(method) - image_space->Begin())) {
1739 method_in_image = true;
1740 break;
1741 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001742 }
Calin Juravleffc87072016-04-20 14:22:09 +01001743 if (method_in_image || compiling_boot || runtime->UseJitCompilation()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001744 // 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 -08001745 // In the case where we are the JIT, we can always use direct pointers since we know where
1746 // the method and its code are / will be. We don't sharpen to interpreter bridge since we
1747 // check IsQuickToInterpreterBridge above.
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001748 CHECK(!method->IsAbstract());
Ian Rogers83883d72013-10-21 21:07:24 -07001749 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001750 *direct_method = force_relocations ? -1 : reinterpret_cast<uintptr_t>(method);
1751 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Brian Carlstrom14247b62015-01-31 21:35:32 -08001752 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001753 target_method->dex_method_index = method->GetDexMethodIndex();
1754 } else if (!must_use_direct_pointers) {
1755 // Set the code and rely on the dex cache for the method.
1756 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001757 if (force_relocations) {
1758 *direct_code = -1;
Brian Carlstrom14247b62015-01-31 21:35:32 -08001759 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Alex Lighta59dd802014-07-02 16:28:08 -07001760 target_method->dex_method_index = method->GetDexMethodIndex();
1761 } else {
1762 *direct_code = compiler_->GetEntryPointOf(method);
1763 }
Ian Rogers83883d72013-10-21 21:07:24 -07001764 } else {
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001765 // Direct pointers were required but none were available.
1766 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001767 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001768 }
1769}
1770
1771bool CompilerDriver::ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001772 bool update_stats, bool enable_devirtualization,
1773 InvokeType* invoke_type, MethodReference* target_method,
1774 int* vtable_idx, uintptr_t* direct_code,
1775 uintptr_t* direct_method) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001776 InvokeType orig_invoke_type = *invoke_type;
1777 int stats_flags = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001778 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof096aad2014-01-23 15:51:58 +00001779 // Try to resolve the method and compiling method's class.
Mathieu Chartier736b5602015-09-02 14:54:11 -07001780 StackHandleScope<2> hs(soa.Self());
1781 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001782 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1783 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001784 uint32_t method_idx = target_method->dex_method_index;
1785 ArtMethod* resolved_method = ResolveMethod(
1786 soa, dex_cache, class_loader, mUnit, method_idx, orig_invoke_type);
1787 auto h_referrer_class = hs.NewHandle(resolved_method != nullptr ?
1788 ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr);
Vladimir Markof096aad2014-01-23 15:51:58 +00001789 bool result = false;
1790 if (resolved_method != nullptr) {
1791 *vtable_idx = GetResolvedMethodVTableIndex(resolved_method, orig_invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001792
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001793 if (enable_devirtualization && mUnit->GetVerifiedMethod() != nullptr) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001794 const MethodReference* devirt_target = mUnit->GetVerifiedMethod()->GetDevirtTarget(dex_pc);
1795
1796 stats_flags = IsFastInvoke(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001797 soa, dex_cache, class_loader, mUnit, h_referrer_class.Get(), resolved_method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001798 invoke_type, target_method, devirt_target, direct_code, direct_method);
1799 result = stats_flags != 0;
1800 } else {
1801 // Devirtualization not enabled. Inline IsFastInvoke(), dropping the devirtualization parts.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001802 if (UNLIKELY(h_referrer_class.Get() == nullptr) ||
1803 UNLIKELY(!h_referrer_class->CanAccessResolvedMethod(resolved_method->GetDeclaringClass(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001804 resolved_method, dex_cache.Get(),
Vladimir Markof096aad2014-01-23 15:51:58 +00001805 target_method->dex_method_index)) ||
1806 *invoke_type == kSuper) {
1807 // Slow path. (Without devirtualization, all super calls go slow path as well.)
1808 } else {
1809 // Sharpening failed so generate a regular resolved method dispatch.
1810 stats_flags = kFlagMethodResolved;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001811 GetCodeAndMethodForDirectCall(
1812 invoke_type, *invoke_type, false, h_referrer_class.Get(), resolved_method, &stats_flags,
1813 target_method, direct_code, direct_method);
Vladimir Markof096aad2014-01-23 15:51:58 +00001814 result = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001815 }
1816 }
1817 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001818 if (!result) {
1819 // Conservative defaults.
1820 *vtable_idx = -1;
1821 *direct_code = 0u;
1822 *direct_method = 0u;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001823 }
1824 if (update_stats) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001825 ProcessedInvoke(orig_invoke_type, stats_flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001826 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001827 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001828}
1829
Vladimir Marko2730db02014-01-27 11:15:17 +00001830const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1831 uint32_t method_idx) const {
1832 MethodReference ref(dex_file, method_idx);
1833 return verification_results_->GetVerifiedMethod(ref);
1834}
1835
1836bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001837 if (!compiler_options_->IsVerificationEnabled()) {
1838 // If we didn't verify, every cast has to be treated as non-safe.
1839 return false;
1840 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001841 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1842 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001843 if (result) {
1844 stats_->SafeCast();
1845 } else {
1846 stats_->NotASafeCast();
1847 }
1848 return result;
1849}
1850
Mathieu Chartier90443472015-07-16 20:32:27 -07001851class CompilationVisitor {
1852 public:
1853 virtual ~CompilationVisitor() {}
1854 virtual void Visit(size_t index) = 0;
1855};
1856
Brian Carlstrom7940e442013-07-12 13:46:57 -07001857class ParallelCompilationManager {
1858 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001859 ParallelCompilationManager(ClassLinker* class_linker,
1860 jobject class_loader,
1861 CompilerDriver* compiler,
1862 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001863 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001864 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001865 : index_(0),
1866 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001867 class_loader_(class_loader),
1868 compiler_(compiler),
1869 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001870 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001871 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001872
1873 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001874 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001875 return class_linker_;
1876 }
1877
1878 jobject GetClassLoader() const {
1879 return class_loader_;
1880 }
1881
1882 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001883 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001884 return compiler_;
1885 }
1886
1887 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001888 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001889 return dex_file_;
1890 }
1891
Andreas Gampede7b4362014-07-28 18:38:57 -07001892 const std::vector<const DexFile*>& GetDexFiles() const {
1893 return dex_files_;
1894 }
1895
Mathieu Chartier90443472015-07-16 20:32:27 -07001896 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1897 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001898 Thread* self = Thread::Current();
1899 self->AssertNoPendingException();
1900 CHECK_GT(work_units, 0U);
1901
Ian Rogers3e5cf302014-05-20 16:40:37 -07001902 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001903 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001904 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001905 }
1906 thread_pool_->StartWorkers(self);
1907
1908 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1909 // thread destructor's called below perform join).
1910 CHECK_NE(self->GetState(), kRunnable);
1911
1912 // Wait for all the worker threads to finish.
1913 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001914
1915 // And stop the workers accepting jobs.
1916 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001917 }
1918
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001919 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001920 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001921 }
1922
Brian Carlstrom7940e442013-07-12 13:46:57 -07001923 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001924 class ForAllClosure : public Task {
1925 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001926 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001927 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001928 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001929 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001930
1931 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001932 while (true) {
1933 const size_t index = manager_->NextIndex();
1934 if (UNLIKELY(index >= end_)) {
1935 break;
1936 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001937 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001938 self->AssertNoPendingException();
1939 }
1940 }
1941
1942 virtual void Finalize() {
1943 delete this;
1944 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001945
Brian Carlstrom7940e442013-07-12 13:46:57 -07001946 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001947 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001948 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001949 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001950 };
1951
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001952 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001953 ClassLinker* const class_linker_;
1954 const jobject class_loader_;
1955 CompilerDriver* const compiler_;
1956 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001957 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001958 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001959
1960 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001961};
1962
Jeff Hao0e49b422013-11-08 12:16:56 -08001963// A fast version of SkipClass above if the class pointer is available
1964// that avoids the expensive FindInClassPath search.
1965static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
Mathieu Chartier90443472015-07-16 20:32:27 -07001966 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001967 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001968 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1969 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001970 if (class_loader == nullptr) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001971 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1972 << dex_file.GetLocation() << " previously found in "
1973 << original_dex_file.GetLocation();
1974 }
1975 return true;
1976 }
1977 return false;
1978}
1979
Mathieu Chartier70b63482014-06-27 17:19:04 -07001980static void CheckAndClearResolveException(Thread* self)
Mathieu Chartier90443472015-07-16 20:32:27 -07001981 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07001982 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001983 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001984 std::string temp;
1985 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1986 const char* expected_exceptions[] = {
1987 "Ljava/lang/IllegalAccessError;",
1988 "Ljava/lang/IncompatibleClassChangeError;",
1989 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001990 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07001991 "Ljava/lang/NoClassDefFoundError;",
1992 "Ljava/lang/NoSuchFieldError;",
1993 "Ljava/lang/NoSuchMethodError;"
1994 };
1995 bool found = false;
1996 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1997 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1998 found = true;
1999 }
2000 }
2001 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07002002 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07002003 }
2004 self->ClearException();
2005}
2006
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002007bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file,
2008 uint16_t class_def_idx) const {
2009 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2010 const uint8_t* class_data = dex_file.GetClassData(class_def);
2011 if (class_data == nullptr) {
2012 // Empty class such as a marker interface.
2013 return false;
2014 }
2015 ClassDataItemIterator it(dex_file, class_data);
2016 while (it.HasNextStaticField()) {
2017 it.Next();
2018 }
2019 // We require a constructor barrier if there are final instance fields.
2020 while (it.HasNextInstanceField()) {
2021 if (it.MemberIsFinal()) {
2022 return true;
2023 }
2024 it.Next();
2025 }
2026 return false;
2027}
2028
Mathieu Chartier90443472015-07-16 20:32:27 -07002029class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
2030 public:
2031 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
2032 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002033
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002034 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002035 ATRACE_CALL();
2036 Thread* const self = Thread::Current();
2037 jobject jclass_loader = manager_->GetClassLoader();
2038 const DexFile& dex_file = *manager_->GetDexFile();
2039 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002040
Mathieu Chartier90443472015-07-16 20:32:27 -07002041 // If an instance field is final then we need to have a barrier on the return, static final
2042 // fields are assigned within the lock held for class initialization. Conservatively assume
2043 // constructor barriers are always required.
2044 bool requires_constructor_barrier = true;
2045
2046 // Method and Field are the worst. We can't resolve without either
2047 // context from the code use (to disambiguate virtual vs direct
2048 // method and instance vs static field) or from class
2049 // definitions. While the compiler will resolve what it can as it
2050 // needs it, here we try to resolve fields and methods used in class
2051 // definitions, since many of them many never be referenced by
2052 // generated code.
2053 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2054 ScopedObjectAccess soa(self);
2055 StackHandleScope<2> hs(soa.Self());
2056 Handle<mirror::ClassLoader> class_loader(
2057 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002058 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2059 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002060 // Resolve the class.
2061 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
2062 class_loader);
2063 bool resolve_fields_and_methods;
2064 if (klass == nullptr) {
2065 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
2066 // attempt to resolve methods and fields when there is no declaring class.
2067 CheckAndClearResolveException(soa.Self());
2068 resolve_fields_and_methods = false;
2069 } else {
2070 // We successfully resolved a class, should we skip it?
2071 if (SkipClass(jclass_loader, dex_file, klass)) {
2072 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002073 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002074 // We want to resolve the methods and fields eagerly.
2075 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07002076 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002077 // Note the class_data pointer advances through the headers,
2078 // static fields, instance fields, direct methods, and virtual
2079 // methods.
2080 const uint8_t* class_data = dex_file.GetClassData(class_def);
2081 if (class_data == nullptr) {
2082 // Empty class such as a marker interface.
2083 requires_constructor_barrier = false;
2084 } else {
2085 ClassDataItemIterator it(dex_file, class_data);
2086 while (it.HasNextStaticField()) {
2087 if (resolve_fields_and_methods) {
2088 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2089 dex_cache, class_loader, true);
2090 if (field == nullptr) {
2091 CheckAndClearResolveException(soa.Self());
2092 }
Ian Rogers68b56852014-08-29 20:19:11 -07002093 }
2094 it.Next();
2095 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002096 // We require a constructor barrier if there are final instance fields.
2097 requires_constructor_barrier = false;
2098 while (it.HasNextInstanceField()) {
2099 if (it.MemberIsFinal()) {
2100 requires_constructor_barrier = true;
2101 }
2102 if (resolve_fields_and_methods) {
2103 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2104 dex_cache, class_loader, false);
2105 if (field == nullptr) {
2106 CheckAndClearResolveException(soa.Self());
2107 }
Ian Rogers68b56852014-08-29 20:19:11 -07002108 }
2109 it.Next();
2110 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002111 if (resolve_fields_and_methods) {
2112 while (it.HasNextDirectMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002113 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002114 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2115 it.GetMethodInvokeType(class_def));
2116 if (method == nullptr) {
2117 CheckAndClearResolveException(soa.Self());
2118 }
2119 it.Next();
2120 }
2121 while (it.HasNextVirtualMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002122 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002123 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2124 it.GetMethodInvokeType(class_def));
2125 if (method == nullptr) {
2126 CheckAndClearResolveException(soa.Self());
2127 }
2128 it.Next();
2129 }
2130 DCHECK(!it.HasNext());
2131 }
2132 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002133 manager_->GetCompiler()->SetRequiresConstructorBarrier(self,
2134 &dex_file,
2135 class_def_index,
2136 requires_constructor_barrier);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002137 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002138
Mathieu Chartier90443472015-07-16 20:32:27 -07002139 private:
2140 const ParallelCompilationManager* const manager_;
2141};
2142
2143class ResolveTypeVisitor : public CompilationVisitor {
2144 public:
2145 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
2146 }
2147 virtual void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002148 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07002149 ScopedObjectAccess soa(Thread::Current());
2150 ClassLinker* class_linker = manager_->GetClassLinker();
2151 const DexFile& dex_file = *manager_->GetDexFile();
2152 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07002153 Handle<mirror::ClassLoader> class_loader(
2154 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002155 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
2156 dex_file,
Mathieu Chartierf284d442016-06-02 11:48:30 -07002157 class_loader.Get())));
Mathieu Chartier90443472015-07-16 20:32:27 -07002158 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002159
Mathieu Chartier90443472015-07-16 20:32:27 -07002160 if (klass == nullptr) {
2161 soa.Self()->AssertPendingException();
2162 mirror::Throwable* exception = soa.Self()->GetException();
2163 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
2164 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
2165 // There's little point continuing compilation if the heap is exhausted.
2166 LOG(FATAL) << "Out of memory during type resolution for compilation";
2167 }
2168 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07002169 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002170 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002171
2172 private:
2173 const ParallelCompilationManager* const manager_;
2174};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002175
Andreas Gampeace0dc12016-01-20 13:33:13 -08002176void CompilerDriver::ResolveDexFile(jobject class_loader,
2177 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002178 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002179 ThreadPool* thread_pool,
2180 size_t thread_count,
2181 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002182 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2183
2184 // TODO: we could resolve strings here, although the string table is largely filled with class
2185 // and method names.
2186
Andreas Gampede7b4362014-07-28 18:38:57 -07002187 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2188 thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002189 if (IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002190 // For images we resolve all types, such as array, whereas for applications just those with
2191 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002192 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002193 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002194 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002195 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002196
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002197 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002198 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002199 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002200}
2201
Andreas Gampeace0dc12016-01-20 13:33:13 -08002202void CompilerDriver::SetVerified(jobject class_loader,
2203 const std::vector<const DexFile*>& dex_files,
2204 TimingLogger* timings) {
2205 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07002206 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002207 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002208 SetVerifiedDexFile(class_loader,
2209 *dex_file,
2210 dex_files,
2211 parallel_thread_pool_.get(),
2212 parallel_thread_count_,
2213 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002214 }
2215}
2216
Andreas Gampeace0dc12016-01-20 13:33:13 -08002217void CompilerDriver::Verify(jobject class_loader,
2218 const std::vector<const DexFile*>& dex_files,
2219 TimingLogger* timings) {
2220 // Note: verification should not be pulling in classes anymore when compiling the boot image,
2221 // as all should have been resolved before. As such, doing this in parallel should still
2222 // be deterministic.
Mathieu Chartier90443472015-07-16 20:32:27 -07002223 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002224 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002225 VerifyDexFile(class_loader,
2226 *dex_file,
2227 dex_files,
2228 parallel_thread_pool_.get(),
2229 parallel_thread_count_,
2230 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002231 }
2232}
2233
Mathieu Chartier90443472015-07-16 20:32:27 -07002234class VerifyClassVisitor : public CompilationVisitor {
2235 public:
Andreas Gampe7fe30232016-03-25 16:58:00 -07002236 VerifyClassVisitor(const ParallelCompilationManager* manager, LogSeverity log_level)
2237 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002238
Mathieu Chartier90443472015-07-16 20:32:27 -07002239 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2240 ATRACE_CALL();
2241 ScopedObjectAccess soa(Thread::Current());
2242 const DexFile& dex_file = *manager_->GetDexFile();
Mathieu Chartiera8077802016-03-16 19:08:31 -07002243 if (!manager_->GetCompiler()->ShouldVerifyClassBasedOnProfile(dex_file, class_def_index)) {
2244 // Skip verification since the class is not in the profile.
2245 return;
2246 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002247 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2248 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2249 ClassLinker* class_linker = manager_->GetClassLinker();
2250 jobject jclass_loader = manager_->GetClassLoader();
2251 StackHandleScope<3> hs(soa.Self());
2252 Handle<mirror::ClassLoader> class_loader(
2253 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2254 Handle<mirror::Class> klass(
2255 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2256 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002257 CHECK(soa.Self()->IsExceptionPending());
2258 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07002259
2260 /*
2261 * At compile time, we can still structurally verify the class even if FindClass fails.
2262 * This is to ensure the class is structurally sound for compilation. An unsound class
2263 * will be rejected by the verifier and later skipped during compilation in the compiler.
2264 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002265 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2266 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002267 std::string error_msg;
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002268 if (verifier::MethodVerifier::VerifyClass(soa.Self(),
2269 &dex_file,
2270 dex_cache,
2271 class_loader,
2272 &class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08002273 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002274 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07002275 log_level_,
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002276 &error_msg) ==
Mathieu Chartier90443472015-07-16 20:32:27 -07002277 verifier::MethodVerifier::kHardFailure) {
2278 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2279 << " because: " << error_msg;
2280 manager_->GetCompiler()->SetHadHardVerifierFailure();
2281 }
2282 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
2283 CHECK(klass->IsResolved()) << PrettyClass(klass.Get());
Andreas Gampe7fe30232016-03-25 16:58:00 -07002284 class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002285
2286 if (klass->IsErroneous()) {
2287 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2288 CHECK(soa.Self()->IsExceptionPending());
2289 soa.Self()->ClearException();
2290 manager_->GetCompiler()->SetHadHardVerifierFailure();
2291 }
2292
2293 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
2294 << PrettyDescriptor(klass.Get()) << ": state=" << klass->GetStatus();
2295
2296 // It is *very* problematic if there are verification errors in the boot classpath. For example,
2297 // we rely on things working OK without verification when the decryption dialog is brought up.
2298 // So abort in a debug build if we find this violated.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002299 DCHECK(!manager_->GetCompiler()->IsBootImage() || klass->IsVerified())
2300 << "Boot classpath class " << PrettyClass(klass.Get()) << " failed to fully verify.";
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002301 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002302 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002303 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002304
2305 private:
2306 const ParallelCompilationManager* const manager_;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002307 const LogSeverity log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002308};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002309
Andreas Gampeace0dc12016-01-20 13:33:13 -08002310void CompilerDriver::VerifyDexFile(jobject class_loader,
2311 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002312 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002313 ThreadPool* thread_pool,
2314 size_t thread_count,
2315 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002316 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002317 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002318 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2319 thread_pool);
Andreas Gampe7fe30232016-03-25 16:58:00 -07002320 LogSeverity log_level = GetCompilerOptions().AbortOnHardVerifierFailure()
2321 ? LogSeverity::INTERNAL_FATAL
2322 : LogSeverity::WARNING;
2323 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002324 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002325}
2326
Mathieu Chartier90443472015-07-16 20:32:27 -07002327class SetVerifiedClassVisitor : public CompilationVisitor {
2328 public:
2329 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2330
2331 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2332 ATRACE_CALL();
2333 ScopedObjectAccess soa(Thread::Current());
2334 const DexFile& dex_file = *manager_->GetDexFile();
2335 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2336 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2337 ClassLinker* class_linker = manager_->GetClassLinker();
2338 jobject jclass_loader = manager_->GetClassLoader();
2339 StackHandleScope<3> hs(soa.Self());
2340 Handle<mirror::ClassLoader> class_loader(
2341 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2342 Handle<mirror::Class> klass(
2343 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2344 // Class might have failed resolution. Then don't set it to verified.
2345 if (klass.Get() != nullptr) {
2346 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2347 // very wrong.
2348 if (klass->IsResolved()) {
2349 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
2350 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2351 // Set class status to verified.
2352 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self());
2353 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2354 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002355 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002356 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002357 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002358 }
2359 // Record the final class status if necessary.
2360 ClassReference ref(manager_->GetDexFile(), class_def_index);
2361 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002362 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002363 } else {
2364 Thread* self = soa.Self();
2365 DCHECK(self->IsExceptionPending());
2366 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002367 }
2368 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002369
2370 private:
2371 const ParallelCompilationManager* const manager_;
2372};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002373
Andreas Gampeace0dc12016-01-20 13:33:13 -08002374void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2375 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002376 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002377 ThreadPool* thread_pool,
2378 size_t thread_count,
2379 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002380 TimingLogger::ScopedTiming t("Verify Dex File", timings);
2381 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2382 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2383 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002384 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002385 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002386}
2387
Mathieu Chartier90443472015-07-16 20:32:27 -07002388class InitializeClassVisitor : public CompilationVisitor {
2389 public:
2390 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002391
Mathieu Chartier90443472015-07-16 20:32:27 -07002392 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2393 ATRACE_CALL();
2394 jobject jclass_loader = manager_->GetClassLoader();
2395 const DexFile& dex_file = *manager_->GetDexFile();
2396 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2397 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2398 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002399
Mathieu Chartier90443472015-07-16 20:32:27 -07002400 ScopedObjectAccess soa(Thread::Current());
2401 StackHandleScope<3> hs(soa.Self());
2402 Handle<mirror::ClassLoader> class_loader(
2403 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2404 Handle<mirror::Class> klass(
2405 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2406
2407 if (klass.Get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) {
2408 // Only try to initialize classes that were successfully verified.
2409 if (klass->IsVerified()) {
2410 // Attempt to initialize the class but bail if we either need to initialize the super-class
2411 // or static fields.
2412 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002413 if (!klass->IsInitialized()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002414 // We don't want non-trivial class initialization occurring on multiple threads due to
2415 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2416 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2417 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2418 // after first initializing its parents, whose locks are acquired. This leads to a
2419 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2420 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2421 // than use a special Object for the purpose we use the Class of java.lang.Class.
2422 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2423 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2424 // Attempt to initialize allowing initialization of parent classes but still not static
2425 // fields.
2426 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
2427 if (!klass->IsInitialized()) {
2428 // We need to initialize static fields, we only do this for image classes that aren't
2429 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002430 bool can_init_static_fields = manager_->GetCompiler()->IsBootImage() &&
Mathieu Chartier90443472015-07-16 20:32:27 -07002431 manager_->GetCompiler()->IsImageClass(descriptor) &&
2432 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2433 if (can_init_static_fields) {
2434 VLOG(compiler) << "Initializing: " << descriptor;
2435 // TODO multithreading support. We should ensure the current compilation thread has
2436 // exclusive access to the runtime and the transaction. To achieve this, we could use
2437 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2438 // checks in Thread::AssertThreadSuspensionIsAllowable.
2439 Runtime* const runtime = Runtime::Current();
2440 Transaction transaction;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002441
Mathieu Chartier90443472015-07-16 20:32:27 -07002442 // Run the class initializer in transaction mode.
2443 runtime->EnterTransactionMode(&transaction);
2444 const mirror::Class::Status old_status = klass->GetStatus();
2445 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2446 true);
2447 // TODO we detach transaction from runtime to indicate we quit the transactional
2448 // mode which prevents the GC from visiting objects modified during the transaction.
2449 // Ensure GC is not run so don't access freed objects when aborting transaction.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002450
Mathieu Chartier90443472015-07-16 20:32:27 -07002451 ScopedAssertNoThreadSuspension ants(soa.Self(), "Transaction end");
2452 runtime->ExitTransactionMode();
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002453
Mathieu Chartier90443472015-07-16 20:32:27 -07002454 if (!success) {
2455 CHECK(soa.Self()->IsExceptionPending());
2456 mirror::Throwable* exception = soa.Self()->GetException();
2457 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2458 << exception->Dump();
2459 std::ostream* file_log = manager_->GetCompiler()->
2460 GetCompilerOptions().GetInitFailureOutput();
2461 if (file_log != nullptr) {
2462 *file_log << descriptor << "\n";
2463 *file_log << exception->Dump() << "\n";
2464 }
2465 soa.Self()->ClearException();
2466 transaction.Rollback();
2467 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002468 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002469 }
2470 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002471 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002472 }
2473 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002474 // Record the final class status if necessary.
2475 ClassReference ref(manager_->GetDexFile(), class_def_index);
2476 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002477 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002478 // Clear any class not found or verification exceptions.
2479 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002480 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002481
2482 private:
2483 const ParallelCompilationManager* const manager_;
2484};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002485
Andreas Gampeace0dc12016-01-20 13:33:13 -08002486void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2487 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002488 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002489 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002490 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002491
2492 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2493 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2494 ThreadPool* init_thread_pool = force_determinism
2495 ? single_thread_pool_.get()
2496 : parallel_thread_pool_.get();
2497 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2498
Brian Carlstrom7940e442013-07-12 13:46:57 -07002499 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002500 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002501 init_thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002502 if (IsBootImage()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002503 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002504 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002505 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002506 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002507 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002508}
2509
Mathieu Chartier91288d82016-04-28 09:44:54 -07002510class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002511 public:
2512 virtual bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier91288d82016-04-28 09:44:54 -07002513 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2514 return true;
2515 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002516 if (klass->IsArrayClass()) {
2517 StackHandleScope<1> hs(Thread::Current());
2518 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(),
2519 hs.NewHandle(klass),
2520 true,
2521 true);
2522 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002523 // Create the conflict tables.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002524 FillIMTAndConflictTables(klass);
Nicolas Geoffray88f288e2016-06-29 08:17:52 +00002525 return true;
Nelli Kimbadee982016-05-13 13:08:53 +03002526 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002527
2528 private:
2529 void FillIMTAndConflictTables(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
2530 if (!klass->ShouldHaveImt()) {
2531 return;
2532 }
2533 if (visited_classes_.find(klass) != visited_classes_.end()) {
2534 return;
2535 }
2536 if (klass->HasSuperClass()) {
2537 FillIMTAndConflictTables(klass->GetSuperClass());
2538 }
2539 if (!klass->IsTemp()) {
2540 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
2541 }
2542 visited_classes_.insert(klass);
2543 }
2544
2545 std::set<mirror::Class*> visited_classes_;
Mathieu Chartier085a0722016-04-01 17:33:31 -07002546};
2547
Brian Carlstrom7940e442013-07-12 13:46:57 -07002548void CompilerDriver::InitializeClasses(jobject class_loader,
2549 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002550 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002551 for (size_t i = 0; i != dex_files.size(); ++i) {
2552 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002553 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002554 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002555 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002556 if (boot_image_ || app_image_) {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002557 // Make sure that we call EnsureIntiailized on all the array classes to call
2558 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2559 // changed at runtime resulting in more dirty image pages.
Mathieu Chartier91288d82016-04-28 09:44:54 -07002560 // Also create conflict tables.
2561 // Only useful if we are compiling an image (image_classes_ is not null).
Mathieu Chartier085a0722016-04-01 17:33:31 -07002562 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier91288d82016-04-28 09:44:54 -07002563 InitializeArrayClassesAndCreateConflictTablesVisitor visitor;
2564 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
Mathieu Chartier085a0722016-04-01 17:33:31 -07002565 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002566 if (IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002567 // Prune garbage objects created during aborted transactions.
2568 Runtime::Current()->GetHeap()->CollectGarbage(true);
2569 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002570}
2571
Andreas Gampeace0dc12016-01-20 13:33:13 -08002572void CompilerDriver::Compile(jobject class_loader,
2573 const std::vector<const DexFile*>& dex_files,
2574 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002575 if (kDebugProfileGuidedCompilation) {
2576 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2577 ((profile_compilation_info_ == nullptr)
2578 ? "null"
2579 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002580 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002581
2582 DCHECK(current_dex_to_dex_methods_ == nullptr);
2583 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002584 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002585 CompileDexFile(class_loader,
2586 *dex_file,
2587 dex_files,
2588 parallel_thread_pool_.get(),
2589 parallel_thread_count_,
2590 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002591 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2592 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2593 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002594 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002595 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002596
2597 ArrayRef<DexFileMethodSet> dex_to_dex_references;
2598 {
2599 // From this point on, we shall not modify dex_to_dex_references_, so
2600 // just grab a reference to it that we use without holding the mutex.
2601 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
2602 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
2603 }
2604 for (const auto& method_set : dex_to_dex_references) {
2605 current_dex_to_dex_methods_ = &method_set.GetMethodIndexes();
2606 CompileDexFile(class_loader,
2607 method_set.GetDexFile(),
2608 dex_files,
2609 parallel_thread_pool_.get(),
2610 parallel_thread_count_,
2611 timings);
2612 }
2613 current_dex_to_dex_methods_ = nullptr;
2614
Andreas Gampe8d295f82015-01-20 14:50:21 -08002615 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002616}
2617
Mathieu Chartier90443472015-07-16 20:32:27 -07002618class CompileClassVisitor : public CompilationVisitor {
2619 public:
2620 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2621
2622 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2623 ATRACE_CALL();
2624 const DexFile& dex_file = *manager_->GetDexFile();
2625 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2626 ClassLinker* class_linker = manager_->GetClassLinker();
2627 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002628 ClassReference ref(&dex_file, class_def_index);
2629 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2630 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002631 return;
2632 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002633 // Use a scoped object access to perform to the quick SkipClass check.
2634 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2635 ScopedObjectAccess soa(Thread::Current());
2636 StackHandleScope<3> hs(soa.Self());
2637 Handle<mirror::ClassLoader> class_loader(
2638 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2639 Handle<mirror::Class> klass(
2640 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2641 Handle<mirror::DexCache> dex_cache;
2642 if (klass.Get() == nullptr) {
2643 soa.Self()->AssertPendingException();
2644 soa.Self()->ClearException();
2645 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2646 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2647 return;
2648 } else {
2649 dex_cache = hs.NewHandle(klass->GetDexCache());
2650 }
2651
Mathieu Chartier90443472015-07-16 20:32:27 -07002652 const uint8_t* class_data = dex_file.GetClassData(class_def);
2653 if (class_data == nullptr) {
2654 // empty class, probably a marker interface
2655 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002656 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002657
Mathieu Chartier736b5602015-09-02 14:54:11 -07002658 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002659 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002660
Mathieu Chartier90443472015-07-16 20:32:27 -07002661 CompilerDriver* const driver = manager_->GetCompiler();
2662
2663 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002664 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002665 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002666
Mathieu Chartier90443472015-07-16 20:32:27 -07002667 ClassDataItemIterator it(dex_file, class_data);
2668 // Skip fields
2669 while (it.HasNextStaticField()) {
2670 it.Next();
2671 }
2672 while (it.HasNextInstanceField()) {
2673 it.Next();
2674 }
2675
2676 bool compilation_enabled = driver->IsClassToCompile(
2677 dex_file.StringByTypeIdx(class_def.class_idx_));
2678
2679 // Compile direct methods
2680 int64_t previous_direct_method_idx = -1;
2681 while (it.HasNextDirectMethod()) {
2682 uint32_t method_idx = it.GetMemberIndex();
2683 if (method_idx == previous_direct_method_idx) {
2684 // smali can create dex files with two encoded_methods sharing the same method_idx
2685 // http://code.google.com/p/smali/issues/detail?id=119
2686 it.Next();
2687 continue;
2688 }
2689 previous_direct_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002690 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002691 it.GetMethodInvokeType(class_def), class_def_index,
2692 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002693 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002694 it.Next();
2695 }
2696 // Compile virtual methods
2697 int64_t previous_virtual_method_idx = -1;
2698 while (it.HasNextVirtualMethod()) {
2699 uint32_t method_idx = it.GetMemberIndex();
2700 if (method_idx == previous_virtual_method_idx) {
2701 // smali can create dex files with two encoded_methods sharing the same method_idx
2702 // http://code.google.com/p/smali/issues/detail?id=119
2703 it.Next();
2704 continue;
2705 }
2706 previous_virtual_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002707 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002708 it.GetMethodInvokeType(class_def), class_def_index,
2709 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002710 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002711 it.Next();
2712 }
2713 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002714 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002715
2716 private:
2717 const ParallelCompilationManager* const manager_;
2718};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002719
Andreas Gampeace0dc12016-01-20 13:33:13 -08002720void CompilerDriver::CompileDexFile(jobject class_loader,
2721 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002722 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002723 ThreadPool* thread_pool,
2724 size_t thread_count,
2725 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002726 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002727 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002728 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002729 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002730 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002731}
2732
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002733void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2734 CompiledMethod* const compiled_method,
2735 size_t non_relative_linker_patch_count) {
2736 DCHECK(GetCompiledMethod(method_ref) == nullptr)
2737 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
2738 {
2739 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2740 compiled_methods_.Put(method_ref, compiled_method);
2741 non_relative_linker_patch_count_ += non_relative_linker_patch_count;
Ian Rogersa4a3f402014-10-20 18:10:34 -07002742 }
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002743 DCHECK(GetCompiledMethod(method_ref) != nullptr)
2744 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002745}
2746
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002747void CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2748 CompiledMethod* compiled_method = nullptr;
2749 {
2750 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2751 auto it = compiled_methods_.find(method_ref);
2752 if (it != compiled_methods_.end()) {
2753 compiled_method = it->second;
2754 compiled_methods_.erase(it);
2755 }
2756 }
2757 if (compiled_method != nullptr) {
2758 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, compiled_method);
2759 }
2760}
2761
Brian Carlstrom7940e442013-07-12 13:46:57 -07002762CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
2763 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2764 ClassTable::const_iterator it = compiled_classes_.find(ref);
2765 if (it == compiled_classes_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002766 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002767 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002768 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002769 return it->second;
2770}
2771
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002772void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2773 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2774 auto it = compiled_classes_.find(ref);
2775 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2776 // An entry doesn't exist or the status is lower than the new status.
2777 if (it != compiled_classes_.end()) {
2778 CHECK_GT(status, it->second->GetStatus());
2779 delete it->second;
2780 }
2781 switch (status) {
2782 case mirror::Class::kStatusNotReady:
2783 case mirror::Class::kStatusError:
2784 case mirror::Class::kStatusRetryVerificationAtRuntime:
2785 case mirror::Class::kStatusVerified:
2786 case mirror::Class::kStatusInitialized:
Mathieu Chartiera8077802016-03-16 19:08:31 -07002787 case mirror::Class::kStatusResolved:
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002788 break; // Expected states.
2789 default:
2790 LOG(FATAL) << "Unexpected class status for class "
2791 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2792 << " of " << status;
2793 }
2794 CompiledClass* compiled_class = new CompiledClass(status);
2795 compiled_classes_.Overwrite(ref, compiled_class);
2796 }
2797}
2798
Brian Carlstrom7940e442013-07-12 13:46:57 -07002799CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2800 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2801 MethodTable::const_iterator it = compiled_methods_.find(ref);
2802 if (it == compiled_methods_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002803 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002804 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002805 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002806 return it->second;
2807}
2808
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002809bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2810 uint16_t class_def_idx,
2811 const DexFile& dex_file) const {
2812 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2813 if (verified_method != nullptr) {
2814 return !verified_method->HasVerificationFailures();
2815 }
2816
2817 // If we can't find verification metadata, check if this is a system class (we trust that system
2818 // classes have their methods verified). If it's not, be conservative and assume the method
2819 // has not been verified successfully.
2820
2821 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2822 // even if methods are not found in the verification cache.
2823 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2824 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2825 Thread* self = Thread::Current();
2826 ScopedObjectAccess soa(self);
2827 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2828 if (!is_system_class) {
2829 self->ClearException();
2830 }
2831 return is_system_class;
2832}
2833
Vladimir Markof4da6752014-08-01 19:04:18 +01002834size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
2835 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2836 return non_relative_linker_patch_count_;
2837}
2838
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002839void CompilerDriver::SetRequiresConstructorBarrier(Thread* self,
2840 const DexFile* dex_file,
2841 uint16_t class_def_index,
2842 bool requires) {
2843 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2844 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002845}
2846
Mathieu Chartier371bd832016-04-07 10:19:48 -07002847bool CompilerDriver::RequiresConstructorBarrier(Thread* self,
2848 const DexFile* dex_file,
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002849 uint16_t class_def_index) {
2850 ClassReference class_ref(dex_file, class_def_index);
2851 {
2852 ReaderMutexLock mu(self, requires_constructor_barrier_lock_);
2853 auto it = requires_constructor_barrier_.find(class_ref);
2854 if (it != requires_constructor_barrier_.end()) {
2855 return it->second;
2856 }
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002857 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002858 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2859 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index);
2860 requires_constructor_barrier_.emplace(class_ref, requires);
2861 return requires;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002862}
2863
Andreas Gampe8d295f82015-01-20 14:50:21 -08002864std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002865 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002866 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002867 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002868 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002869 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002870#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002871 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002872 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2873 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002874 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2875 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002876#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002877 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002878 return oss.str();
2879}
2880
Jeff Hao848f70a2014-01-15 13:49:50 -08002881bool CompilerDriver::IsStringTypeIndex(uint16_t type_index, const DexFile* dex_file) {
2882 const char* type = dex_file->GetTypeDescriptor(dex_file->GetTypeId(type_index));
2883 return strcmp(type, "Ljava/lang/String;") == 0;
2884}
2885
2886bool CompilerDriver::IsStringInit(uint32_t method_index, const DexFile* dex_file, int32_t* offset) {
2887 DexFileMethodInliner* inliner = GetMethodInlinerMap()->GetMethodInliner(dex_file);
2888 size_t pointer_size = InstructionSetPointerSize(GetInstructionSet());
2889 *offset = inliner->GetOffsetForStringInit(method_index, pointer_size);
2890 return inliner->IsStringInitMethodIndex(method_index);
2891}
2892
Jeff Haodcdc85b2015-12-04 14:06:18 -08002893bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
2894 const DexFile* inlined_into) const {
2895 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
2896 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00002897 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
2898 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002899 return false;
2900 }
2901
2902 return true;
2903}
2904
Andreas Gampeace0dc12016-01-20 13:33:13 -08002905void CompilerDriver::InitializeThreadPools() {
2906 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2907 parallel_thread_pool_.reset(
2908 new ThreadPool("Compiler driver thread pool", parallel_count));
2909 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2910}
2911
2912void CompilerDriver::FreeThreadPools() {
2913 parallel_thread_pool_.reset();
2914 single_thread_pool_.reset();
2915}
2916
Brian Carlstrom7940e442013-07-12 13:46:57 -07002917} // namespace art