blob: daac7fbb96db9ddcb8e411e7adb5ddadab6c42d8 [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"
Andreas Gampe542451c2016-07-26 09:02:02 -070030#include "base/enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070031#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080032#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010033#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070034#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010035#include "class_linker-inl.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070036#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000037#include "compiled_method.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000038#include "compiler.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000039#include "compiler_driver-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070040#include "dex_compilation_unit.h"
41#include "dex_file-inl.h"
Andreas Gampeace0dc12016-01-20 13:33:13 -080042#include "dex_instruction-inl.h"
Andreas Gampe5eb0d382015-07-23 01:19:26 -070043#include "dex/dex_to_dex_compiler.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000044#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000045#include "dex/verified_method.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000046#include "dex/quick/dex_file_method_inliner.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080047#include "dex/quick/dex_file_to_method_inliner_map.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080048#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "jni_internal.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070050#include "object_lock.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "runtime.h"
52#include "gc/accounting/card_table-inl.h"
53#include "gc/accounting/heap_bitmap.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070054#include "gc/space/image_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "gc/space/space.h"
56#include "mirror/class_loader.h"
57#include "mirror/class-inl.h"
58#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "mirror/object-inl.h"
60#include "mirror/object_array-inl.h"
61#include "mirror/throwable.h"
62#include "scoped_thread_state_change.h"
63#include "ScopedLocalRef.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070064#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "thread.h"
Andreas Gampeb0f370e2014-09-25 22:51:40 -070066#include "thread_list.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070068#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010069#include "transaction.h"
Vladimir Marko492a7fa2016-06-01 18:38:43 +010070#include "utils/array_ref.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000071#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampee21dc3d2014-12-08 16:59:43 -080072#include "utils/swap_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "verifier/method_verifier.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000074#include "verifier/method_verifier-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075
Brian Carlstrom7940e442013-07-12 13:46:57 -070076namespace art {
77
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070078static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
79
Calin Juravle226501b2015-12-11 14:41:31 +000080// Print additional info during profile guided compilation.
81static constexpr bool kDebugProfileGuidedCompilation = false;
82
Brian Carlstrom7940e442013-07-12 13:46:57 -070083static double Percentage(size_t x, size_t y) {
84 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
85}
86
87static void DumpStat(size_t x, size_t y, const char* str) {
88 if (x == 0 && y == 0) {
89 return;
90 }
Ian Rogerse732ef12013-10-09 15:22:24 -070091 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -070092}
93
Vladimir Markof096aad2014-01-23 15:51:58 +000094class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -070095 public:
96 AOTCompilationStats()
97 : stats_lock_("AOT compilation statistics lock"),
98 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
99 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
100 resolved_types_(0), unresolved_types_(0),
101 resolved_instance_fields_(0), unresolved_instance_fields_(0),
102 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
103 type_based_devirtualization_(0),
104 safe_casts_(0), not_safe_casts_(0) {
105 for (size_t i = 0; i <= kMaxInvokeType; i++) {
106 resolved_methods_[i] = 0;
107 unresolved_methods_[i] = 0;
108 virtual_made_direct_[i] = 0;
109 direct_calls_to_boot_[i] = 0;
110 direct_methods_to_boot_[i] = 0;
111 }
112 }
113
114 void Dump() {
115 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
116 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
117 DumpStat(resolved_types_, unresolved_types_, "types resolved");
118 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
119 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
120 "static fields resolved");
121 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
122 "static fields local to a class");
123 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
124 // Note, the code below subtracts the stat value so that when added to the stat value we have
125 // 100% of samples. TODO: clean this up.
126 DumpStat(type_based_devirtualization_,
127 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
128 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
129 type_based_devirtualization_,
130 "virtual/interface calls made direct based on type information");
131
132 for (size_t i = 0; i <= kMaxInvokeType; i++) {
133 std::ostringstream oss;
134 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
135 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
136 if (virtual_made_direct_[i] > 0) {
137 std::ostringstream oss2;
138 oss2 << static_cast<InvokeType>(i) << " methods made direct";
139 DumpStat(virtual_made_direct_[i],
140 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
141 oss2.str().c_str());
142 }
143 if (direct_calls_to_boot_[i] > 0) {
144 std::ostringstream oss2;
145 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
146 DumpStat(direct_calls_to_boot_[i],
147 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
148 oss2.str().c_str());
149 }
150 if (direct_methods_to_boot_[i] > 0) {
151 std::ostringstream oss2;
152 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
153 DumpStat(direct_methods_to_boot_[i],
154 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
155 oss2.str().c_str());
156 }
157 }
158 }
159
160// Allow lossy statistics in non-debug builds.
161#ifndef NDEBUG
162#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
163#else
164#define STATS_LOCK()
165#endif
166
Mathieu Chartier90443472015-07-16 20:32:27 -0700167 void TypeInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700168 STATS_LOCK();
169 types_in_dex_cache_++;
170 }
171
Mathieu Chartier90443472015-07-16 20:32:27 -0700172 void TypeNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700173 STATS_LOCK();
174 types_not_in_dex_cache_++;
175 }
176
Mathieu Chartier90443472015-07-16 20:32:27 -0700177 void StringInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 STATS_LOCK();
179 strings_in_dex_cache_++;
180 }
181
Mathieu Chartier90443472015-07-16 20:32:27 -0700182 void StringNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700183 STATS_LOCK();
184 strings_not_in_dex_cache_++;
185 }
186
Mathieu Chartier90443472015-07-16 20:32:27 -0700187 void TypeDoesntNeedAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188 STATS_LOCK();
189 resolved_types_++;
190 }
191
Mathieu Chartier90443472015-07-16 20:32:27 -0700192 void TypeNeedsAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700193 STATS_LOCK();
194 unresolved_types_++;
195 }
196
Mathieu Chartier90443472015-07-16 20:32:27 -0700197 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700198 STATS_LOCK();
199 resolved_instance_fields_++;
200 }
201
Mathieu Chartier90443472015-07-16 20:32:27 -0700202 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 STATS_LOCK();
204 unresolved_instance_fields_++;
205 }
206
Mathieu Chartier90443472015-07-16 20:32:27 -0700207 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700208 STATS_LOCK();
209 resolved_local_static_fields_++;
210 }
211
Mathieu Chartier90443472015-07-16 20:32:27 -0700212 void ResolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700213 STATS_LOCK();
214 resolved_static_fields_++;
215 }
216
Mathieu Chartier90443472015-07-16 20:32:27 -0700217 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 STATS_LOCK();
219 unresolved_static_fields_++;
220 }
221
222 // Indicate that type information from the verifier led to devirtualization.
Mathieu Chartier90443472015-07-16 20:32:27 -0700223 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700224 STATS_LOCK();
225 type_based_devirtualization_++;
226 }
227
228 // Indicate that a method of the given type was resolved at compile time.
Mathieu Chartier90443472015-07-16 20:32:27 -0700229 void ResolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700230 DCHECK_LE(type, kMaxInvokeType);
231 STATS_LOCK();
232 resolved_methods_[type]++;
233 }
234
235 // Indicate that a method of the given type was unresolved at compile time as it was in an
236 // unknown dex file.
Mathieu Chartier90443472015-07-16 20:32:27 -0700237 void UnresolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700238 DCHECK_LE(type, kMaxInvokeType);
239 STATS_LOCK();
240 unresolved_methods_[type]++;
241 }
242
243 // Indicate that a type of virtual method dispatch has been converted into a direct method
244 // dispatch.
Mathieu Chartier90443472015-07-16 20:32:27 -0700245 void VirtualMadeDirect(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700246 DCHECK(type == kVirtual || type == kInterface || type == kSuper);
247 STATS_LOCK();
248 virtual_made_direct_[type]++;
249 }
250
251 // Indicate that a method of the given type was able to call directly into boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700252 void DirectCallsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700253 DCHECK_LE(type, kMaxInvokeType);
254 STATS_LOCK();
255 direct_calls_to_boot_[type]++;
256 }
257
258 // Indicate that a method of the given type was able to be resolved directly from boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700259 void DirectMethodsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700260 DCHECK_LE(type, kMaxInvokeType);
261 STATS_LOCK();
262 direct_methods_to_boot_[type]++;
263 }
264
Mathieu Chartier90443472015-07-16 20:32:27 -0700265 void ProcessedInvoke(InvokeType type, int flags) REQUIRES(!stats_lock_) {
Vladimir Markof096aad2014-01-23 15:51:58 +0000266 STATS_LOCK();
267 if (flags == 0) {
268 unresolved_methods_[type]++;
269 } else {
270 DCHECK_NE((flags & kFlagMethodResolved), 0);
271 resolved_methods_[type]++;
272 if ((flags & kFlagVirtualMadeDirect) != 0) {
273 virtual_made_direct_[type]++;
274 if ((flags & kFlagPreciseTypeDevirtualization) != 0) {
275 type_based_devirtualization_++;
276 }
277 } else {
278 DCHECK_EQ((flags & kFlagPreciseTypeDevirtualization), 0);
279 }
280 if ((flags & kFlagDirectCallToBoot) != 0) {
281 direct_calls_to_boot_[type]++;
282 }
283 if ((flags & kFlagDirectMethodToBoot) != 0) {
284 direct_methods_to_boot_[type]++;
285 }
286 }
287 }
288
Brian Carlstrom7940e442013-07-12 13:46:57 -0700289 // A check-cast could be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700290 void SafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291 STATS_LOCK();
292 safe_casts_++;
293 }
294
295 // A check-cast couldn't be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700296 void NotASafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700297 STATS_LOCK();
298 not_safe_casts_++;
299 }
300
301 private:
302 Mutex stats_lock_;
303
304 size_t types_in_dex_cache_;
305 size_t types_not_in_dex_cache_;
306
307 size_t strings_in_dex_cache_;
308 size_t strings_not_in_dex_cache_;
309
310 size_t resolved_types_;
311 size_t unresolved_types_;
312
313 size_t resolved_instance_fields_;
314 size_t unresolved_instance_fields_;
315
316 size_t resolved_local_static_fields_;
317 size_t resolved_static_fields_;
318 size_t unresolved_static_fields_;
319 // Type based devirtualization for invoke interface and virtual.
320 size_t type_based_devirtualization_;
321
322 size_t resolved_methods_[kMaxInvokeType + 1];
323 size_t unresolved_methods_[kMaxInvokeType + 1];
324 size_t virtual_made_direct_[kMaxInvokeType + 1];
325 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
326 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
327
328 size_t safe_casts_;
329 size_t not_safe_casts_;
330
331 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
332};
333
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100334class CompilerDriver::DexFileMethodSet {
335 public:
336 explicit DexFileMethodSet(const DexFile& dex_file)
337 : dex_file_(dex_file),
338 method_indexes_(dex_file.NumMethodIds(), false, Allocator::GetMallocAllocator()) {
339 }
340 DexFileMethodSet(DexFileMethodSet&& other) = default;
341
342 const DexFile& GetDexFile() const { return dex_file_; }
343
344 BitVector& GetMethodIndexes() { return method_indexes_; }
345 const BitVector& GetMethodIndexes() const { return method_indexes_; }
346
347 private:
348 const DexFile& dex_file_;
349 BitVector method_indexes_;
350};
351
Jeff Haodcdc85b2015-12-04 14:06:18 -0800352CompilerDriver::CompilerDriver(
353 const CompilerOptions* compiler_options,
354 VerificationResults* verification_results,
355 DexFileToMethodInlinerMap* method_inliner_map,
356 Compiler::Kind compiler_kind,
357 InstructionSet instruction_set,
358 const InstructionSetFeatures* instruction_set_features,
Vladimir Marko944da602016-02-19 12:27:55 +0000359 bool boot_image,
Mathieu Chartier91288d82016-04-28 09:44:54 -0700360 bool app_image,
Vladimir Marko944da602016-02-19 12:27:55 +0000361 std::unordered_set<std::string>* image_classes,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800362 std::unordered_set<std::string>* compiled_classes,
363 std::unordered_set<std::string>* compiled_methods,
Vladimir Marko944da602016-02-19 12:27:55 +0000364 size_t thread_count,
365 bool dump_stats,
366 bool dump_passes,
367 CumulativeLogger* timer,
368 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200369 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000370 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800371 verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000372 method_inliner_map_(method_inliner_map),
Ian Rogers72d32622014-05-06 16:20:11 -0700373 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700374 compiler_kind_(compiler_kind),
Artem Serovba6b6792016-08-15 14:22:07 +0100375 instruction_set_(instruction_set == kArm ? kThumb2: instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700376 instruction_set_features_(instruction_set_features),
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700377 requires_constructor_barrier_lock_("constructor barrier lock"),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700378 compiled_classes_lock_("compiled classes lock"),
379 compiled_methods_lock_("compiled method lock"),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800380 compiled_methods_(MethodTable::key_compare()),
Vladimir Markof4da6752014-08-01 19:04:18 +0100381 non_relative_linker_patch_count_(0u),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800382 boot_image_(boot_image),
Mathieu Chartier91288d82016-04-28 09:44:54 -0700383 app_image_(app_image),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700384 image_classes_(image_classes),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800385 classes_to_compile_(compiled_classes),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700386 methods_to_compile_(compiled_methods),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800387 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800388 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700389 stats_(new AOTCompilationStats),
390 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000391 dump_passes_(dump_passes),
392 timings_logger_(timer),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700393 compiler_context_(nullptr),
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700394 support_boot_image_fixup_(instruction_set != kMips64),
Vladimir Markod1eaf0d2015-10-29 12:18:29 +0000395 dex_files_for_oat_file_(nullptr),
Calin Juravle998c2162015-12-21 15:39:33 +0200396 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000397 profile_compilation_info_(profile_compilation_info),
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100398 max_arena_alloc_(0),
399 dex_to_dex_references_lock_("dex-to-dex references lock"),
400 dex_to_dex_references_(),
401 current_dex_to_dex_methods_(nullptr) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800402 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom6449c622014-02-10 23:48:36 -0800403 DCHECK(method_inliner_map_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700404
Ian Rogers72d32622014-05-06 16:20:11 -0700405 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700406
Mathieu Chartiera8077802016-03-16 19:08:31 -0700407 if (compiler_options->VerifyOnlyProfile()) {
408 CHECK(profile_compilation_info_ != nullptr) << "Requires profile";
409 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800410 if (boot_image_) {
411 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image";
412 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700413}
414
415CompilerDriver::~CompilerDriver() {
416 Thread* self = Thread::Current();
417 {
418 MutexLock mu(self, compiled_classes_lock_);
419 STLDeleteValues(&compiled_classes_);
420 }
421 {
422 MutexLock mu(self, compiled_methods_lock_);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800423 for (auto& pair : compiled_methods_) {
424 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, pair.second);
425 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700426 }
Ian Rogers72d32622014-05-06 16:20:11 -0700427 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700428}
429
Vladimir Marko35831e82015-09-11 11:59:18 +0100430
Ian Rogersdd7624d2014-03-14 17:43:00 -0700431#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700432 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700433 return CreateTrampoline64(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700434 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700435 } else { \
436 return CreateTrampoline32(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700437 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700438 }
439
Vladimir Marko93205e32016-04-13 11:59:46 +0100440std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700441 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700442}
443
Vladimir Marko93205e32016-04-13 11:59:46 +0100444std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
445 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700446 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800447}
448
Vladimir Marko93205e32016-04-13 11:59:46 +0100449std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
450 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700451 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700452}
453
Vladimir Marko93205e32016-04-13 11:59:46 +0100454std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
455 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700456 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700457}
458
Vladimir Marko93205e32016-04-13 11:59:46 +0100459std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
460 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700461 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700462}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700463#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700464
465void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700466 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800467 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700468 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800469
470 InitializeThreadPools();
471
Andreas Gampe8d295f82015-01-20 14:50:21 -0800472 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
Andreas Gampe740667a2015-09-15 17:55:06 -0700473 // Precompile:
474 // 1) Load image classes
475 // 2) Resolve all classes
476 // 3) Attempt to verify all classes
477 // 4) Attempt to initialize image classes, and trivially initialized classes
Andreas Gampeace0dc12016-01-20 13:33:13 -0800478 PreCompile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700479 // Compile:
480 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
481 // compilation.
482 if (!GetCompilerOptions().VerifyAtRuntime()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800483 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700484 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700485 if (dump_stats_) {
486 stats_->Dump();
487 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800488
489 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700490}
491
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700492static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
493 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
494 const DexFile& dex_file, const DexFile::ClassDef& class_def)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700495 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800496 auto* const runtime = Runtime::Current();
Calin Juravleffc87072016-04-20 14:22:09 +0100497 if (runtime->UseJitCompilation() || driver.GetCompilerOptions().VerifyAtRuntime()) {
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700498 // Verify at runtime shouldn't dex to dex since we didn't resolve of verify.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700499 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800500 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700501 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800502 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800503 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700504 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700505 CHECK(self->IsExceptionPending());
506 self->ClearException();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700507 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700508 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700509 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
510 // references with actual offsets. We cannot re-verify such instructions.
511 //
512 // We store the verification information in the class status in the oat file, which the linker
513 // can validate (checksums) and use to skip load-time verification. It is thus safe to
514 // optimize when a class has been fully verified before.
515 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200516 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700517 return optimizer::DexToDexCompilationLevel::kOptimize;
Sebastien Hertz75021222013-07-16 18:34:50 +0200518 } else if (klass->IsCompileTimeVerified()) {
519 // Class verification has soft-failed. Anyway, ensure at least correctness.
520 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700521 return optimizer::DexToDexCompilationLevel::kRequired;
Sebastien Hertz75021222013-07-16 18:34:50 +0200522 } else {
523 // Class verification has failed: do not run DEX-to-DEX compilation.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700524 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
525 }
526}
527
528static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
529 Thread* self,
530 const CompilerDriver& driver,
531 jobject jclass_loader,
532 const DexFile& dex_file,
533 const DexFile::ClassDef& class_def) {
534 ScopedObjectAccess soa(self);
535 StackHandleScope<1> hs(soa.Self());
536 Handle<mirror::ClassLoader> class_loader(
537 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
538 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
539}
540
541// Does the runtime for the InstructionSet provide an implementation returned by
542// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
543static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
544 switch (isa) {
545 case kArm:
546 case kArm64:
547 case kThumb2:
548 case kMips:
549 case kMips64:
550 case kX86:
551 case kX86_64: return true;
552 default: return false;
553 }
554}
555
556static void CompileMethod(Thread* self,
557 CompilerDriver* driver,
558 const DexFile::CodeItem* code_item,
559 uint32_t access_flags,
560 InvokeType invoke_type,
561 uint16_t class_def_idx,
562 uint32_t method_idx,
563 jobject class_loader,
564 const DexFile& dex_file,
565 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700566 bool compilation_enabled,
567 Handle<mirror::DexCache> dex_cache)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700568 REQUIRES(!driver->compiled_methods_lock_) {
569 DCHECK(driver != nullptr);
570 CompiledMethod* compiled_method = nullptr;
571 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
572 MethodReference method_ref(&dex_file, method_idx);
573
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100574 if (driver->GetCurrentDexToDexMethods() != nullptr) {
575 // This is the second pass when we dex-to-dex compile previously marked methods.
576 // TODO: Refactor the compilation to avoid having to distinguish the two passes
577 // here. That should be done on a higher level. http://b/29089975
578 if (driver->GetCurrentDexToDexMethods()->IsBitSet(method_idx)) {
579 const VerifiedMethod* verified_method =
580 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
581 // Do not optimize if a VerifiedMethod is missing. SafeCast elision,
582 // for example, relies on it.
583 compiled_method = optimizer::ArtCompileDEX(
584 driver,
585 code_item,
586 access_flags,
587 invoke_type,
588 class_def_idx,
589 method_idx,
590 class_loader,
591 dex_file,
592 (verified_method != nullptr)
593 ? dex_to_dex_compilation_level
594 : optimizer::DexToDexCompilationLevel::kRequired);
595 }
596 } else if ((access_flags & kAccNative) != 0) {
Vladimir Markof6d1e0f2016-05-23 15:32:42 +0100597 // Are we extracting only and have support for generic JNI down calls?
598 if (!driver->GetCompilerOptions().IsJniCompilationEnabled() &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700599 InstructionSetHasGenericJniStub(driver->GetInstructionSet())) {
600 // Leaving this empty will trigger the generic JNI version
601 } else {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700602 // Look-up the ArtMethod associated with this code_item (if any)
603 // -- It is later used to lookup any [optimization] annotations for this method.
604 ScopedObjectAccess soa(self);
605 StackHandleScope<1> hs(soa.Self());
606 Handle<mirror::ClassLoader> class_loader_handle(hs.NewHandle(
607 soa.Decode<mirror::ClassLoader*>(class_loader)));
608
609 // TODO: Lookup annotation from DexFile directly without resolving method.
610 ArtMethod* method =
611 Runtime::Current()->GetClassLinker()->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
612 dex_file,
613 method_idx,
614 dex_cache,
615 class_loader_handle,
616 /* referrer */ nullptr,
617 invoke_type);
618
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700619 // Query any JNI optimization annotations such as @FastNative or @CriticalNative.
620 Compiler::JniOptimizationFlags optimization_flags = Compiler::kNone;
621 if (UNLIKELY(method == nullptr)) {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700622 // Failed method resolutions happen very rarely, e.g. ancestor class cannot be resolved.
623 DCHECK(self->IsExceptionPending());
624 self->ClearException();
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700625 } else if (method->IsAnnotatedWithFastNative()) {
626 // TODO: Will no longer need this CHECK once we have verifier checking this.
627 CHECK(!method->IsAnnotatedWithCriticalNative());
628 optimization_flags = Compiler::kFastNative;
629 } else if (method->IsAnnotatedWithCriticalNative()) {
630 // TODO: Will no longer need this CHECK once we have verifier checking this.
631 CHECK(!method->IsAnnotatedWithFastNative());
632 optimization_flags = Compiler::kCriticalNative;
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700633 }
634
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700635 compiled_method = driver->GetCompiler()->JniCompile(access_flags,
636 method_idx,
637 dex_file,
638 optimization_flags);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700639 CHECK(compiled_method != nullptr);
640 }
641 } else if ((access_flags & kAccAbstract) != 0) {
642 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000643 } else {
Andreas Gampe0760a812015-08-26 17:12:51 -0700644 const VerifiedMethod* verified_method =
645 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700646 bool compile = compilation_enabled &&
647 // Basic checks, e.g., not <clinit>.
648 driver->GetVerificationResults()
649 ->IsCandidateForCompilation(method_ref, access_flags) &&
650 // Did not fail to create VerifiedMethod metadata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700651 verified_method != nullptr &&
652 // Do not have failures that should punt to the interpreter.
653 !verified_method->HasRuntimeThrow() &&
654 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700655 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700656 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000657 driver->IsMethodToCompile(method_ref) &&
658 driver->ShouldCompileBasedOnProfile(method_ref);
659
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700660 if (compile) {
661 // NOTE: if compiler declines to compile this method, it will return null.
662 compiled_method = driver->GetCompiler()->Compile(code_item, access_flags, invoke_type,
663 class_def_idx, method_idx, class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700664 dex_file, dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700665 }
666 if (compiled_method == nullptr &&
667 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100668 DCHECK(!Runtime::Current()->UseJitCompilation());
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700669 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100670 driver->MarkForDexToDexCompilation(self, method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700671 }
672 }
673 if (kTimeCompileMethod) {
674 uint64_t duration_ns = NanoTime() - start_ns;
675 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
676 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
677 << " took " << PrettyDuration(duration_ns);
678 }
679 }
680
681 if (compiled_method != nullptr) {
682 // Count non-relative linker patches.
683 size_t non_relative_linker_patch_count = 0u;
684 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
685 if (!patch.IsPcRelative()) {
686 ++non_relative_linker_patch_count;
687 }
688 }
689 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
690 // When compiling with PIC, there should be zero non-relative linker patches
691 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
692
693 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
694 }
695
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700696 if (self->IsExceptionPending()) {
697 ScopedObjectAccess soa(self);
698 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
699 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200700 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700701}
702
Mathieu Chartiere401d142015-04-22 13:56:20 -0700703void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700704 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700705 jobject jclass_loader;
706 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700707 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800708 uint32_t method_idx = method->GetDexMethodIndex();
709 uint32_t access_flags = method->GetAccessFlags();
710 InvokeType invoke_type = method->GetInvokeType();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700711 StackHandleScope<1> hs(self);
712 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700713 {
714 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800715 ScopedLocalRef<jobject> local_class_loader(
716 soa.Env(), soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700717 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
718 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700719 dex_file = method->GetDexFile();
720 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700721 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800722 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700723
724 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700725 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700726
727 std::vector<const DexFile*> dex_files;
728 dex_files.push_back(dex_file);
729
Andreas Gampeace0dc12016-01-20 13:33:13 -0800730 InitializeThreadPools();
731
732 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700733
Brian Carlstrom7940e442013-07-12 13:46:57 -0700734 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700735 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
736 GetDexToDexCompilationLevel(self,
737 *this,
738 jclass_loader,
739 *dex_file,
740 dex_file->GetClassDef(class_def_idx));
741
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100742 DCHECK(current_dex_to_dex_methods_ == nullptr);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700743 CompileMethod(self,
744 this,
745 code_item,
746 access_flags,
747 invoke_type,
748 class_def_idx,
749 method_idx,
750 jclass_loader,
751 *dex_file,
752 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700753 true,
754 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700755
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100756 ArrayRef<DexFileMethodSet> dex_to_dex_references;
757 {
758 // From this point on, we shall not modify dex_to_dex_references_, so
759 // just grab a reference to it that we use without holding the mutex.
760 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
761 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
762 }
763 if (!dex_to_dex_references.empty()) {
764 DCHECK_EQ(dex_to_dex_references.size(), 1u);
765 DCHECK(&dex_to_dex_references[0].GetDexFile() == dex_file);
766 current_dex_to_dex_methods_ = &dex_to_dex_references.front().GetMethodIndexes();
767 DCHECK(current_dex_to_dex_methods_->IsBitSet(method_idx));
768 DCHECK_EQ(current_dex_to_dex_methods_->NumSetBits(), 1u);
769 CompileMethod(self,
770 this,
771 code_item,
772 access_flags,
773 invoke_type,
774 class_def_idx,
775 method_idx,
776 jclass_loader,
777 *dex_file,
778 dex_to_dex_compilation_level,
779 true,
780 dex_cache);
781 current_dex_to_dex_methods_ = nullptr;
782 }
783
Andreas Gampeace0dc12016-01-20 13:33:13 -0800784 FreeThreadPools();
785
Brian Carlstrom7940e442013-07-12 13:46:57 -0700786 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800787}
788
Andreas Gampeace0dc12016-01-20 13:33:13 -0800789void CompilerDriver::Resolve(jobject class_loader,
790 const std::vector<const DexFile*>& dex_files,
791 TimingLogger* timings) {
792 // Resolution allocates classes and needs to run single-threaded to be deterministic.
793 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
794 ThreadPool* resolve_thread_pool = force_determinism
795 ? single_thread_pool_.get()
796 : parallel_thread_pool_.get();
797 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
798
Brian Carlstrom7940e442013-07-12 13:46:57 -0700799 for (size_t i = 0; i != dex_files.size(); ++i) {
800 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700801 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800802 ResolveDexFile(class_loader,
803 *dex_file,
804 dex_files,
805 resolve_thread_pool,
806 resolve_thread_count,
807 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700808 }
809}
810
Andreas Gampeace0dc12016-01-20 13:33:13 -0800811// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
812// this is single-threaded for simplicity.
813// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
814// stable order.
815
816static void ResolveConstStrings(CompilerDriver* driver,
817 const DexFile& dex_file,
818 const DexFile::CodeItem* code_item) {
819 if (code_item == nullptr) {
820 // Abstract or native method.
821 return;
822 }
823
824 const uint16_t* code_ptr = code_item->insns_;
825 const uint16_t* code_end = code_item->insns_ + code_item->insns_size_in_code_units_;
826
827 while (code_ptr < code_end) {
828 const Instruction* inst = Instruction::At(code_ptr);
829 switch (inst->Opcode()) {
830 case Instruction::CONST_STRING: {
831 uint32_t string_index = inst->VRegB_21c();
832 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
833 break;
834 }
835 case Instruction::CONST_STRING_JUMBO: {
836 uint32_t string_index = inst->VRegB_31c();
837 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
838 break;
839 }
840
841 default:
842 break;
843 }
844
845 code_ptr += inst->SizeInCodeUnits();
846 }
847}
848
849static void ResolveConstStrings(CompilerDriver* driver,
850 const std::vector<const DexFile*>& dex_files,
851 TimingLogger* timings) {
852 for (const DexFile* dex_file : dex_files) {
853 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
854
855 size_t class_def_count = dex_file->NumClassDefs();
856 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
857 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
858
859 const uint8_t* class_data = dex_file->GetClassData(class_def);
860 if (class_data == nullptr) {
861 // empty class, probably a marker interface
862 continue;
863 }
864
865 ClassDataItemIterator it(*dex_file, class_data);
866 // Skip fields
867 while (it.HasNextStaticField()) {
868 it.Next();
869 }
870 while (it.HasNextInstanceField()) {
871 it.Next();
872 }
873
874 bool compilation_enabled = driver->IsClassToCompile(
875 dex_file->StringByTypeIdx(class_def.class_idx_));
876 if (!compilation_enabled) {
877 // Compilation is skipped, do not resolve const-string in code of this class.
878 // TODO: Make sure that inlining honors this.
879 continue;
880 }
881
882 // Direct methods.
883 int64_t previous_direct_method_idx = -1;
884 while (it.HasNextDirectMethod()) {
885 uint32_t method_idx = it.GetMemberIndex();
886 if (method_idx == previous_direct_method_idx) {
887 // smali can create dex files with two encoded_methods sharing the same method_idx
888 // http://code.google.com/p/smali/issues/detail?id=119
889 it.Next();
890 continue;
891 }
892 previous_direct_method_idx = method_idx;
893 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
894 it.Next();
895 }
896 // Virtual methods.
897 int64_t previous_virtual_method_idx = -1;
898 while (it.HasNextVirtualMethod()) {
899 uint32_t method_idx = it.GetMemberIndex();
900 if (method_idx == previous_virtual_method_idx) {
901 // smali can create dex files with two encoded_methods sharing the same method_idx
902 // http://code.google.com/p/smali/issues/detail?id=119
903 it.Next();
904 continue;
905 }
906 previous_virtual_method_idx = method_idx;
907 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
908 it.Next();
909 }
910 DCHECK(!it.HasNext());
911 }
912 }
913}
914
915inline void CompilerDriver::CheckThreadPools() {
916 DCHECK(parallel_thread_pool_ != nullptr);
917 DCHECK(single_thread_pool_ != nullptr);
918}
919
920void CompilerDriver::PreCompile(jobject class_loader,
921 const std::vector<const DexFile*>& dex_files,
922 TimingLogger* timings) {
923 CheckThreadPools();
924
Brian Carlstrom7940e442013-07-12 13:46:57 -0700925 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800926 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700927
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700928 const bool verification_enabled = compiler_options_->IsVerificationEnabled();
929 const bool never_verify = compiler_options_->NeverVerify();
Mathieu Chartiera8077802016-03-16 19:08:31 -0700930 const bool verify_only_profile = compiler_options_->VerifyOnlyProfile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700931
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700932 // We need to resolve for never_verify since it needs to run dex to dex to add the
933 // RETURN_VOID_NO_BARRIER.
Mathieu Chartiera8077802016-03-16 19:08:31 -0700934 // Let the verifier resolve as needed for the verify_only_profile case.
935 if ((never_verify || verification_enabled) && !verify_only_profile) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800936 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700937 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
938 }
939
940 if (never_verify) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800941 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800942 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700943 }
944
945 if (!verification_enabled) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700946 return;
947 }
948
Andreas Gampeace0dc12016-01-20 13:33:13 -0800949 if (GetCompilerOptions().IsForceDeterminism() && IsBootImage()) {
950 // Resolve strings from const-string. Do this now to have a deterministic image.
951 ResolveConstStrings(this, dex_files, timings);
952 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
953 }
954
955 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800956 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700957
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800958 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
959 LOG(FATAL) << "Had a hard failure verifying all classes, and was asked to abort in such "
960 << "situations. Please check the log.";
961 }
962
Andreas Gampeace0dc12016-01-20 13:33:13 -0800963 InitializeClasses(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800964 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700965
966 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800967 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700968}
969
Ian Rogersdfb325e2013-10-30 01:00:44 -0700970bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800971 if (image_classes_ != nullptr) {
972 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -0700973 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700974 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800975 // No set of image classes, assume we include all the classes.
976 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
977 return !IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700978}
979
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800980bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700981 if (classes_to_compile_ == nullptr) {
982 return true;
983 }
984 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800985}
986
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700987bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700988 if (methods_to_compile_ == nullptr) {
989 return true;
990 }
991
992 std::string tmp = PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
993 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
994}
995
Calin Juravle226501b2015-12-11 14:41:31 +0000996bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
997 if (profile_compilation_info_ == nullptr) {
998 // If we miss profile information it means that we don't do a profile guided compilation.
999 // Return true, and let the other filters decide if the method should be compiled.
1000 return true;
1001 }
1002 bool result = profile_compilation_info_->ContainsMethod(method_ref);
1003
1004 if (kDebugProfileGuidedCompilation) {
1005 LOG(INFO) << "[ProfileGuidedCompilation] "
1006 << (result ? "Compiled" : "Skipped") << " method:"
1007 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
1008 }
1009 return result;
1010}
1011
Mathieu Chartiera8077802016-03-16 19:08:31 -07001012bool CompilerDriver::ShouldVerifyClassBasedOnProfile(const DexFile& dex_file,
1013 uint16_t class_idx) const {
1014 if (!compiler_options_->VerifyOnlyProfile()) {
1015 // No profile, verify everything.
1016 return true;
1017 }
1018 DCHECK(profile_compilation_info_ != nullptr);
1019 bool result = profile_compilation_info_->ContainsClass(dex_file, class_idx);
1020 if (kDebugProfileGuidedCompilation) {
1021 LOG(INFO) << "[ProfileGuidedCompilation] "
1022 << (result ? "Verified" : "Skipped") << " method:"
1023 << dex_file.GetClassDescriptor(dex_file.GetClassDef(class_idx));
1024 }
1025 return result;
1026}
1027
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001028class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
1029 public:
Chih-Hung Hsieh471118e2016-04-29 14:27:41 -07001030 explicit ResolveCatchBlockExceptionsClassVisitor(
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001031 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve)
1032 : exceptions_to_resolve_(exceptions_to_resolve) {}
1033
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001034 virtual bool operator()(mirror::Class* c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001035 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Alex Lighte64300b2015-12-15 15:02:47 -08001036 for (auto& m : c->GetMethods(pointer_size)) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001037 ResolveExceptionsForMethod(&m, pointer_size);
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001038 }
1039 return true;
1040 }
1041
1042 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001043 void ResolveExceptionsForMethod(ArtMethod* method_handle, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001044 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001045 const DexFile::CodeItem* code_item = method_handle->GetCodeItem();
1046 if (code_item == nullptr) {
1047 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -07001048 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001049 if (code_item->tries_size_ == 0) {
1050 return; // nothing to process
1051 }
1052 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
1053 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
1054 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1055 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
1056 bool has_catch_all = false;
1057 if (encoded_catch_handler_size <= 0) {
1058 encoded_catch_handler_size = -encoded_catch_handler_size;
1059 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001060 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001061 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
1062 uint16_t encoded_catch_handler_handlers_type_idx =
1063 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1064 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko05792b92015-08-03 11:56:49 +01001065 if (!method_handle->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx,
1066 pointer_size)) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001067 exceptions_to_resolve_.emplace(encoded_catch_handler_handlers_type_idx,
1068 method_handle->GetDexFile());
1069 }
1070 // ignore address associated with catch handler
1071 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1072 }
1073 if (has_catch_all) {
1074 // ignore catch all address
1075 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1076 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001077 }
1078 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001079
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001080 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve_;
1081};
1082
1083class RecordImageClassesVisitor : public ClassVisitor {
1084 public:
1085 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
1086 : image_classes_(image_classes) {}
1087
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001088 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001089 std::string temp;
1090 image_classes_->insert(klass->GetDescriptor(&temp));
1091 return true;
1092 }
1093
1094 private:
1095 std::unordered_set<std::string>* const image_classes_;
1096};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001097
1098// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001099void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001100 CHECK(timings != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001101 if (!IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001102 return;
1103 }
1104
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001105 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001106 // Make a first class to load all classes explicitly listed in the file
1107 Thread* self = Thread::Current();
1108 ScopedObjectAccess soa(self);
1109 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001110 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001111 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001112 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001113 StackHandleScope<1> hs(self);
1114 Handle<mirror::Class> klass(
1115 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001116 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001117 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001118 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001119 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001120 } else {
1121 ++it;
1122 }
1123 }
1124
1125 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1126 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1127 // Do this here so that exception classes appear to have been specified image classes.
Ian Rogers700a4022014-05-19 16:49:03 -07001128 std::set<std::pair<uint16_t, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001129 StackHandleScope<1> hs(self);
1130 Handle<mirror::Class> java_lang_Throwable(
1131 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001132 do {
1133 unresolved_exception_types.clear();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001134 ResolveCatchBlockExceptionsClassVisitor visitor(unresolved_exception_types);
1135 class_linker->VisitClasses(&visitor);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001136 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
1137 uint16_t exception_type_idx = exception_type.first;
1138 const DexFile* dex_file = exception_type.second;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001139 StackHandleScope<2> hs2(self);
Mathieu Chartierf284d442016-06-02 11:48:30 -07001140 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file,
1141 nullptr)));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001142 Handle<mirror::Class> klass(hs2.NewHandle(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001143 class_linker->ResolveType(*dex_file,
1144 exception_type_idx,
1145 dex_cache,
1146 ScopedNullHandle<mirror::ClassLoader>())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001147 if (klass.Get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001148 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1149 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1150 LOG(FATAL) << "Failed to resolve class " << descriptor;
1151 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001152 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001153 }
1154 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1155 // more are found
1156 } while (!unresolved_exception_types.empty());
1157
1158 // We walk the roots looking for classes so that we'll pick up the
1159 // above classes plus any classes them depend on such super
1160 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001161 RecordImageClassesVisitor visitor(image_classes_.get());
1162 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001163
1164 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001165}
1166
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001167static void MaybeAddToImageClasses(Handle<mirror::Class> c,
1168 std::unordered_set<std::string>* image_classes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001169 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001170 Thread* self = Thread::Current();
1171 StackHandleScope<1> hs(self);
1172 // Make a copy of the handle so that we don't clobber it doing Assign.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001173 MutableHandle<mirror::Class> klass(hs.NewHandle(c.Get()));
Ian Rogers1ff3c982014-08-12 02:30:58 -07001174 std::string temp;
Andreas Gampe542451c2016-07-26 09:02:02 -07001175 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001176 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001177 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001178 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1179 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001180 if (!result.second) { // Previously inserted.
1181 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001182 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001183 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Mathieu Chartierf8322842014-05-16 10:59:25 -07001184 for (size_t i = 0; i < klass->NumDirectInterfaces(); ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001185 StackHandleScope<1> hs2(self);
1186 MaybeAddToImageClasses(hs2.NewHandle(mirror::Class::GetDirectInterface(self, klass, i)),
Mathieu Chartierf8322842014-05-16 10:59:25 -07001187 image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001188 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001189 for (auto& m : c->GetVirtualMethods(pointer_size)) {
Alex Light36121492016-02-22 13:43:29 -08001190 StackHandleScope<1> hs2(self);
1191 MaybeAddToImageClasses(hs2.NewHandle(m.GetDeclaringClass()), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001192 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001193 if (klass->IsArrayClass()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001194 StackHandleScope<1> hs2(self);
1195 MaybeAddToImageClasses(hs2.NewHandle(klass->GetComponentType()), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001196 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001197 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001198 }
1199}
1200
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001201// Keeps all the data for the update together. Also doubles as the reference visitor.
1202// Note: we can use object pointers because we suspend all threads.
1203class ClinitImageUpdate {
1204 public:
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001205 static ClinitImageUpdate* Create(std::unordered_set<std::string>* image_class_descriptors,
1206 Thread* self, ClassLinker* linker, std::string* error_msg) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001207 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(image_class_descriptors, self,
1208 linker));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001209 if (res->dex_cache_class_ == nullptr) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001210 *error_msg = "Could not find DexCache class.";
1211 return nullptr;
1212 }
1213
1214 return res.release();
1215 }
1216
1217 ~ClinitImageUpdate() {
1218 // Allow others to suspend again.
1219 self_->EndAssertNoThreadSuspension(old_cause_);
1220 }
1221
1222 // Visitor for VisitReferences.
1223 void operator()(mirror::Object* object, MemberOffset field_offset, bool /* is_static */) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001224 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001225 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1226 if (ref != nullptr) {
1227 VisitClinitClassesObject(ref);
1228 }
1229 }
1230
1231 // java.lang.Reference visitor for VisitReferences.
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001232 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref ATTRIBUTE_UNUSED)
1233 const {}
1234
1235 // Ignore class native roots.
1236 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1237 const {}
1238 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001239
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001240 void Walk() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001241 // Use the initial classes as roots for a search.
1242 for (mirror::Class* klass_root : image_classes_) {
1243 VisitClinitClassesObject(klass_root);
1244 }
1245 }
1246
1247 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001248 class FindImageClassesVisitor : public ClassVisitor {
1249 public:
1250 explicit FindImageClassesVisitor(ClinitImageUpdate* data) : data_(data) {}
1251
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001252 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001253 std::string temp;
1254 const char* name = klass->GetDescriptor(&temp);
1255 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
1256 data_->image_classes_.push_back(klass);
1257 } else {
1258 // Check whether it is initialized and has a clinit. They must be kept, too.
1259 if (klass->IsInitialized() && klass->FindClassInitializer(
1260 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
1261 data_->image_classes_.push_back(klass);
1262 }
1263 }
1264 return true;
1265 }
1266
1267 private:
1268 ClinitImageUpdate* const data_;
1269 };
1270
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001271 ClinitImageUpdate(std::unordered_set<std::string>* image_class_descriptors, Thread* self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001272 ClassLinker* linker)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001273 REQUIRES_SHARED(Locks::mutator_lock_) :
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001274 image_class_descriptors_(image_class_descriptors), self_(self) {
1275 CHECK(linker != nullptr);
1276 CHECK(image_class_descriptors != nullptr);
1277
1278 // Make sure nobody interferes with us.
1279 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1280
1281 // Find the interesting classes.
Andreas Gampedc8b63c2014-12-02 14:39:52 -08001282 dex_cache_class_ = linker->LookupClass(self, "Ljava/lang/DexCache;",
1283 ComputeModifiedUtf8Hash("Ljava/lang/DexCache;"), nullptr);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001284
1285 // Find all the already-marked classes.
1286 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001287 FindImageClassesVisitor visitor(this);
1288 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001289 }
1290
1291 void VisitClinitClassesObject(mirror::Object* object) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001292 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001293 DCHECK(object != nullptr);
1294 if (marked_objects_.find(object) != marked_objects_.end()) {
1295 // Already processed.
1296 return;
1297 }
1298
1299 // Mark it.
1300 marked_objects_.insert(object);
1301
1302 if (object->IsClass()) {
1303 // If it is a class, add it.
1304 StackHandleScope<1> hs(self_);
1305 MaybeAddToImageClasses(hs.NewHandle(object->AsClass()), image_class_descriptors_);
1306 } else {
1307 // Else visit the object's class.
1308 VisitClinitClassesObject(object->GetClass());
1309 }
1310
Mathieu Chartiere401d142015-04-22 13:56:20 -07001311 // If it is not a DexCache, visit all references.
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001312 mirror::Class* klass = object->GetClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001313 if (klass != dex_cache_class_) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001314 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001315 }
1316 }
1317
1318 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001319 std::unordered_set<std::string>* const image_class_descriptors_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001320 std::vector<mirror::Class*> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001321 const mirror::Class* dex_cache_class_;
1322 Thread* const self_;
1323 const char* old_cause_;
1324
1325 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1326};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001327
Ian Rogers3d504072014-03-01 09:16:49 -08001328void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001329 if (IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001330 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001331
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001332 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001333
1334 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001335 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001336
1337 std::string error_msg;
1338 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(image_classes_.get(),
1339 Thread::Current(),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001340 runtime->GetClassLinker(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001341 &error_msg));
1342 CHECK(update.get() != nullptr) << error_msg; // TODO: Soft failure?
1343
1344 // Do the marking.
1345 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001346 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001347}
1348
Vladimir Marko07785bb2015-06-15 18:52:54 +01001349bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1350 Runtime* runtime = Runtime::Current();
1351 if (!runtime->IsAotCompiler()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001352 DCHECK(runtime->UseJitCompilation());
Vladimir Marko07785bb2015-06-15 18:52:54 +01001353 // Having the klass reference here implies that the klass is already loaded.
1354 return true;
1355 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001356 if (!IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001357 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1358 // loaded because we don't even know what class loader will be used to load them.
1359 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1360 return class_in_image;
1361 }
1362 std::string temp;
1363 const char* descriptor = klass->GetDescriptor(&temp);
1364 return IsImageClass(descriptor);
1365}
1366
Vladimir Marko492a7fa2016-06-01 18:38:43 +01001367void CompilerDriver::MarkForDexToDexCompilation(Thread* self, const MethodReference& method_ref) {
1368 MutexLock lock(self, dex_to_dex_references_lock_);
1369 // Since we're compiling one dex file at a time, we need to look for the
1370 // current dex file entry only at the end of dex_to_dex_references_.
1371 if (dex_to_dex_references_.empty() ||
1372 &dex_to_dex_references_.back().GetDexFile() != method_ref.dex_file) {
1373 dex_to_dex_references_.emplace_back(*method_ref.dex_file);
1374 }
1375 dex_to_dex_references_.back().GetMethodIndexes().SetBit(method_ref.dex_method_index);
1376}
1377
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001378bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(Handle<mirror::DexCache> dex_cache,
1379 uint32_t type_idx) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001380 bool result = false;
1381 if ((IsBootImage() &&
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001382 IsImageClass(dex_cache->GetDexFile()->StringDataByIdx(
1383 dex_cache->GetDexFile()->GetTypeId(type_idx).descriptor_idx_))) ||
Calin Juravleffc87072016-04-20 14:22:09 +01001384 Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001385 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1386 result = (resolved_class != nullptr);
1387 }
1388
1389 if (result) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001390 stats_->TypeInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001391 } else {
1392 stats_->TypeNotInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001393 }
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001394 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001395}
1396
1397bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
1398 uint32_t string_idx) {
1399 // See also Compiler::ResolveDexFile
1400
1401 bool result = false;
Calin Juravleffc87072016-04-20 14:22:09 +01001402 if (IsBootImage() || Runtime::Current()->UseJitCompilation()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001403 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001404 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001405 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1406 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1407 soa.Self(), dex_file, false)));
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001408 if (IsBootImage()) {
1409 // We resolve all const-string strings when building for the image.
1410 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1411 result = true;
1412 } else {
1413 // Just check whether the dex cache already has the string.
Calin Juravleffc87072016-04-20 14:22:09 +01001414 DCHECK(Runtime::Current()->UseJitCompilation());
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001415 result = (dex_cache->GetResolvedString(string_idx) != nullptr);
1416 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001417 }
1418 if (result) {
1419 stats_->StringInDexCache();
1420 } else {
1421 stats_->StringNotInDexCache();
1422 }
1423 return result;
1424}
1425
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001426bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx,
1427 Handle<mirror::DexCache> dex_cache,
1428 uint32_t type_idx) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001429 // Get type from dex cache assuming it was populated by the verifier
1430 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001431 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001432 stats_->TypeNeedsAccessCheck();
1433 return false; // Unknown class needs access checks.
1434 }
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001435 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001436 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1437 if (!is_accessible) {
1438 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1439 if (referrer_class == nullptr) {
1440 stats_->TypeNeedsAccessCheck();
1441 return false; // Incomplete referrer knowledge needs access check.
1442 }
1443 // Perform access check, will return true if access is ok or false if we're going to have to
1444 // check this at runtime (for example for class loaders).
1445 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001446 }
David Brazdil38f64d32016-01-18 17:13:41 +00001447 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001448 stats_->TypeDoesntNeedAccessCheck();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001449 } else {
1450 stats_->TypeNeedsAccessCheck();
1451 }
David Brazdil38f64d32016-01-18 17:13:41 +00001452 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001453}
1454
1455bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001456 Handle<mirror::DexCache> dex_cache,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001457 uint32_t type_idx,
1458 bool* finalizable) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001459 // Get type from dex cache assuming it was populated by the verifier.
1460 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001461 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001462 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001463 // Be conservative.
1464 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001465 return false; // Unknown class needs access checks.
1466 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001467 *finalizable = resolved_class->IsFinalizable();
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001468 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001469 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1470 if (!is_accessible) {
1471 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1472 if (referrer_class == nullptr) {
1473 stats_->TypeNeedsAccessCheck();
1474 return false; // Incomplete referrer knowledge needs access check.
1475 }
1476 // Perform access and instantiable checks, will return true if access is ok or false if we're
1477 // going to have to check this at runtime (for example for class loaders).
1478 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001479 }
David Brazdil38f64d32016-01-18 17:13:41 +00001480 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001481 if (result) {
1482 stats_->TypeDoesntNeedAccessCheck();
1483 } else {
1484 stats_->TypeNeedsAccessCheck();
1485 }
1486 return result;
1487}
1488
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001489bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
1490 bool* is_type_initialized, bool* use_direct_type_ptr,
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001491 uintptr_t* direct_type_ptr, bool* out_is_finalizable) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001492 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001493 Runtime* runtime = Runtime::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001494 mirror::DexCache* dex_cache = runtime->GetClassLinker()->FindDexCache(
1495 soa.Self(), dex_file, false);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001496 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1497 if (resolved_class == nullptr) {
1498 return false;
1499 }
Igor Murashkind6dee672014-10-16 18:36:16 -07001500 if (GetCompilerOptions().GetCompilePic()) {
1501 // Do not allow a direct class pointer to be used when compiling for position-independent
1502 return false;
1503 }
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001504 *out_is_finalizable = resolved_class->IsFinalizable();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001505 gc::Heap* heap = runtime->GetHeap();
1506 const bool compiling_boot = heap->IsCompilingBoot();
Alex Light6e183f22014-07-18 14:57:04 -07001507 const bool support_boot_image_fixup = GetSupportBootImageFixup();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001508 if (compiling_boot) {
1509 // boot -> boot class pointers.
1510 // True if the class is in the image at boot compiling time.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001511 const bool is_image_class = IsBootImage() && IsImageClass(
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001512 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
1513 // True if pc relative load works.
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001514 if (is_image_class && support_boot_image_fixup) {
1515 *is_type_initialized = resolved_class->IsInitialized();
1516 *use_direct_type_ptr = false;
1517 *direct_type_ptr = 0;
1518 return true;
1519 } else {
1520 return false;
1521 }
Calin Juravleffc87072016-04-20 14:22:09 +01001522 } else if (runtime->UseJitCompilation() && !heap->IsMovableObject(resolved_class)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001523 *is_type_initialized = resolved_class->IsInitialized();
1524 // If the class may move around, then don't embed it as a direct pointer.
1525 *use_direct_type_ptr = true;
1526 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1527 return true;
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001528 } else {
1529 // True if the class is in the image at app compiling time.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001530 const bool class_in_image = heap->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
Alex Light6e183f22014-07-18 14:57:04 -07001531 if (class_in_image && support_boot_image_fixup) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001532 // boot -> app class pointers.
1533 *is_type_initialized = resolved_class->IsInitialized();
Alex Lighta59dd802014-07-02 16:28:08 -07001534 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1535 *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001536 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1537 return true;
1538 } else {
1539 // app -> app class pointers.
1540 // Give up because app does not have an image and class
1541 // isn't created at compile time. TODO: implement this
1542 // if/when each app gets an image.
1543 return false;
1544 }
1545 }
1546}
1547
Fred Shihe7f82e22014-08-06 10:46:37 -07001548bool CompilerDriver::CanEmbedReferenceTypeInCode(ClassReference* ref,
1549 bool* use_direct_ptr,
1550 uintptr_t* direct_type_ptr) {
1551 CHECK(ref != nullptr);
1552 CHECK(use_direct_ptr != nullptr);
1553 CHECK(direct_type_ptr != nullptr);
1554
1555 ScopedObjectAccess soa(Thread::Current());
1556 mirror::Class* reference_class = mirror::Reference::GetJavaLangRefReference();
Andreas Gampe928f72b2014-09-09 19:53:48 -07001557 bool is_initialized = false;
Fred Shihe7f82e22014-08-06 10:46:37 -07001558 bool unused_finalizable;
1559 // Make sure we have a finished Reference class object before attempting to use it.
1560 if (!CanEmbedTypeInCode(*reference_class->GetDexCache()->GetDexFile(),
1561 reference_class->GetDexTypeIndex(), &is_initialized,
1562 use_direct_ptr, direct_type_ptr, &unused_finalizable) ||
1563 !is_initialized) {
1564 return false;
1565 }
1566 ref->first = &reference_class->GetDexFile();
1567 ref->second = reference_class->GetDexClassDefIndex();
1568 return true;
1569}
1570
1571uint32_t CompilerDriver::GetReferenceSlowFlagOffset() const {
1572 ScopedObjectAccess soa(Thread::Current());
1573 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1574 DCHECK(klass->IsInitialized());
1575 return klass->GetSlowPathFlagOffset().Uint32Value();
1576}
1577
1578uint32_t CompilerDriver::GetReferenceDisableFlagOffset() const {
1579 ScopedObjectAccess soa(Thread::Current());
1580 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1581 DCHECK(klass->IsInitialized());
1582 return klass->GetDisableIntrinsicFlagOffset().Uint32Value();
1583}
1584
Vladimir Marko20f85592015-03-19 10:07:02 +00001585DexCacheArraysLayout CompilerDriver::GetDexCacheArraysLayout(const DexFile* dex_file) {
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001586 return ContainsElement(GetDexFilesForOatFile(), dex_file)
Mathieu Chartierc7853442015-03-27 14:35:38 -07001587 ? DexCacheArraysLayout(GetInstructionSetPointerSize(instruction_set_), dex_file)
Vladimir Marko20f85592015-03-19 10:07:02 +00001588 : DexCacheArraysLayout();
1589}
1590
Vladimir Markobe0e5462014-02-26 11:24:15 +00001591void CompilerDriver::ProcessedInstanceField(bool resolved) {
1592 if (!resolved) {
1593 stats_->UnresolvedInstanceField();
1594 } else {
1595 stats_->ResolvedInstanceField();
1596 }
1597}
1598
1599void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1600 if (!resolved) {
1601 stats_->UnresolvedStaticField();
1602 } else if (local) {
1603 stats_->ResolvedLocalStaticField();
1604 } else {
1605 stats_->ResolvedStaticField();
1606 }
1607}
1608
Vladimir Markof096aad2014-01-23 15:51:58 +00001609void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
1610 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001611}
1612
Mathieu Chartierc7853442015-03-27 14:35:38 -07001613ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1614 const DexCompilationUnit* mUnit, bool is_put,
1615 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001616 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001617 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001618 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001619 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001620 {
Mathieu Chartier736b5602015-09-02 14:54:11 -07001621 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001622 Handle<mirror::ClassLoader> class_loader_handle(
1623 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartier736b5602015-09-02 14:54:11 -07001624 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001625 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001626 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001627 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001628 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001629 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001630 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001631 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001632 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001633 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001634 ProcessedInstanceField(can_link);
1635 return can_link ? resolved_field : nullptr;
1636}
1637
1638bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1639 bool is_put, MemberOffset* field_offset,
1640 bool* is_volatile) {
1641 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001642 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001643
Mathieu Chartierc7853442015-03-27 14:35:38 -07001644 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001645 // Conservative defaults.
1646 *is_volatile = true;
1647 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001648 return false;
1649 } else {
1650 *is_volatile = resolved_field->IsVolatile();
1651 *field_offset = resolved_field->GetOffset();
1652 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001653 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001654}
1655
Ian Rogers83883d72013-10-21 21:07:24 -07001656void CompilerDriver::GetCodeAndMethodForDirectCall(InvokeType* type, InvokeType sharp_type,
1657 bool no_guarantee_of_dex_cache_entry,
Igor Murashkind6dee672014-10-16 18:36:16 -07001658 const mirror::Class* referrer_class,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001659 ArtMethod* method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001660 int* stats_flags,
Ian Rogers83883d72013-10-21 21:07:24 -07001661 MethodReference* target_method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001662 uintptr_t* direct_code,
1663 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001664 // For direct and static methods compute possible direct_code and direct_method values, ie
1665 // an address for the Method* being invoked and an address of the code for that Method*.
1666 // For interface calls compute a value for direct_method that is the interface method being
1667 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001668 *direct_code = 0;
1669 *direct_method = 0;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001670 Runtime* const runtime = Runtime::Current();
1671 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001672 auto* cl = runtime->GetClassLinker();
1673 const auto pointer_size = cl->GetImagePointerSize();
Igor Murashkind6dee672014-10-16 18:36:16 -07001674 bool use_dex_cache = GetCompilerOptions().GetCompilePic(); // Off by default
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001675 const bool compiling_boot = heap->IsCompilingBoot();
Alex Lighta59dd802014-07-02 16:28:08 -07001676 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1677 const bool force_relocations = (compiling_boot ||
1678 GetCompilerOptions().GetIncludePatchInformation());
Elliott Hughes956af0f2014-12-11 14:34:28 -08001679 if (sharp_type != kStatic && sharp_type != kDirect) {
1680 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001681 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001682 // TODO: support patching on all architectures.
1683 use_dex_cache = use_dex_cache || (force_relocations && !support_boot_image_fixup_);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001684 mirror::Class* declaring_class = method->GetDeclaringClass();
1685 bool method_code_in_boot = declaring_class->GetClassLoader() == nullptr;
Ian Rogers83883d72013-10-21 21:07:24 -07001686 if (!use_dex_cache) {
1687 if (!method_code_in_boot) {
1688 use_dex_cache = true;
1689 } else {
Brian Carlstrom14247b62015-01-31 21:35:32 -08001690 bool has_clinit_trampoline =
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001691 method->IsStatic() && !declaring_class->IsInitialized();
1692 if (has_clinit_trampoline && declaring_class != referrer_class) {
Ian Rogers83883d72013-10-21 21:07:24 -07001693 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1694 // class.
1695 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001696 }
1697 }
Ian Rogers83883d72013-10-21 21:07:24 -07001698 }
Calin Juravleffc87072016-04-20 14:22:09 +01001699 if (runtime->UseJitCompilation()) {
Mathieu Chartier28a35882015-02-26 18:28:07 -08001700 // If we are the JIT, then don't allow a direct call to the interpreter bridge since this will
1701 // never be updated even after we compile the method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001702 if (cl->IsQuickToInterpreterBridge(
Mathieu Chartier28a35882015-02-26 18:28:07 -08001703 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)))) {
1704 use_dex_cache = true;
1705 }
1706 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001707 if (method_code_in_boot) {
1708 *stats_flags |= kFlagDirectCallToBoot | kFlagDirectMethodToBoot;
Ian Rogers83883d72013-10-21 21:07:24 -07001709 }
Alex Lighta59dd802014-07-02 16:28:08 -07001710 if (!use_dex_cache && force_relocations) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001711 bool is_in_image;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001712 if (IsBootImage()) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001713 is_in_image = IsImageClass(method->GetDeclaringClassDescriptor());
1714 } else {
1715 is_in_image = instruction_set_ != kX86 && instruction_set_ != kX86_64 &&
Vladimir Markoc08ab292015-06-22 14:35:42 +01001716 heap->FindSpaceFromObject(method->GetDeclaringClass(), false)->IsImageSpace() &&
1717 !cl->IsQuickToInterpreterBridge(
1718 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)));
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001719 }
1720 if (!is_in_image) {
Ian Rogers83883d72013-10-21 21:07:24 -07001721 // We can only branch directly to Methods that are resolved in the DexCache.
1722 // Otherwise we won't invoke the resolution trampoline.
1723 use_dex_cache = true;
1724 }
1725 }
1726 // The method is defined not within this dex file. We need a dex cache slot within the current
1727 // dex file or direct pointers.
1728 bool must_use_direct_pointers = false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001729 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
1730 if (target_method->dex_file == dex_cache->GetDexFile() &&
Calin Juravleffc87072016-04-20 14:22:09 +01001731 !(runtime->UseJitCompilation() && dex_cache->GetResolvedMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001732 method->GetDexMethodIndex(), pointer_size) == nullptr)) {
Ian Rogers83883d72013-10-21 21:07:24 -07001733 target_method->dex_method_index = method->GetDexMethodIndex();
1734 } else {
Ian Rogers83883d72013-10-21 21:07:24 -07001735 if (no_guarantee_of_dex_cache_entry) {
1736 // See if the method is also declared in this dex cache.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001737 uint32_t dex_method_idx = method->FindDexMethodIndexInOtherDexFile(
1738 *target_method->dex_file, target_method->dex_method_index);
Ian Rogers83883d72013-10-21 21:07:24 -07001739 if (dex_method_idx != DexFile::kDexNoIndex) {
1740 target_method->dex_method_index = dex_method_idx;
1741 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001742 if (force_relocations && !use_dex_cache) {
Jeff Hao49161ce2014-03-12 11:05:25 -07001743 target_method->dex_method_index = method->GetDexMethodIndex();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001744 target_method->dex_file = dex_cache->GetDexFile();
Jeff Hao49161ce2014-03-12 11:05:25 -07001745 }
Ian Rogers83883d72013-10-21 21:07:24 -07001746 must_use_direct_pointers = true;
1747 }
1748 }
1749 }
1750 if (use_dex_cache) {
1751 if (must_use_direct_pointers) {
1752 // Fail. Test above showed the only safe dispatch was via the dex cache, however, the direct
1753 // pointers are required as the dex cache lacks an appropriate entry.
1754 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1755 } else {
1756 *type = sharp_type;
1757 }
1758 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001759 bool method_in_image = false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001760 const std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
1761 for (gc::space::ImageSpace* image_space : image_spaces) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001762 const auto& method_section = image_space->GetImageHeader().GetMethodsSection();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001763 if (method_section.Contains(reinterpret_cast<uint8_t*>(method) - image_space->Begin())) {
1764 method_in_image = true;
1765 break;
1766 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001767 }
Calin Juravleffc87072016-04-20 14:22:09 +01001768 if (method_in_image || compiling_boot || runtime->UseJitCompilation()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001769 // 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 -08001770 // In the case where we are the JIT, we can always use direct pointers since we know where
1771 // the method and its code are / will be. We don't sharpen to interpreter bridge since we
1772 // check IsQuickToInterpreterBridge above.
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001773 CHECK(!method->IsAbstract());
Ian Rogers83883d72013-10-21 21:07:24 -07001774 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001775 *direct_method = force_relocations ? -1 : reinterpret_cast<uintptr_t>(method);
1776 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Brian Carlstrom14247b62015-01-31 21:35:32 -08001777 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001778 target_method->dex_method_index = method->GetDexMethodIndex();
1779 } else if (!must_use_direct_pointers) {
1780 // Set the code and rely on the dex cache for the method.
1781 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001782 if (force_relocations) {
1783 *direct_code = -1;
Brian Carlstrom14247b62015-01-31 21:35:32 -08001784 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Alex Lighta59dd802014-07-02 16:28:08 -07001785 target_method->dex_method_index = method->GetDexMethodIndex();
1786 } else {
1787 *direct_code = compiler_->GetEntryPointOf(method);
1788 }
Ian Rogers83883d72013-10-21 21:07:24 -07001789 } else {
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001790 // Direct pointers were required but none were available.
1791 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001792 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001793 }
1794}
1795
1796bool CompilerDriver::ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001797 bool update_stats, bool enable_devirtualization,
1798 InvokeType* invoke_type, MethodReference* target_method,
1799 int* vtable_idx, uintptr_t* direct_code,
1800 uintptr_t* direct_method) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001801 InvokeType orig_invoke_type = *invoke_type;
1802 int stats_flags = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001803 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof096aad2014-01-23 15:51:58 +00001804 // Try to resolve the method and compiling method's class.
Mathieu Chartier736b5602015-09-02 14:54:11 -07001805 StackHandleScope<2> hs(soa.Self());
1806 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001807 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1808 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001809 uint32_t method_idx = target_method->dex_method_index;
1810 ArtMethod* resolved_method = ResolveMethod(
1811 soa, dex_cache, class_loader, mUnit, method_idx, orig_invoke_type);
1812 auto h_referrer_class = hs.NewHandle(resolved_method != nullptr ?
1813 ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr);
Vladimir Markof096aad2014-01-23 15:51:58 +00001814 bool result = false;
1815 if (resolved_method != nullptr) {
1816 *vtable_idx = GetResolvedMethodVTableIndex(resolved_method, orig_invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001817
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001818 if (enable_devirtualization && mUnit->GetVerifiedMethod() != nullptr) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001819 const MethodReference* devirt_target = mUnit->GetVerifiedMethod()->GetDevirtTarget(dex_pc);
1820
1821 stats_flags = IsFastInvoke(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001822 soa, dex_cache, class_loader, mUnit, h_referrer_class.Get(), resolved_method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001823 invoke_type, target_method, devirt_target, direct_code, direct_method);
1824 result = stats_flags != 0;
1825 } else {
1826 // Devirtualization not enabled. Inline IsFastInvoke(), dropping the devirtualization parts.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001827 if (UNLIKELY(h_referrer_class.Get() == nullptr) ||
1828 UNLIKELY(!h_referrer_class->CanAccessResolvedMethod(resolved_method->GetDeclaringClass(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001829 resolved_method, dex_cache.Get(),
Vladimir Markof096aad2014-01-23 15:51:58 +00001830 target_method->dex_method_index)) ||
1831 *invoke_type == kSuper) {
1832 // Slow path. (Without devirtualization, all super calls go slow path as well.)
1833 } else {
1834 // Sharpening failed so generate a regular resolved method dispatch.
1835 stats_flags = kFlagMethodResolved;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001836 GetCodeAndMethodForDirectCall(
1837 invoke_type, *invoke_type, false, h_referrer_class.Get(), resolved_method, &stats_flags,
1838 target_method, direct_code, direct_method);
Vladimir Markof096aad2014-01-23 15:51:58 +00001839 result = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001840 }
1841 }
1842 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001843 if (!result) {
1844 // Conservative defaults.
1845 *vtable_idx = -1;
1846 *direct_code = 0u;
1847 *direct_method = 0u;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001848 }
1849 if (update_stats) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001850 ProcessedInvoke(orig_invoke_type, stats_flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001851 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001852 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001853}
1854
Vladimir Marko2730db02014-01-27 11:15:17 +00001855const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1856 uint32_t method_idx) const {
1857 MethodReference ref(dex_file, method_idx);
1858 return verification_results_->GetVerifiedMethod(ref);
1859}
1860
1861bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001862 if (!compiler_options_->IsVerificationEnabled()) {
1863 // If we didn't verify, every cast has to be treated as non-safe.
1864 return false;
1865 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001866 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1867 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001868 if (result) {
1869 stats_->SafeCast();
1870 } else {
1871 stats_->NotASafeCast();
1872 }
1873 return result;
1874}
1875
Mathieu Chartier90443472015-07-16 20:32:27 -07001876class CompilationVisitor {
1877 public:
1878 virtual ~CompilationVisitor() {}
1879 virtual void Visit(size_t index) = 0;
1880};
1881
Brian Carlstrom7940e442013-07-12 13:46:57 -07001882class ParallelCompilationManager {
1883 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001884 ParallelCompilationManager(ClassLinker* class_linker,
1885 jobject class_loader,
1886 CompilerDriver* compiler,
1887 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001888 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001889 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001890 : index_(0),
1891 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001892 class_loader_(class_loader),
1893 compiler_(compiler),
1894 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001895 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001896 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001897
1898 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001899 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001900 return class_linker_;
1901 }
1902
1903 jobject GetClassLoader() const {
1904 return class_loader_;
1905 }
1906
1907 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001908 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001909 return compiler_;
1910 }
1911
1912 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001913 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001914 return dex_file_;
1915 }
1916
Andreas Gampede7b4362014-07-28 18:38:57 -07001917 const std::vector<const DexFile*>& GetDexFiles() const {
1918 return dex_files_;
1919 }
1920
Mathieu Chartier90443472015-07-16 20:32:27 -07001921 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1922 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001923 Thread* self = Thread::Current();
1924 self->AssertNoPendingException();
1925 CHECK_GT(work_units, 0U);
1926
Ian Rogers3e5cf302014-05-20 16:40:37 -07001927 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001928 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001929 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001930 }
1931 thread_pool_->StartWorkers(self);
1932
1933 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1934 // thread destructor's called below perform join).
1935 CHECK_NE(self->GetState(), kRunnable);
1936
1937 // Wait for all the worker threads to finish.
1938 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001939
1940 // And stop the workers accepting jobs.
1941 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001942 }
1943
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001944 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001945 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001946 }
1947
Brian Carlstrom7940e442013-07-12 13:46:57 -07001948 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001949 class ForAllClosure : public Task {
1950 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001951 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001952 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001953 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001954 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001955
1956 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001957 while (true) {
1958 const size_t index = manager_->NextIndex();
1959 if (UNLIKELY(index >= end_)) {
1960 break;
1961 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001962 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001963 self->AssertNoPendingException();
1964 }
1965 }
1966
1967 virtual void Finalize() {
1968 delete this;
1969 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001970
Brian Carlstrom7940e442013-07-12 13:46:57 -07001971 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001972 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001973 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001974 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001975 };
1976
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001977 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001978 ClassLinker* const class_linker_;
1979 const jobject class_loader_;
1980 CompilerDriver* const compiler_;
1981 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001982 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001983 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001984
1985 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001986};
1987
Jeff Hao0e49b422013-11-08 12:16:56 -08001988// A fast version of SkipClass above if the class pointer is available
1989// that avoids the expensive FindInClassPath search.
1990static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001991 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001992 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001993 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1994 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001995 if (class_loader == nullptr) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001996 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1997 << dex_file.GetLocation() << " previously found in "
1998 << original_dex_file.GetLocation();
1999 }
2000 return true;
2001 }
2002 return false;
2003}
2004
Mathieu Chartier70b63482014-06-27 17:19:04 -07002005static void CheckAndClearResolveException(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002006 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07002007 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002008 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002009 std::string temp;
2010 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
2011 const char* expected_exceptions[] = {
2012 "Ljava/lang/IllegalAccessError;",
2013 "Ljava/lang/IncompatibleClassChangeError;",
2014 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07002015 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07002016 "Ljava/lang/NoClassDefFoundError;",
2017 "Ljava/lang/NoSuchFieldError;",
2018 "Ljava/lang/NoSuchMethodError;"
2019 };
2020 bool found = false;
2021 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
2022 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
2023 found = true;
2024 }
2025 }
2026 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07002027 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07002028 }
2029 self->ClearException();
2030}
2031
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002032bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file,
2033 uint16_t class_def_idx) const {
2034 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2035 const uint8_t* class_data = dex_file.GetClassData(class_def);
2036 if (class_data == nullptr) {
2037 // Empty class such as a marker interface.
2038 return false;
2039 }
2040 ClassDataItemIterator it(dex_file, class_data);
2041 while (it.HasNextStaticField()) {
2042 it.Next();
2043 }
2044 // We require a constructor barrier if there are final instance fields.
2045 while (it.HasNextInstanceField()) {
2046 if (it.MemberIsFinal()) {
2047 return true;
2048 }
2049 it.Next();
2050 }
2051 return false;
2052}
2053
Mathieu Chartier90443472015-07-16 20:32:27 -07002054class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
2055 public:
2056 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
2057 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002058
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002059 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002060 ATRACE_CALL();
2061 Thread* const self = Thread::Current();
2062 jobject jclass_loader = manager_->GetClassLoader();
2063 const DexFile& dex_file = *manager_->GetDexFile();
2064 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002065
Mathieu Chartier90443472015-07-16 20:32:27 -07002066 // If an instance field is final then we need to have a barrier on the return, static final
2067 // fields are assigned within the lock held for class initialization. Conservatively assume
2068 // constructor barriers are always required.
2069 bool requires_constructor_barrier = true;
2070
2071 // Method and Field are the worst. We can't resolve without either
2072 // context from the code use (to disambiguate virtual vs direct
2073 // method and instance vs static field) or from class
2074 // definitions. While the compiler will resolve what it can as it
2075 // needs it, here we try to resolve fields and methods used in class
2076 // definitions, since many of them many never be referenced by
2077 // generated code.
2078 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2079 ScopedObjectAccess soa(self);
2080 StackHandleScope<2> hs(soa.Self());
2081 Handle<mirror::ClassLoader> class_loader(
2082 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002083 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2084 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002085 // Resolve the class.
2086 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
2087 class_loader);
2088 bool resolve_fields_and_methods;
2089 if (klass == nullptr) {
2090 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
2091 // attempt to resolve methods and fields when there is no declaring class.
2092 CheckAndClearResolveException(soa.Self());
2093 resolve_fields_and_methods = false;
2094 } else {
2095 // We successfully resolved a class, should we skip it?
2096 if (SkipClass(jclass_loader, dex_file, klass)) {
2097 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002098 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002099 // We want to resolve the methods and fields eagerly.
2100 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07002101 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002102 // Note the class_data pointer advances through the headers,
2103 // static fields, instance fields, direct methods, and virtual
2104 // methods.
2105 const uint8_t* class_data = dex_file.GetClassData(class_def);
2106 if (class_data == nullptr) {
2107 // Empty class such as a marker interface.
2108 requires_constructor_barrier = false;
2109 } else {
2110 ClassDataItemIterator it(dex_file, class_data);
2111 while (it.HasNextStaticField()) {
2112 if (resolve_fields_and_methods) {
2113 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2114 dex_cache, class_loader, true);
2115 if (field == nullptr) {
2116 CheckAndClearResolveException(soa.Self());
2117 }
Ian Rogers68b56852014-08-29 20:19:11 -07002118 }
2119 it.Next();
2120 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002121 // We require a constructor barrier if there are final instance fields.
2122 requires_constructor_barrier = false;
2123 while (it.HasNextInstanceField()) {
2124 if (it.MemberIsFinal()) {
2125 requires_constructor_barrier = true;
2126 }
2127 if (resolve_fields_and_methods) {
2128 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2129 dex_cache, class_loader, false);
2130 if (field == nullptr) {
2131 CheckAndClearResolveException(soa.Self());
2132 }
Ian Rogers68b56852014-08-29 20:19:11 -07002133 }
2134 it.Next();
2135 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002136 if (resolve_fields_and_methods) {
2137 while (it.HasNextDirectMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002138 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002139 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2140 it.GetMethodInvokeType(class_def));
2141 if (method == nullptr) {
2142 CheckAndClearResolveException(soa.Self());
2143 }
2144 it.Next();
2145 }
2146 while (it.HasNextVirtualMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002147 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002148 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2149 it.GetMethodInvokeType(class_def));
2150 if (method == nullptr) {
2151 CheckAndClearResolveException(soa.Self());
2152 }
2153 it.Next();
2154 }
2155 DCHECK(!it.HasNext());
2156 }
2157 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002158 manager_->GetCompiler()->SetRequiresConstructorBarrier(self,
2159 &dex_file,
2160 class_def_index,
2161 requires_constructor_barrier);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002162 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002163
Mathieu Chartier90443472015-07-16 20:32:27 -07002164 private:
2165 const ParallelCompilationManager* const manager_;
2166};
2167
2168class ResolveTypeVisitor : public CompilationVisitor {
2169 public:
2170 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
2171 }
2172 virtual void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002173 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07002174 ScopedObjectAccess soa(Thread::Current());
2175 ClassLinker* class_linker = manager_->GetClassLinker();
2176 const DexFile& dex_file = *manager_->GetDexFile();
2177 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07002178 Handle<mirror::ClassLoader> class_loader(
2179 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002180 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
2181 dex_file,
Mathieu Chartierf284d442016-06-02 11:48:30 -07002182 class_loader.Get())));
Mathieu Chartier90443472015-07-16 20:32:27 -07002183 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002184
Mathieu Chartier90443472015-07-16 20:32:27 -07002185 if (klass == nullptr) {
2186 soa.Self()->AssertPendingException();
2187 mirror::Throwable* exception = soa.Self()->GetException();
2188 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
2189 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
2190 // There's little point continuing compilation if the heap is exhausted.
2191 LOG(FATAL) << "Out of memory during type resolution for compilation";
2192 }
2193 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07002194 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002195 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002196
2197 private:
2198 const ParallelCompilationManager* const manager_;
2199};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002200
Andreas Gampeace0dc12016-01-20 13:33:13 -08002201void CompilerDriver::ResolveDexFile(jobject class_loader,
2202 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002203 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002204 ThreadPool* thread_pool,
2205 size_t thread_count,
2206 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002207 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2208
2209 // TODO: we could resolve strings here, although the string table is largely filled with class
2210 // and method names.
2211
Andreas Gampede7b4362014-07-28 18:38:57 -07002212 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2213 thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002214 if (IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002215 // For images we resolve all types, such as array, whereas for applications just those with
2216 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002217 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002218 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002219 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002220 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002221
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002222 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002223 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002224 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002225}
2226
Andreas Gampeace0dc12016-01-20 13:33:13 -08002227void CompilerDriver::SetVerified(jobject class_loader,
2228 const std::vector<const DexFile*>& dex_files,
2229 TimingLogger* timings) {
2230 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07002231 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002232 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002233 SetVerifiedDexFile(class_loader,
2234 *dex_file,
2235 dex_files,
2236 parallel_thread_pool_.get(),
2237 parallel_thread_count_,
2238 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002239 }
2240}
2241
Andreas Gampeace0dc12016-01-20 13:33:13 -08002242void CompilerDriver::Verify(jobject class_loader,
2243 const std::vector<const DexFile*>& dex_files,
2244 TimingLogger* timings) {
2245 // Note: verification should not be pulling in classes anymore when compiling the boot image,
2246 // as all should have been resolved before. As such, doing this in parallel should still
2247 // be deterministic.
Mathieu Chartier90443472015-07-16 20:32:27 -07002248 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002249 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002250 VerifyDexFile(class_loader,
2251 *dex_file,
2252 dex_files,
2253 parallel_thread_pool_.get(),
2254 parallel_thread_count_,
2255 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002256 }
2257}
2258
Mathieu Chartier90443472015-07-16 20:32:27 -07002259class VerifyClassVisitor : public CompilationVisitor {
2260 public:
Andreas Gampe7fe30232016-03-25 16:58:00 -07002261 VerifyClassVisitor(const ParallelCompilationManager* manager, LogSeverity log_level)
2262 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002263
Mathieu Chartier90443472015-07-16 20:32:27 -07002264 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2265 ATRACE_CALL();
2266 ScopedObjectAccess soa(Thread::Current());
2267 const DexFile& dex_file = *manager_->GetDexFile();
Mathieu Chartiera8077802016-03-16 19:08:31 -07002268 if (!manager_->GetCompiler()->ShouldVerifyClassBasedOnProfile(dex_file, class_def_index)) {
2269 // Skip verification since the class is not in the profile.
2270 return;
2271 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002272 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2273 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2274 ClassLinker* class_linker = manager_->GetClassLinker();
2275 jobject jclass_loader = manager_->GetClassLoader();
2276 StackHandleScope<3> hs(soa.Self());
2277 Handle<mirror::ClassLoader> class_loader(
2278 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2279 Handle<mirror::Class> klass(
2280 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2281 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002282 CHECK(soa.Self()->IsExceptionPending());
2283 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07002284
2285 /*
2286 * At compile time, we can still structurally verify the class even if FindClass fails.
2287 * This is to ensure the class is structurally sound for compilation. An unsound class
2288 * will be rejected by the verifier and later skipped during compilation in the compiler.
2289 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002290 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2291 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002292 std::string error_msg;
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002293 if (verifier::MethodVerifier::VerifyClass(soa.Self(),
2294 &dex_file,
2295 dex_cache,
2296 class_loader,
David Brazdil15fc7292016-09-02 14:13:18 +01002297 class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08002298 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002299 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07002300 log_level_,
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002301 &error_msg) ==
Mathieu Chartier90443472015-07-16 20:32:27 -07002302 verifier::MethodVerifier::kHardFailure) {
2303 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2304 << " because: " << error_msg;
2305 manager_->GetCompiler()->SetHadHardVerifierFailure();
2306 }
2307 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
2308 CHECK(klass->IsResolved()) << PrettyClass(klass.Get());
Andreas Gampe7fe30232016-03-25 16:58:00 -07002309 class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002310
2311 if (klass->IsErroneous()) {
2312 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2313 CHECK(soa.Self()->IsExceptionPending());
2314 soa.Self()->ClearException();
2315 manager_->GetCompiler()->SetHadHardVerifierFailure();
2316 }
2317
2318 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
2319 << PrettyDescriptor(klass.Get()) << ": state=" << klass->GetStatus();
2320
2321 // It is *very* problematic if there are verification errors in the boot classpath. For example,
2322 // we rely on things working OK without verification when the decryption dialog is brought up.
2323 // So abort in a debug build if we find this violated.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002324 DCHECK(!manager_->GetCompiler()->IsBootImage() || klass->IsVerified())
2325 << "Boot classpath class " << PrettyClass(klass.Get()) << " failed to fully verify.";
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002326 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002327 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002328 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002329
2330 private:
2331 const ParallelCompilationManager* const manager_;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002332 const LogSeverity log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002333};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002334
Andreas Gampeace0dc12016-01-20 13:33:13 -08002335void CompilerDriver::VerifyDexFile(jobject class_loader,
2336 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002337 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002338 ThreadPool* thread_pool,
2339 size_t thread_count,
2340 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002341 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002342 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002343 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2344 thread_pool);
Andreas Gampe7fe30232016-03-25 16:58:00 -07002345 LogSeverity log_level = GetCompilerOptions().AbortOnHardVerifierFailure()
2346 ? LogSeverity::INTERNAL_FATAL
2347 : LogSeverity::WARNING;
2348 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002349 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002350}
2351
Mathieu Chartier90443472015-07-16 20:32:27 -07002352class SetVerifiedClassVisitor : public CompilationVisitor {
2353 public:
2354 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2355
2356 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2357 ATRACE_CALL();
2358 ScopedObjectAccess soa(Thread::Current());
2359 const DexFile& dex_file = *manager_->GetDexFile();
2360 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2361 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2362 ClassLinker* class_linker = manager_->GetClassLinker();
2363 jobject jclass_loader = manager_->GetClassLoader();
2364 StackHandleScope<3> hs(soa.Self());
2365 Handle<mirror::ClassLoader> class_loader(
2366 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2367 Handle<mirror::Class> klass(
2368 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2369 // Class might have failed resolution. Then don't set it to verified.
2370 if (klass.Get() != nullptr) {
2371 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2372 // very wrong.
2373 if (klass->IsResolved()) {
2374 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
2375 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2376 // Set class status to verified.
2377 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self());
2378 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2379 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002380 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002381 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002382 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002383 }
2384 // Record the final class status if necessary.
2385 ClassReference ref(manager_->GetDexFile(), class_def_index);
2386 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002387 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002388 } else {
2389 Thread* self = soa.Self();
2390 DCHECK(self->IsExceptionPending());
2391 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002392 }
2393 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002394
2395 private:
2396 const ParallelCompilationManager* const manager_;
2397};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002398
Andreas Gampeace0dc12016-01-20 13:33:13 -08002399void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2400 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002401 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002402 ThreadPool* thread_pool,
2403 size_t thread_count,
2404 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002405 TimingLogger::ScopedTiming t("Verify Dex File", timings);
2406 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2407 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2408 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002409 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002410 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002411}
2412
Mathieu Chartier90443472015-07-16 20:32:27 -07002413class InitializeClassVisitor : public CompilationVisitor {
2414 public:
2415 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002416
Mathieu Chartier90443472015-07-16 20:32:27 -07002417 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2418 ATRACE_CALL();
2419 jobject jclass_loader = manager_->GetClassLoader();
2420 const DexFile& dex_file = *manager_->GetDexFile();
2421 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2422 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2423 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002424
Mathieu Chartier90443472015-07-16 20:32:27 -07002425 ScopedObjectAccess soa(Thread::Current());
2426 StackHandleScope<3> hs(soa.Self());
2427 Handle<mirror::ClassLoader> class_loader(
2428 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2429 Handle<mirror::Class> klass(
2430 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2431
2432 if (klass.Get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) {
2433 // Only try to initialize classes that were successfully verified.
2434 if (klass->IsVerified()) {
2435 // Attempt to initialize the class but bail if we either need to initialize the super-class
2436 // or static fields.
2437 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002438 if (!klass->IsInitialized()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002439 // We don't want non-trivial class initialization occurring on multiple threads due to
2440 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2441 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2442 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2443 // after first initializing its parents, whose locks are acquired. This leads to a
2444 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2445 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2446 // than use a special Object for the purpose we use the Class of java.lang.Class.
2447 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2448 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2449 // Attempt to initialize allowing initialization of parent classes but still not static
2450 // fields.
2451 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
2452 if (!klass->IsInitialized()) {
2453 // We need to initialize static fields, we only do this for image classes that aren't
2454 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002455 bool can_init_static_fields = manager_->GetCompiler()->IsBootImage() &&
Mathieu Chartier90443472015-07-16 20:32:27 -07002456 manager_->GetCompiler()->IsImageClass(descriptor) &&
2457 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2458 if (can_init_static_fields) {
2459 VLOG(compiler) << "Initializing: " << descriptor;
2460 // TODO multithreading support. We should ensure the current compilation thread has
2461 // exclusive access to the runtime and the transaction. To achieve this, we could use
2462 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2463 // checks in Thread::AssertThreadSuspensionIsAllowable.
2464 Runtime* const runtime = Runtime::Current();
2465 Transaction transaction;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002466
Mathieu Chartier90443472015-07-16 20:32:27 -07002467 // Run the class initializer in transaction mode.
2468 runtime->EnterTransactionMode(&transaction);
2469 const mirror::Class::Status old_status = klass->GetStatus();
2470 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2471 true);
2472 // TODO we detach transaction from runtime to indicate we quit the transactional
2473 // mode which prevents the GC from visiting objects modified during the transaction.
2474 // Ensure GC is not run so don't access freed objects when aborting transaction.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002475
Mathieu Chartier90443472015-07-16 20:32:27 -07002476 ScopedAssertNoThreadSuspension ants(soa.Self(), "Transaction end");
2477 runtime->ExitTransactionMode();
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002478
Mathieu Chartier90443472015-07-16 20:32:27 -07002479 if (!success) {
2480 CHECK(soa.Self()->IsExceptionPending());
2481 mirror::Throwable* exception = soa.Self()->GetException();
2482 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2483 << exception->Dump();
2484 std::ostream* file_log = manager_->GetCompiler()->
2485 GetCompilerOptions().GetInitFailureOutput();
2486 if (file_log != nullptr) {
2487 *file_log << descriptor << "\n";
2488 *file_log << exception->Dump() << "\n";
2489 }
2490 soa.Self()->ClearException();
2491 transaction.Rollback();
2492 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002493 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002494 }
2495 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002496 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002497 }
2498 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002499 // Record the final class status if necessary.
2500 ClassReference ref(manager_->GetDexFile(), class_def_index);
2501 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002502 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002503 // Clear any class not found or verification exceptions.
2504 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002505 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002506
2507 private:
2508 const ParallelCompilationManager* const manager_;
2509};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002510
Andreas Gampeace0dc12016-01-20 13:33:13 -08002511void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2512 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002513 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002514 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002515 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002516
2517 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2518 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2519 ThreadPool* init_thread_pool = force_determinism
2520 ? single_thread_pool_.get()
2521 : parallel_thread_pool_.get();
2522 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2523
Brian Carlstrom7940e442013-07-12 13:46:57 -07002524 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002525 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002526 init_thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002527 if (IsBootImage()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002528 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002529 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002530 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002531 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002532 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002533}
2534
Mathieu Chartier91288d82016-04-28 09:44:54 -07002535class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002536 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002537 virtual bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier91288d82016-04-28 09:44:54 -07002538 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2539 return true;
2540 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002541 if (klass->IsArrayClass()) {
2542 StackHandleScope<1> hs(Thread::Current());
2543 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(),
2544 hs.NewHandle(klass),
2545 true,
2546 true);
2547 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002548 // Create the conflict tables.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002549 FillIMTAndConflictTables(klass);
Nicolas Geoffray88f288e2016-06-29 08:17:52 +00002550 return true;
Nelli Kimbadee982016-05-13 13:08:53 +03002551 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002552
2553 private:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002554 void FillIMTAndConflictTables(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002555 if (!klass->ShouldHaveImt()) {
2556 return;
2557 }
2558 if (visited_classes_.find(klass) != visited_classes_.end()) {
2559 return;
2560 }
2561 if (klass->HasSuperClass()) {
2562 FillIMTAndConflictTables(klass->GetSuperClass());
2563 }
2564 if (!klass->IsTemp()) {
2565 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
2566 }
2567 visited_classes_.insert(klass);
2568 }
2569
2570 std::set<mirror::Class*> visited_classes_;
Mathieu Chartier085a0722016-04-01 17:33:31 -07002571};
2572
Brian Carlstrom7940e442013-07-12 13:46:57 -07002573void CompilerDriver::InitializeClasses(jobject class_loader,
2574 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002575 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002576 for (size_t i = 0; i != dex_files.size(); ++i) {
2577 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002578 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002579 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002580 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002581 if (boot_image_ || app_image_) {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002582 // Make sure that we call EnsureIntiailized on all the array classes to call
2583 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2584 // changed at runtime resulting in more dirty image pages.
Mathieu Chartier91288d82016-04-28 09:44:54 -07002585 // Also create conflict tables.
2586 // Only useful if we are compiling an image (image_classes_ is not null).
Mathieu Chartier085a0722016-04-01 17:33:31 -07002587 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier91288d82016-04-28 09:44:54 -07002588 InitializeArrayClassesAndCreateConflictTablesVisitor visitor;
2589 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
Mathieu Chartier085a0722016-04-01 17:33:31 -07002590 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002591 if (IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002592 // Prune garbage objects created during aborted transactions.
2593 Runtime::Current()->GetHeap()->CollectGarbage(true);
2594 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002595}
2596
Andreas Gampeace0dc12016-01-20 13:33:13 -08002597void CompilerDriver::Compile(jobject class_loader,
2598 const std::vector<const DexFile*>& dex_files,
2599 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002600 if (kDebugProfileGuidedCompilation) {
2601 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2602 ((profile_compilation_info_ == nullptr)
2603 ? "null"
2604 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002605 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002606
2607 DCHECK(current_dex_to_dex_methods_ == nullptr);
2608 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002609 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002610 CompileDexFile(class_loader,
2611 *dex_file,
2612 dex_files,
2613 parallel_thread_pool_.get(),
2614 parallel_thread_count_,
2615 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002616 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2617 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2618 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002619 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002620 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002621
2622 ArrayRef<DexFileMethodSet> dex_to_dex_references;
2623 {
2624 // From this point on, we shall not modify dex_to_dex_references_, so
2625 // just grab a reference to it that we use without holding the mutex.
2626 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
2627 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
2628 }
2629 for (const auto& method_set : dex_to_dex_references) {
2630 current_dex_to_dex_methods_ = &method_set.GetMethodIndexes();
2631 CompileDexFile(class_loader,
2632 method_set.GetDexFile(),
2633 dex_files,
2634 parallel_thread_pool_.get(),
2635 parallel_thread_count_,
2636 timings);
2637 }
2638 current_dex_to_dex_methods_ = nullptr;
2639
Andreas Gampe8d295f82015-01-20 14:50:21 -08002640 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002641}
2642
Mathieu Chartier90443472015-07-16 20:32:27 -07002643class CompileClassVisitor : public CompilationVisitor {
2644 public:
2645 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2646
2647 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2648 ATRACE_CALL();
2649 const DexFile& dex_file = *manager_->GetDexFile();
2650 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2651 ClassLinker* class_linker = manager_->GetClassLinker();
2652 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002653 ClassReference ref(&dex_file, class_def_index);
2654 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2655 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002656 return;
2657 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002658 // Use a scoped object access to perform to the quick SkipClass check.
2659 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2660 ScopedObjectAccess soa(Thread::Current());
2661 StackHandleScope<3> hs(soa.Self());
2662 Handle<mirror::ClassLoader> class_loader(
2663 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2664 Handle<mirror::Class> klass(
2665 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2666 Handle<mirror::DexCache> dex_cache;
2667 if (klass.Get() == nullptr) {
2668 soa.Self()->AssertPendingException();
2669 soa.Self()->ClearException();
2670 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2671 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2672 return;
2673 } else {
2674 dex_cache = hs.NewHandle(klass->GetDexCache());
2675 }
2676
Mathieu Chartier90443472015-07-16 20:32:27 -07002677 const uint8_t* class_data = dex_file.GetClassData(class_def);
2678 if (class_data == nullptr) {
2679 // empty class, probably a marker interface
2680 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002681 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002682
Mathieu Chartier736b5602015-09-02 14:54:11 -07002683 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002684 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002685
Mathieu Chartier90443472015-07-16 20:32:27 -07002686 CompilerDriver* const driver = manager_->GetCompiler();
2687
2688 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002689 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002690 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002691
Mathieu Chartier90443472015-07-16 20:32:27 -07002692 ClassDataItemIterator it(dex_file, class_data);
2693 // Skip fields
2694 while (it.HasNextStaticField()) {
2695 it.Next();
2696 }
2697 while (it.HasNextInstanceField()) {
2698 it.Next();
2699 }
2700
2701 bool compilation_enabled = driver->IsClassToCompile(
2702 dex_file.StringByTypeIdx(class_def.class_idx_));
2703
2704 // Compile direct methods
2705 int64_t previous_direct_method_idx = -1;
2706 while (it.HasNextDirectMethod()) {
2707 uint32_t method_idx = it.GetMemberIndex();
2708 if (method_idx == previous_direct_method_idx) {
2709 // smali can create dex files with two encoded_methods sharing the same method_idx
2710 // http://code.google.com/p/smali/issues/detail?id=119
2711 it.Next();
2712 continue;
2713 }
2714 previous_direct_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002715 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002716 it.GetMethodInvokeType(class_def), class_def_index,
2717 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002718 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002719 it.Next();
2720 }
2721 // Compile virtual methods
2722 int64_t previous_virtual_method_idx = -1;
2723 while (it.HasNextVirtualMethod()) {
2724 uint32_t method_idx = it.GetMemberIndex();
2725 if (method_idx == previous_virtual_method_idx) {
2726 // smali can create dex files with two encoded_methods sharing the same method_idx
2727 // http://code.google.com/p/smali/issues/detail?id=119
2728 it.Next();
2729 continue;
2730 }
2731 previous_virtual_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002732 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002733 it.GetMethodInvokeType(class_def), class_def_index,
2734 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002735 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002736 it.Next();
2737 }
2738 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002739 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002740
2741 private:
2742 const ParallelCompilationManager* const manager_;
2743};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002744
Andreas Gampeace0dc12016-01-20 13:33:13 -08002745void CompilerDriver::CompileDexFile(jobject class_loader,
2746 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002747 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002748 ThreadPool* thread_pool,
2749 size_t thread_count,
2750 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002751 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002752 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002753 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002754 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002755 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002756}
2757
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002758void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2759 CompiledMethod* const compiled_method,
2760 size_t non_relative_linker_patch_count) {
2761 DCHECK(GetCompiledMethod(method_ref) == nullptr)
2762 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
2763 {
2764 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2765 compiled_methods_.Put(method_ref, compiled_method);
2766 non_relative_linker_patch_count_ += non_relative_linker_patch_count;
Ian Rogersa4a3f402014-10-20 18:10:34 -07002767 }
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002768 DCHECK(GetCompiledMethod(method_ref) != nullptr)
2769 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002770}
2771
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002772void CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2773 CompiledMethod* compiled_method = nullptr;
2774 {
2775 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2776 auto it = compiled_methods_.find(method_ref);
2777 if (it != compiled_methods_.end()) {
2778 compiled_method = it->second;
2779 compiled_methods_.erase(it);
2780 }
2781 }
2782 if (compiled_method != nullptr) {
2783 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, compiled_method);
2784 }
2785}
2786
Brian Carlstrom7940e442013-07-12 13:46:57 -07002787CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
2788 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2789 ClassTable::const_iterator it = compiled_classes_.find(ref);
2790 if (it == compiled_classes_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002791 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002792 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002793 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002794 return it->second;
2795}
2796
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002797void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2798 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2799 auto it = compiled_classes_.find(ref);
2800 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2801 // An entry doesn't exist or the status is lower than the new status.
2802 if (it != compiled_classes_.end()) {
2803 CHECK_GT(status, it->second->GetStatus());
2804 delete it->second;
2805 }
2806 switch (status) {
2807 case mirror::Class::kStatusNotReady:
2808 case mirror::Class::kStatusError:
2809 case mirror::Class::kStatusRetryVerificationAtRuntime:
2810 case mirror::Class::kStatusVerified:
2811 case mirror::Class::kStatusInitialized:
Mathieu Chartiera8077802016-03-16 19:08:31 -07002812 case mirror::Class::kStatusResolved:
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002813 break; // Expected states.
2814 default:
2815 LOG(FATAL) << "Unexpected class status for class "
2816 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2817 << " of " << status;
2818 }
2819 CompiledClass* compiled_class = new CompiledClass(status);
2820 compiled_classes_.Overwrite(ref, compiled_class);
2821 }
2822}
2823
Brian Carlstrom7940e442013-07-12 13:46:57 -07002824CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2825 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2826 MethodTable::const_iterator it = compiled_methods_.find(ref);
2827 if (it == compiled_methods_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002828 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002829 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002830 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002831 return it->second;
2832}
2833
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002834bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2835 uint16_t class_def_idx,
2836 const DexFile& dex_file) const {
2837 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2838 if (verified_method != nullptr) {
2839 return !verified_method->HasVerificationFailures();
2840 }
2841
2842 // If we can't find verification metadata, check if this is a system class (we trust that system
2843 // classes have their methods verified). If it's not, be conservative and assume the method
2844 // has not been verified successfully.
2845
2846 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2847 // even if methods are not found in the verification cache.
2848 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2849 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2850 Thread* self = Thread::Current();
2851 ScopedObjectAccess soa(self);
2852 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2853 if (!is_system_class) {
2854 self->ClearException();
2855 }
2856 return is_system_class;
2857}
2858
Vladimir Markof4da6752014-08-01 19:04:18 +01002859size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
2860 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2861 return non_relative_linker_patch_count_;
2862}
2863
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002864void CompilerDriver::SetRequiresConstructorBarrier(Thread* self,
2865 const DexFile* dex_file,
2866 uint16_t class_def_index,
2867 bool requires) {
2868 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2869 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002870}
2871
Mathieu Chartier371bd832016-04-07 10:19:48 -07002872bool CompilerDriver::RequiresConstructorBarrier(Thread* self,
2873 const DexFile* dex_file,
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002874 uint16_t class_def_index) {
2875 ClassReference class_ref(dex_file, class_def_index);
2876 {
2877 ReaderMutexLock mu(self, requires_constructor_barrier_lock_);
2878 auto it = requires_constructor_barrier_.find(class_ref);
2879 if (it != requires_constructor_barrier_.end()) {
2880 return it->second;
2881 }
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002882 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002883 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2884 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index);
2885 requires_constructor_barrier_.emplace(class_ref, requires);
2886 return requires;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002887}
2888
Andreas Gampe8d295f82015-01-20 14:50:21 -08002889std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002890 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002891 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002892 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002893 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002894 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002895#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002896 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002897 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2898 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002899 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2900 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002901#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002902 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002903 return oss.str();
2904}
2905
Jeff Hao848f70a2014-01-15 13:49:50 -08002906bool CompilerDriver::IsStringTypeIndex(uint16_t type_index, const DexFile* dex_file) {
2907 const char* type = dex_file->GetTypeDescriptor(dex_file->GetTypeId(type_index));
2908 return strcmp(type, "Ljava/lang/String;") == 0;
2909}
2910
2911bool CompilerDriver::IsStringInit(uint32_t method_index, const DexFile* dex_file, int32_t* offset) {
2912 DexFileMethodInliner* inliner = GetMethodInlinerMap()->GetMethodInliner(dex_file);
Igor Murashkin9d4b6da2016-07-29 09:51:58 -07002913 const PointerSize pointer_size = InstructionSetPointerSize(GetInstructionSet());
Jeff Hao848f70a2014-01-15 13:49:50 -08002914 *offset = inliner->GetOffsetForStringInit(method_index, pointer_size);
2915 return inliner->IsStringInitMethodIndex(method_index);
2916}
2917
Jeff Haodcdc85b2015-12-04 14:06:18 -08002918bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
2919 const DexFile* inlined_into) const {
2920 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
2921 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00002922 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
2923 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002924 return false;
2925 }
2926
2927 return true;
2928}
2929
Andreas Gampeace0dc12016-01-20 13:33:13 -08002930void CompilerDriver::InitializeThreadPools() {
2931 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2932 parallel_thread_pool_.reset(
2933 new ThreadPool("Compiler driver thread pool", parallel_count));
2934 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2935}
2936
2937void CompilerDriver::FreeThreadPools() {
2938 parallel_thread_pool_.reset();
2939 single_thread_pool_.reset();
2940}
2941
Brian Carlstrom7940e442013-07-12 13:46:57 -07002942} // namespace art