compiler_driver.cc revision 84c8432726299e8884215874d83958f55d5b2cd7
1/* 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 19#include <unordered_set> 20#include <vector> 21#include <unistd.h> 22 23#ifndef __APPLE__ 24#include <malloc.h> // For mallinfo 25#endif 26 27#include "android-base/strings.h" 28 29#include "art_field-inl.h" 30#include "art_method-inl.h" 31#include "base/arena_allocator.h" 32#include "base/array_ref.h" 33#include "base/bit_vector.h" 34#include "base/enums.h" 35#include "base/stl_util.h" 36#include "base/systrace.h" 37#include "base/time_utils.h" 38#include "base/timing_logger.h" 39#include "class_linker-inl.h" 40#include "compiled_method.h" 41#include "compiler.h" 42#include "compiler_callbacks.h" 43#include "compiler_driver-inl.h" 44#include "dex_compilation_unit.h" 45#include "dex_file-inl.h" 46#include "dex_instruction-inl.h" 47#include "dex/dex_to_dex_compiler.h" 48#include "dex/verification_results.h" 49#include "dex/verified_method.h" 50#include "driver/compiler_options.h" 51#include "intrinsics_enum.h" 52#include "jni_internal.h" 53#include "object_lock.h" 54#include "runtime.h" 55#include "gc/accounting/card_table-inl.h" 56#include "gc/accounting/heap_bitmap.h" 57#include "gc/space/image_space.h" 58#include "gc/space/space.h" 59#include "mirror/class_loader.h" 60#include "mirror/class-inl.h" 61#include "mirror/dex_cache-inl.h" 62#include "mirror/object-inl.h" 63#include "mirror/object-refvisitor-inl.h" 64#include "mirror/object_array-inl.h" 65#include "mirror/throwable.h" 66#include "scoped_thread_state_change-inl.h" 67#include "ScopedLocalRef.h" 68#include "handle_scope-inl.h" 69#include "thread.h" 70#include "thread_list.h" 71#include "thread_pool.h" 72#include "trampolines/trampoline_compiler.h" 73#include "transaction.h" 74#include "utils/atomic_method_ref_map-inl.h" 75#include "utils/dex_cache_arrays_layout-inl.h" 76#include "utils/swap_space.h" 77#include "vdex_file.h" 78#include "verifier/method_verifier.h" 79#include "verifier/method_verifier-inl.h" 80#include "verifier/verifier_deps.h" 81#include "verifier/verifier_enums.h" 82 83namespace art { 84 85static constexpr bool kTimeCompileMethod = !kIsDebugBuild; 86 87// Print additional info during profile guided compilation. 88static constexpr bool kDebugProfileGuidedCompilation = false; 89 90static double Percentage(size_t x, size_t y) { 91 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y)); 92} 93 94static void DumpStat(size_t x, size_t y, const char* str) { 95 if (x == 0 && y == 0) { 96 return; 97 } 98 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases"; 99} 100 101class CompilerDriver::AOTCompilationStats { 102 public: 103 AOTCompilationStats() 104 : stats_lock_("AOT compilation statistics lock"), 105 resolved_types_(0), unresolved_types_(0), 106 resolved_instance_fields_(0), unresolved_instance_fields_(0), 107 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0), 108 type_based_devirtualization_(0), 109 safe_casts_(0), not_safe_casts_(0) { 110 for (size_t i = 0; i <= kMaxInvokeType; i++) { 111 resolved_methods_[i] = 0; 112 unresolved_methods_[i] = 0; 113 virtual_made_direct_[i] = 0; 114 direct_calls_to_boot_[i] = 0; 115 direct_methods_to_boot_[i] = 0; 116 } 117 } 118 119 void Dump() { 120 DumpStat(resolved_types_, unresolved_types_, "types resolved"); 121 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved"); 122 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_, 123 "static fields resolved"); 124 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_, 125 "static fields local to a class"); 126 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information"); 127 // Note, the code below subtracts the stat value so that when added to the stat value we have 128 // 100% of samples. TODO: clean this up. 129 DumpStat(type_based_devirtualization_, 130 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] + 131 resolved_methods_[kInterface] + unresolved_methods_[kInterface] - 132 type_based_devirtualization_, 133 "virtual/interface calls made direct based on type information"); 134 135 for (size_t i = 0; i <= kMaxInvokeType; i++) { 136 std::ostringstream oss; 137 oss << static_cast<InvokeType>(i) << " methods were AOT resolved"; 138 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str()); 139 if (virtual_made_direct_[i] > 0) { 140 std::ostringstream oss2; 141 oss2 << static_cast<InvokeType>(i) << " methods made direct"; 142 DumpStat(virtual_made_direct_[i], 143 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i], 144 oss2.str().c_str()); 145 } 146 if (direct_calls_to_boot_[i] > 0) { 147 std::ostringstream oss2; 148 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot"; 149 DumpStat(direct_calls_to_boot_[i], 150 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i], 151 oss2.str().c_str()); 152 } 153 if (direct_methods_to_boot_[i] > 0) { 154 std::ostringstream oss2; 155 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot"; 156 DumpStat(direct_methods_to_boot_[i], 157 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i], 158 oss2.str().c_str()); 159 } 160 } 161 } 162 163// Allow lossy statistics in non-debug builds. 164#ifndef NDEBUG 165#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_) 166#else 167#define STATS_LOCK() 168#endif 169 170 void TypeDoesntNeedAccessCheck() REQUIRES(!stats_lock_) { 171 STATS_LOCK(); 172 resolved_types_++; 173 } 174 175 void TypeNeedsAccessCheck() REQUIRES(!stats_lock_) { 176 STATS_LOCK(); 177 unresolved_types_++; 178 } 179 180 void ResolvedInstanceField() REQUIRES(!stats_lock_) { 181 STATS_LOCK(); 182 resolved_instance_fields_++; 183 } 184 185 void UnresolvedInstanceField() REQUIRES(!stats_lock_) { 186 STATS_LOCK(); 187 unresolved_instance_fields_++; 188 } 189 190 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) { 191 STATS_LOCK(); 192 resolved_local_static_fields_++; 193 } 194 195 void ResolvedStaticField() REQUIRES(!stats_lock_) { 196 STATS_LOCK(); 197 resolved_static_fields_++; 198 } 199 200 void UnresolvedStaticField() REQUIRES(!stats_lock_) { 201 STATS_LOCK(); 202 unresolved_static_fields_++; 203 } 204 205 // Indicate that type information from the verifier led to devirtualization. 206 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) { 207 STATS_LOCK(); 208 type_based_devirtualization_++; 209 } 210 211 // A check-cast could be eliminated due to verifier type analysis. 212 void SafeCast() REQUIRES(!stats_lock_) { 213 STATS_LOCK(); 214 safe_casts_++; 215 } 216 217 // A check-cast couldn't be eliminated due to verifier type analysis. 218 void NotASafeCast() REQUIRES(!stats_lock_) { 219 STATS_LOCK(); 220 not_safe_casts_++; 221 } 222 223 private: 224 Mutex stats_lock_; 225 226 size_t resolved_types_; 227 size_t unresolved_types_; 228 229 size_t resolved_instance_fields_; 230 size_t unresolved_instance_fields_; 231 232 size_t resolved_local_static_fields_; 233 size_t resolved_static_fields_; 234 size_t unresolved_static_fields_; 235 // Type based devirtualization for invoke interface and virtual. 236 size_t type_based_devirtualization_; 237 238 size_t resolved_methods_[kMaxInvokeType + 1]; 239 size_t unresolved_methods_[kMaxInvokeType + 1]; 240 size_t virtual_made_direct_[kMaxInvokeType + 1]; 241 size_t direct_calls_to_boot_[kMaxInvokeType + 1]; 242 size_t direct_methods_to_boot_[kMaxInvokeType + 1]; 243 244 size_t safe_casts_; 245 size_t not_safe_casts_; 246 247 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats); 248}; 249 250class CompilerDriver::DexFileMethodSet { 251 public: 252 explicit DexFileMethodSet(const DexFile& dex_file) 253 : dex_file_(dex_file), 254 method_indexes_(dex_file.NumMethodIds(), false, Allocator::GetMallocAllocator()) { 255 } 256 DexFileMethodSet(DexFileMethodSet&& other) = default; 257 258 const DexFile& GetDexFile() const { return dex_file_; } 259 260 BitVector& GetMethodIndexes() { return method_indexes_; } 261 const BitVector& GetMethodIndexes() const { return method_indexes_; } 262 263 private: 264 const DexFile& dex_file_; 265 BitVector method_indexes_; 266}; 267 268CompilerDriver::CompilerDriver( 269 const CompilerOptions* compiler_options, 270 VerificationResults* verification_results, 271 Compiler::Kind compiler_kind, 272 InstructionSet instruction_set, 273 const InstructionSetFeatures* instruction_set_features, 274 std::unordered_set<std::string>* image_classes, 275 std::unordered_set<std::string>* compiled_classes, 276 std::unordered_set<std::string>* compiled_methods, 277 size_t thread_count, 278 bool dump_stats, 279 bool dump_passes, 280 CumulativeLogger* timer, 281 int swap_fd, 282 const ProfileCompilationInfo* profile_compilation_info) 283 : compiler_options_(compiler_options), 284 verification_results_(verification_results), 285 compiler_(Compiler::Create(this, compiler_kind)), 286 compiler_kind_(compiler_kind), 287 instruction_set_(instruction_set == kArm ? kThumb2 : instruction_set), 288 instruction_set_features_(instruction_set_features), 289 requires_constructor_barrier_lock_("constructor barrier lock"), 290 compiled_classes_lock_("compiled classes lock"), 291 non_relative_linker_patch_count_(0u), 292 image_classes_(image_classes), 293 classes_to_compile_(compiled_classes), 294 methods_to_compile_(compiled_methods), 295 had_hard_verifier_failure_(false), 296 parallel_thread_count_(thread_count), 297 stats_(new AOTCompilationStats), 298 dump_stats_(dump_stats), 299 dump_passes_(dump_passes), 300 timings_logger_(timer), 301 compiler_context_(nullptr), 302 support_boot_image_fixup_(true), 303 dex_files_for_oat_file_(nullptr), 304 compiled_method_storage_(swap_fd), 305 profile_compilation_info_(profile_compilation_info), 306 max_arena_alloc_(0), 307 dex_to_dex_references_lock_("dex-to-dex references lock"), 308 dex_to_dex_references_(), 309 current_dex_to_dex_methods_(nullptr) { 310 DCHECK(compiler_options_ != nullptr); 311 312 compiler_->Init(); 313 314 if (GetCompilerOptions().IsBootImage()) { 315 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image"; 316 } 317} 318 319CompilerDriver::~CompilerDriver() { 320 compiled_methods_.Visit([this](const MethodReference& ref ATTRIBUTE_UNUSED, 321 CompiledMethod* method) { 322 if (method != nullptr) { 323 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, method); 324 } 325 }); 326 compiler_->UnInit(); 327} 328 329 330#define CREATE_TRAMPOLINE(type, abi, offset) \ 331 if (Is64BitInstructionSet(instruction_set_)) { \ 332 return CreateTrampoline64(instruction_set_, abi, \ 333 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset)); \ 334 } else { \ 335 return CreateTrampoline32(instruction_set_, abi, \ 336 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset)); \ 337 } 338 339std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const { 340 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup) 341} 342 343std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline() 344 const { 345 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline) 346} 347 348std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline() 349 const { 350 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline) 351} 352 353std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline() 354 const { 355 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline) 356} 357 358std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge() 359 const { 360 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge) 361} 362#undef CREATE_TRAMPOLINE 363 364static void SetupIntrinsic(Thread* self, 365 Intrinsics intrinsic, 366 InvokeType invoke_type, 367 const char* class_name, 368 const char* method_name, 369 const char* signature) 370 REQUIRES_SHARED(Locks::mutator_lock_) { 371 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 372 PointerSize image_size = class_linker->GetImagePointerSize(); 373 mirror::Class* cls = class_linker->FindSystemClass(self, class_name); 374 if (cls == nullptr) { 375 LOG(FATAL) << "Could not find class of intrinsic " << class_name; 376 } 377 ArtMethod* method = (invoke_type == kStatic || invoke_type == kDirect) 378 ? cls->FindDeclaredDirectMethod(method_name, signature, image_size) 379 : cls->FindDeclaredVirtualMethod(method_name, signature, image_size); 380 if (method == nullptr) { 381 LOG(FATAL) << "Could not find method of intrinsic " 382 << class_name << " " << method_name << " " << signature; 383 } 384 DCHECK_EQ(method->GetInvokeType(), invoke_type); 385 method->SetIntrinsic(static_cast<uint32_t>(intrinsic)); 386} 387 388void CompilerDriver::CompileAll(jobject class_loader, 389 const std::vector<const DexFile*>& dex_files, 390 TimingLogger* timings) { 391 DCHECK(!Runtime::Current()->IsStarted()); 392 393 InitializeThreadPools(); 394 395 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false); 396 // Precompile: 397 // 1) Load image classes 398 // 2) Resolve all classes 399 // 3) Attempt to verify all classes 400 // 4) Attempt to initialize image classes, and trivially initialized classes 401 PreCompile(class_loader, dex_files, timings); 402 if (GetCompilerOptions().IsBootImage()) { 403 // We don't need to setup the intrinsics for non boot image compilation, as 404 // those compilations will pick up a boot image that have the ArtMethod already 405 // set with the intrinsics flag. 406 ScopedObjectAccess soa(Thread::Current()); 407#define SETUP_INTRINSICS(Name, InvokeType, NeedsEnvironmentOrCache, SideEffects, Exceptions, \ 408 ClassName, MethodName, Signature) \ 409 SetupIntrinsic(soa.Self(), Intrinsics::k##Name, InvokeType, ClassName, MethodName, Signature); 410#include "intrinsics_list.h" 411INTRINSICS_LIST(SETUP_INTRINSICS) 412#undef INTRINSICS_LIST 413#undef SETUP_INTRINSICS 414 } 415 // Compile: 416 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex 417 // compilation. 418 if (GetCompilerOptions().IsAnyCompilationEnabled()) { 419 Compile(class_loader, dex_files, timings); 420 } 421 if (dump_stats_) { 422 stats_->Dump(); 423 } 424 425 FreeThreadPools(); 426} 427 428void CompilerDriver::CompileAll(jobject class_loader, 429 const std::vector<const DexFile*>& dex_files, 430 VdexFile* vdex_file, 431 TimingLogger* timings) { 432 if (vdex_file != nullptr) { 433 // TODO: we unquicken unconditionnally, as we don't know 434 // if the boot image has changed. How exactly we'll know is under 435 // experimentation. 436 TimingLogger::ScopedTiming t("Unquicken", timings); 437 // We do not decompile a RETURN_VOID_NO_BARRIER into a RETURN_VOID, as the quickening 438 // optimization does not depend on the boot image (the optimization relies on not 439 // having final fields in a class, which does not change for an app). 440 VdexFile::Unquicken(dex_files, vdex_file->GetQuickeningInfo()); 441 442 Runtime::Current()->GetCompilerCallbacks()->SetVerifierDeps( 443 new verifier::VerifierDeps(dex_files, vdex_file->GetVerifierDepsData())); 444 } 445 CompileAll(class_loader, dex_files, timings); 446} 447 448static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel( 449 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader, 450 const DexFile& dex_file, const DexFile::ClassDef& class_def) 451 REQUIRES_SHARED(Locks::mutator_lock_) { 452 auto* const runtime = Runtime::Current(); 453 DCHECK(driver.GetCompilerOptions().IsQuickeningCompilationEnabled()); 454 const char* descriptor = dex_file.GetClassDescriptor(class_def); 455 ClassLinker* class_linker = runtime->GetClassLinker(); 456 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader); 457 if (klass == nullptr) { 458 CHECK(self->IsExceptionPending()); 459 self->ClearException(); 460 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile; 461 } 462 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic 463 // references with actual offsets. We cannot re-verify such instructions. 464 // 465 // We store the verification information in the class status in the oat file, which the linker 466 // can validate (checksums) and use to skip load-time verification. It is thus safe to 467 // optimize when a class has been fully verified before. 468 optimizer::DexToDexCompilationLevel max_level = optimizer::DexToDexCompilationLevel::kOptimize; 469 if (driver.GetCompilerOptions().GetDebuggable()) { 470 // We are debuggable so definitions of classes might be changed. We don't want to do any 471 // optimizations that could break that. 472 max_level = optimizer::DexToDexCompilationLevel::kDontDexToDexCompile; 473 } 474 if (klass->IsVerified()) { 475 // Class is verified so we can enable DEX-to-DEX compilation for performance. 476 return max_level; 477 } else { 478 // Class verification has failed: do not run DEX-to-DEX optimizations. 479 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile; 480 } 481} 482 483static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel( 484 Thread* self, 485 const CompilerDriver& driver, 486 jobject jclass_loader, 487 const DexFile& dex_file, 488 const DexFile::ClassDef& class_def) { 489 ScopedObjectAccess soa(self); 490 StackHandleScope<1> hs(soa.Self()); 491 Handle<mirror::ClassLoader> class_loader( 492 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader))); 493 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def); 494} 495 496// Does the runtime for the InstructionSet provide an implementation returned by 497// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler? 498static bool InstructionSetHasGenericJniStub(InstructionSet isa) { 499 switch (isa) { 500 case kArm: 501 case kArm64: 502 case kThumb2: 503 case kMips: 504 case kMips64: 505 case kX86: 506 case kX86_64: return true; 507 default: return false; 508 } 509} 510 511static void CompileMethod(Thread* self, 512 CompilerDriver* driver, 513 const DexFile::CodeItem* code_item, 514 uint32_t access_flags, 515 InvokeType invoke_type, 516 uint16_t class_def_idx, 517 uint32_t method_idx, 518 Handle<mirror::ClassLoader> class_loader, 519 const DexFile& dex_file, 520 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level, 521 bool compilation_enabled, 522 Handle<mirror::DexCache> dex_cache) { 523 DCHECK(driver != nullptr); 524 CompiledMethod* compiled_method = nullptr; 525 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0; 526 MethodReference method_ref(&dex_file, method_idx); 527 528 if (driver->GetCurrentDexToDexMethods() != nullptr) { 529 // This is the second pass when we dex-to-dex compile previously marked methods. 530 // TODO: Refactor the compilation to avoid having to distinguish the two passes 531 // here. That should be done on a higher level. http://b/29089975 532 if (driver->GetCurrentDexToDexMethods()->IsBitSet(method_idx)) { 533 const VerifiedMethod* verified_method = 534 driver->GetVerificationResults()->GetVerifiedMethod(method_ref); 535 // Do not optimize if a VerifiedMethod is missing. SafeCast elision, 536 // for example, relies on it. 537 compiled_method = optimizer::ArtCompileDEX( 538 driver, 539 code_item, 540 access_flags, 541 invoke_type, 542 class_def_idx, 543 method_idx, 544 class_loader, 545 dex_file, 546 (verified_method != nullptr) 547 ? dex_to_dex_compilation_level 548 : optimizer::DexToDexCompilationLevel::kDontDexToDexCompile); 549 } 550 } else if ((access_flags & kAccNative) != 0) { 551 // Are we extracting only and have support for generic JNI down calls? 552 if (!driver->GetCompilerOptions().IsJniCompilationEnabled() && 553 InstructionSetHasGenericJniStub(driver->GetInstructionSet())) { 554 // Leaving this empty will trigger the generic JNI version 555 } else { 556 // Look-up the ArtMethod associated with this code_item (if any) 557 // -- It is later used to lookup any [optimization] annotations for this method. 558 ScopedObjectAccess soa(self); 559 560 // TODO: Lookup annotation from DexFile directly without resolving method. 561 ArtMethod* method = 562 Runtime::Current()->GetClassLinker()->ResolveMethod<ClassLinker::kNoICCECheckForCache>( 563 dex_file, 564 method_idx, 565 dex_cache, 566 class_loader, 567 /* referrer */ nullptr, 568 invoke_type); 569 570 // Query any JNI optimization annotations such as @FastNative or @CriticalNative. 571 Compiler::JniOptimizationFlags optimization_flags = Compiler::kNone; 572 if (UNLIKELY(method == nullptr)) { 573 // Failed method resolutions happen very rarely, e.g. ancestor class cannot be resolved. 574 DCHECK(self->IsExceptionPending()); 575 self->ClearException(); 576 } else if (method->IsAnnotatedWithFastNative()) { 577 // TODO: Will no longer need this CHECK once we have verifier checking this. 578 CHECK(!method->IsAnnotatedWithCriticalNative()); 579 optimization_flags = Compiler::kFastNative; 580 } else if (method->IsAnnotatedWithCriticalNative()) { 581 // TODO: Will no longer need this CHECK once we have verifier checking this. 582 CHECK(!method->IsAnnotatedWithFastNative()); 583 optimization_flags = Compiler::kCriticalNative; 584 } 585 586 compiled_method = driver->GetCompiler()->JniCompile(access_flags, 587 method_idx, 588 dex_file, 589 optimization_flags); 590 CHECK(compiled_method != nullptr); 591 } 592 } else if ((access_flags & kAccAbstract) != 0) { 593 // Abstract methods don't have code. 594 } else { 595 const VerifiedMethod* verified_method = 596 driver->GetVerificationResults()->GetVerifiedMethod(method_ref); 597 bool compile = compilation_enabled && 598 // Basic checks, e.g., not <clinit>. 599 driver->GetVerificationResults() 600 ->IsCandidateForCompilation(method_ref, access_flags) && 601 // Did not fail to create VerifiedMethod metadata. 602 verified_method != nullptr && 603 // Do not have failures that should punt to the interpreter. 604 !verified_method->HasRuntimeThrow() && 605 (verified_method->GetEncounteredVerificationFailures() & 606 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 && 607 // Is eligable for compilation by methods-to-compile filter. 608 driver->IsMethodToCompile(method_ref) && 609 driver->ShouldCompileBasedOnProfile(method_ref); 610 611 if (compile) { 612 // NOTE: if compiler declines to compile this method, it will return null. 613 compiled_method = driver->GetCompiler()->Compile(code_item, 614 access_flags, 615 invoke_type, 616 class_def_idx, 617 method_idx, 618 class_loader, 619 dex_file, 620 dex_cache); 621 } 622 if (compiled_method == nullptr && 623 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) { 624 DCHECK(!Runtime::Current()->UseJitCompilation()); 625 // TODO: add a command-line option to disable DEX-to-DEX compilation ? 626 driver->MarkForDexToDexCompilation(self, method_ref); 627 } 628 } 629 if (kTimeCompileMethod) { 630 uint64_t duration_ns = NanoTime() - start_ns; 631 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) { 632 LOG(WARNING) << "Compilation of " << dex_file.PrettyMethod(method_idx) 633 << " took " << PrettyDuration(duration_ns); 634 } 635 } 636 637 if (compiled_method != nullptr) { 638 // Count non-relative linker patches. 639 size_t non_relative_linker_patch_count = 0u; 640 for (const LinkerPatch& patch : compiled_method->GetPatches()) { 641 if (!patch.IsPcRelative()) { 642 ++non_relative_linker_patch_count; 643 } 644 } 645 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default 646 // When compiling with PIC, there should be zero non-relative linker patches 647 CHECK(!compile_pic || non_relative_linker_patch_count == 0u); 648 649 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count); 650 } 651 652 if (self->IsExceptionPending()) { 653 ScopedObjectAccess soa(self); 654 LOG(FATAL) << "Unexpected exception compiling: " << dex_file.PrettyMethod(method_idx) << "\n" 655 << self->GetException()->Dump(); 656 } 657} 658 659void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) { 660 DCHECK(!Runtime::Current()->IsStarted()); 661 jobject jclass_loader; 662 const DexFile* dex_file; 663 uint16_t class_def_idx; 664 uint32_t method_idx = method->GetDexMethodIndex(); 665 uint32_t access_flags = method->GetAccessFlags(); 666 InvokeType invoke_type = method->GetInvokeType(); 667 StackHandleScope<2> hs(self); 668 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache())); 669 Handle<mirror::ClassLoader> class_loader( 670 hs.NewHandle(method->GetDeclaringClass()->GetClassLoader())); 671 { 672 ScopedObjectAccessUnchecked soa(self); 673 ScopedLocalRef<jobject> local_class_loader( 674 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get())); 675 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get()); 676 // Find the dex_file 677 dex_file = method->GetDexFile(); 678 class_def_idx = method->GetClassDefIndex(); 679 } 680 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset()); 681 682 // Go to native so that we don't block GC during compilation. 683 ScopedThreadSuspension sts(self, kNative); 684 685 std::vector<const DexFile*> dex_files; 686 dex_files.push_back(dex_file); 687 688 InitializeThreadPools(); 689 690 PreCompile(jclass_loader, dex_files, timings); 691 692 // Can we run DEX-to-DEX compiler on this class ? 693 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level = 694 GetDexToDexCompilationLevel(self, 695 *this, 696 jclass_loader, 697 *dex_file, 698 dex_file->GetClassDef(class_def_idx)); 699 700 DCHECK(current_dex_to_dex_methods_ == nullptr); 701 CompileMethod(self, 702 this, 703 code_item, 704 access_flags, 705 invoke_type, 706 class_def_idx, 707 method_idx, 708 class_loader, 709 *dex_file, 710 dex_to_dex_compilation_level, 711 true, 712 dex_cache); 713 714 ArrayRef<DexFileMethodSet> dex_to_dex_references; 715 { 716 // From this point on, we shall not modify dex_to_dex_references_, so 717 // just grab a reference to it that we use without holding the mutex. 718 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_); 719 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_); 720 } 721 if (!dex_to_dex_references.empty()) { 722 DCHECK_EQ(dex_to_dex_references.size(), 1u); 723 DCHECK(&dex_to_dex_references[0].GetDexFile() == dex_file); 724 current_dex_to_dex_methods_ = &dex_to_dex_references.front().GetMethodIndexes(); 725 DCHECK(current_dex_to_dex_methods_->IsBitSet(method_idx)); 726 DCHECK_EQ(current_dex_to_dex_methods_->NumSetBits(), 1u); 727 CompileMethod(self, 728 this, 729 code_item, 730 access_flags, 731 invoke_type, 732 class_def_idx, 733 method_idx, 734 class_loader, 735 *dex_file, 736 dex_to_dex_compilation_level, 737 true, 738 dex_cache); 739 current_dex_to_dex_methods_ = nullptr; 740 } 741 742 FreeThreadPools(); 743 744 self->GetJniEnv()->DeleteGlobalRef(jclass_loader); 745} 746 747void CompilerDriver::Resolve(jobject class_loader, 748 const std::vector<const DexFile*>& dex_files, 749 TimingLogger* timings) { 750 // Resolution allocates classes and needs to run single-threaded to be deterministic. 751 bool force_determinism = GetCompilerOptions().IsForceDeterminism(); 752 ThreadPool* resolve_thread_pool = force_determinism 753 ? single_thread_pool_.get() 754 : parallel_thread_pool_.get(); 755 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_; 756 757 for (size_t i = 0; i != dex_files.size(); ++i) { 758 const DexFile* dex_file = dex_files[i]; 759 CHECK(dex_file != nullptr); 760 ResolveDexFile(class_loader, 761 *dex_file, 762 dex_files, 763 resolve_thread_pool, 764 resolve_thread_count, 765 timings); 766 } 767} 768 769// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now 770// this is single-threaded for simplicity. 771// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a 772// stable order. 773 774static void ResolveConstStrings(Handle<mirror::DexCache> dex_cache, 775 const DexFile& dex_file, 776 const DexFile::CodeItem* code_item) 777 REQUIRES_SHARED(Locks::mutator_lock_) { 778 if (code_item == nullptr) { 779 // Abstract or native method. 780 return; 781 } 782 783 const uint16_t* code_ptr = code_item->insns_; 784 const uint16_t* code_end = code_item->insns_ + code_item->insns_size_in_code_units_; 785 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker(); 786 787 while (code_ptr < code_end) { 788 const Instruction* inst = Instruction::At(code_ptr); 789 switch (inst->Opcode()) { 790 case Instruction::CONST_STRING: 791 case Instruction::CONST_STRING_JUMBO: { 792 dex::StringIndex string_index((inst->Opcode() == Instruction::CONST_STRING) 793 ? inst->VRegB_21c() 794 : inst->VRegB_31c()); 795 mirror::String* string = class_linker->ResolveString(dex_file, string_index, dex_cache); 796 CHECK(string != nullptr) << "Could not allocate a string when forcing determinism"; 797 break; 798 } 799 800 default: 801 break; 802 } 803 804 code_ptr += inst->SizeInCodeUnits(); 805 } 806} 807 808static void ResolveConstStrings(CompilerDriver* driver, 809 const std::vector<const DexFile*>& dex_files, 810 TimingLogger* timings) { 811 ScopedObjectAccess soa(Thread::Current()); 812 StackHandleScope<1> hs(soa.Self()); 813 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker(); 814 MutableHandle<mirror::DexCache> dex_cache(hs.NewHandle<mirror::DexCache>(nullptr)); 815 816 for (const DexFile* dex_file : dex_files) { 817 dex_cache.Assign(class_linker->FindDexCache(soa.Self(), *dex_file)); 818 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings); 819 820 size_t class_def_count = dex_file->NumClassDefs(); 821 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) { 822 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index); 823 824 const uint8_t* class_data = dex_file->GetClassData(class_def); 825 if (class_data == nullptr) { 826 // empty class, probably a marker interface 827 continue; 828 } 829 830 ClassDataItemIterator it(*dex_file, class_data); 831 // Skip fields 832 while (it.HasNextStaticField()) { 833 it.Next(); 834 } 835 while (it.HasNextInstanceField()) { 836 it.Next(); 837 } 838 839 bool compilation_enabled = driver->IsClassToCompile( 840 dex_file->StringByTypeIdx(class_def.class_idx_)); 841 if (!compilation_enabled) { 842 // Compilation is skipped, do not resolve const-string in code of this class. 843 // TODO: Make sure that inlining honors this. 844 continue; 845 } 846 847 // Direct methods. 848 int64_t previous_direct_method_idx = -1; 849 while (it.HasNextDirectMethod()) { 850 uint32_t method_idx = it.GetMemberIndex(); 851 if (method_idx == previous_direct_method_idx) { 852 // smali can create dex files with two encoded_methods sharing the same method_idx 853 // http://code.google.com/p/smali/issues/detail?id=119 854 it.Next(); 855 continue; 856 } 857 previous_direct_method_idx = method_idx; 858 ResolveConstStrings(dex_cache, *dex_file, it.GetMethodCodeItem()); 859 it.Next(); 860 } 861 // Virtual methods. 862 int64_t previous_virtual_method_idx = -1; 863 while (it.HasNextVirtualMethod()) { 864 uint32_t method_idx = it.GetMemberIndex(); 865 if (method_idx == previous_virtual_method_idx) { 866 // smali can create dex files with two encoded_methods sharing the same method_idx 867 // http://code.google.com/p/smali/issues/detail?id=119 868 it.Next(); 869 continue; 870 } 871 previous_virtual_method_idx = method_idx; 872 ResolveConstStrings(dex_cache, *dex_file, it.GetMethodCodeItem()); 873 it.Next(); 874 } 875 DCHECK(!it.HasNext()); 876 } 877 } 878} 879 880inline void CompilerDriver::CheckThreadPools() { 881 DCHECK(parallel_thread_pool_ != nullptr); 882 DCHECK(single_thread_pool_ != nullptr); 883} 884 885static void EnsureVerifiedOrVerifyAtRuntime(jobject jclass_loader, 886 const std::vector<const DexFile*>& dex_files) { 887 ScopedObjectAccess soa(Thread::Current()); 888 StackHandleScope<2> hs(soa.Self()); 889 Handle<mirror::ClassLoader> class_loader( 890 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader))); 891 MutableHandle<mirror::Class> cls(hs.NewHandle<mirror::Class>(nullptr)); 892 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 893 894 for (const DexFile* dex_file : dex_files) { 895 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) { 896 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i); 897 const char* descriptor = dex_file->GetClassDescriptor(class_def); 898 cls.Assign(class_linker->FindClass(soa.Self(), descriptor, class_loader)); 899 if (cls == nullptr) { 900 soa.Self()->ClearException(); 901 } else if (&cls->GetDexFile() == dex_file) { 902 DCHECK(cls->IsErroneous() || cls->IsVerified() || cls->ShouldVerifyAtRuntime()) 903 << cls->PrettyClass() 904 << " " << cls->GetStatus(); 905 } 906 } 907 } 908} 909 910void CompilerDriver::PreCompile(jobject class_loader, 911 const std::vector<const DexFile*>& dex_files, 912 TimingLogger* timings) { 913 CheckThreadPools(); 914 915 for (const DexFile* dex_file : dex_files) { 916 // Can be already inserted if the caller is CompileOne. This happens for gtests. 917 if (!compiled_methods_.HaveDexFile(dex_file)) { 918 compiled_methods_.AddDexFile(dex_file); 919 } 920 } 921 922 LoadImageClasses(timings); 923 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false); 924 925 if (compiler_options_->IsAnyCompilationEnabled()) { 926 // Resolve eagerly to prepare for compilation. 927 Resolve(class_loader, dex_files, timings); 928 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false); 929 } 930 931 if (compiler_options_->AssumeClassesAreVerified()) { 932 VLOG(compiler) << "Verify none mode specified, skipping verification."; 933 SetVerified(class_loader, dex_files, timings); 934 } 935 936 if (!compiler_options_->IsVerificationEnabled()) { 937 return; 938 } 939 940 if (GetCompilerOptions().IsForceDeterminism() && GetCompilerOptions().IsBootImage()) { 941 // Resolve strings from const-string. Do this now to have a deterministic image. 942 ResolveConstStrings(this, dex_files, timings); 943 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false); 944 } 945 946 Verify(class_loader, dex_files, timings); 947 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false); 948 949 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) { 950 LOG(FATAL) << "Had a hard failure verifying all classes, and was asked to abort in such " 951 << "situations. Please check the log."; 952 } 953 954 if (compiler_options_->IsAnyCompilationEnabled()) { 955 if (kIsDebugBuild) { 956 EnsureVerifiedOrVerifyAtRuntime(class_loader, dex_files); 957 } 958 InitializeClasses(class_loader, dex_files, timings); 959 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false); 960 } 961 962 UpdateImageClasses(timings); 963 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false); 964} 965 966bool CompilerDriver::IsImageClass(const char* descriptor) const { 967 if (image_classes_ != nullptr) { 968 // If we have a set of image classes, use those. 969 return image_classes_->find(descriptor) != image_classes_->end(); 970 } 971 // No set of image classes, assume we include all the classes. 972 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case. 973 return !GetCompilerOptions().IsBootImage(); 974} 975 976bool CompilerDriver::IsClassToCompile(const char* descriptor) const { 977 if (classes_to_compile_ == nullptr) { 978 return true; 979 } 980 return classes_to_compile_->find(descriptor) != classes_to_compile_->end(); 981} 982 983bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const { 984 if (methods_to_compile_ == nullptr) { 985 return true; 986 } 987 988 std::string tmp = method_ref.dex_file->PrettyMethod(method_ref.dex_method_index, true); 989 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end(); 990} 991 992bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const { 993 // Profile compilation info may be null if no profile is passed. 994 if (!CompilerFilter::DependsOnProfile(compiler_options_->GetCompilerFilter())) { 995 // Use the compiler filter instead of the presence of profile_compilation_info_ since 996 // we may want to have full speed compilation along with profile based layout optimizations. 997 return true; 998 } 999 // If we are using a profile filter but do not have a profile compilation info, compile nothing. 1000 if (profile_compilation_info_ == nullptr) { 1001 return false; 1002 } 1003 // TODO: Revisit compiling all startup methods. b/36457259 1004 bool result = profile_compilation_info_->IsStartupOrHotMethod(method_ref); 1005 1006 if (kDebugProfileGuidedCompilation) { 1007 LOG(INFO) << "[ProfileGuidedCompilation] " 1008 << (result ? "Compiled" : "Skipped") << " method:" 1009 << method_ref.dex_file->PrettyMethod(method_ref.dex_method_index, true); 1010 } 1011 return result; 1012} 1013 1014class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor { 1015 public: 1016 ResolveCatchBlockExceptionsClassVisitor() : classes_() {} 1017 1018 virtual bool operator()(ObjPtr<mirror::Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) { 1019 classes_.push_back(c); 1020 return true; 1021 } 1022 1023 void FindExceptionTypesToResolve( 1024 std::set<std::pair<dex::TypeIndex, const DexFile*>>* exceptions_to_resolve) 1025 REQUIRES_SHARED(Locks::mutator_lock_) { 1026 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize(); 1027 for (ObjPtr<mirror::Class> klass : classes_) { 1028 for (ArtMethod& method : klass->GetMethods(pointer_size)) { 1029 FindExceptionTypesToResolveForMethod(&method, exceptions_to_resolve); 1030 } 1031 } 1032 } 1033 1034 private: 1035 void FindExceptionTypesToResolveForMethod( 1036 ArtMethod* method, 1037 std::set<std::pair<dex::TypeIndex, const DexFile*>>* exceptions_to_resolve) 1038 REQUIRES_SHARED(Locks::mutator_lock_) { 1039 const DexFile::CodeItem* code_item = method->GetCodeItem(); 1040 if (code_item == nullptr) { 1041 return; // native or abstract method 1042 } 1043 if (code_item->tries_size_ == 0) { 1044 return; // nothing to process 1045 } 1046 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0); 1047 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list); 1048 for (size_t i = 0; i < num_encoded_catch_handlers; i++) { 1049 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list); 1050 bool has_catch_all = false; 1051 if (encoded_catch_handler_size <= 0) { 1052 encoded_catch_handler_size = -encoded_catch_handler_size; 1053 has_catch_all = true; 1054 } 1055 for (int32_t j = 0; j < encoded_catch_handler_size; j++) { 1056 dex::TypeIndex encoded_catch_handler_handlers_type_idx = 1057 dex::TypeIndex(DecodeUnsignedLeb128(&encoded_catch_handler_list)); 1058 // Add to set of types to resolve if not already in the dex cache resolved types 1059 if (!method->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) { 1060 exceptions_to_resolve->emplace(encoded_catch_handler_handlers_type_idx, 1061 method->GetDexFile()); 1062 } 1063 // ignore address associated with catch handler 1064 DecodeUnsignedLeb128(&encoded_catch_handler_list); 1065 } 1066 if (has_catch_all) { 1067 // ignore catch all address 1068 DecodeUnsignedLeb128(&encoded_catch_handler_list); 1069 } 1070 } 1071 } 1072 1073 std::vector<ObjPtr<mirror::Class>> classes_; 1074}; 1075 1076class RecordImageClassesVisitor : public ClassVisitor { 1077 public: 1078 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes) 1079 : image_classes_(image_classes) {} 1080 1081 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) { 1082 std::string temp; 1083 image_classes_->insert(klass->GetDescriptor(&temp)); 1084 return true; 1085 } 1086 1087 private: 1088 std::unordered_set<std::string>* const image_classes_; 1089}; 1090 1091// Make a list of descriptors for classes to include in the image 1092void CompilerDriver::LoadImageClasses(TimingLogger* timings) { 1093 CHECK(timings != nullptr); 1094 if (!GetCompilerOptions().IsBootImage()) { 1095 return; 1096 } 1097 1098 TimingLogger::ScopedTiming t("LoadImageClasses", timings); 1099 // Make a first class to load all classes explicitly listed in the file 1100 Thread* self = Thread::Current(); 1101 ScopedObjectAccess soa(self); 1102 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 1103 CHECK(image_classes_.get() != nullptr); 1104 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) { 1105 const std::string& descriptor(*it); 1106 StackHandleScope<1> hs(self); 1107 Handle<mirror::Class> klass( 1108 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str()))); 1109 if (klass == nullptr) { 1110 VLOG(compiler) << "Failed to find class " << descriptor; 1111 image_classes_->erase(it++); 1112 self->ClearException(); 1113 } else { 1114 ++it; 1115 } 1116 } 1117 1118 // Resolve exception classes referenced by the loaded classes. The catch logic assumes 1119 // exceptions are resolved by the verifier when there is a catch block in an interested method. 1120 // Do this here so that exception classes appear to have been specified image classes. 1121 std::set<std::pair<dex::TypeIndex, const DexFile*>> unresolved_exception_types; 1122 StackHandleScope<1> hs(self); 1123 Handle<mirror::Class> java_lang_Throwable( 1124 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;"))); 1125 do { 1126 unresolved_exception_types.clear(); 1127 { 1128 // Thread suspension is not allowed while ResolveCatchBlockExceptionsClassVisitor 1129 // is using a std::vector<ObjPtr<mirror::Class>>. 1130 ScopedAssertNoThreadSuspension ants(__FUNCTION__); 1131 ResolveCatchBlockExceptionsClassVisitor visitor; 1132 class_linker->VisitClasses(&visitor); 1133 visitor.FindExceptionTypesToResolve(&unresolved_exception_types); 1134 } 1135 for (const auto& exception_type : unresolved_exception_types) { 1136 dex::TypeIndex exception_type_idx = exception_type.first; 1137 const DexFile* dex_file = exception_type.second; 1138 StackHandleScope<2> hs2(self); 1139 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file, 1140 nullptr))); 1141 Handle<mirror::Class> klass(hs2.NewHandle( 1142 (dex_cache != nullptr) 1143 ? class_linker->ResolveType(*dex_file, 1144 exception_type_idx, 1145 dex_cache, 1146 ScopedNullHandle<mirror::ClassLoader>()) 1147 : nullptr)); 1148 if (klass == nullptr) { 1149 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx); 1150 const char* descriptor = dex_file->GetTypeDescriptor(type_id); 1151 LOG(FATAL) << "Failed to resolve class " << descriptor; 1152 } 1153 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get())); 1154 } 1155 // Resolving exceptions may load classes that reference more exceptions, iterate until no 1156 // more are found 1157 } while (!unresolved_exception_types.empty()); 1158 1159 // We walk the roots looking for classes so that we'll pick up the 1160 // above classes plus any classes them depend on such super 1161 // classes, interfaces, and the required ClassLinker roots. 1162 RecordImageClassesVisitor visitor(image_classes_.get()); 1163 class_linker->VisitClasses(&visitor); 1164 1165 CHECK_NE(image_classes_->size(), 0U); 1166} 1167 1168static void MaybeAddToImageClasses(Thread* self, 1169 ObjPtr<mirror::Class> klass, 1170 std::unordered_set<std::string>* image_classes) 1171 REQUIRES_SHARED(Locks::mutator_lock_) { 1172 DCHECK_EQ(self, Thread::Current()); 1173 StackHandleScope<1> hs(self); 1174 std::string temp; 1175 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize(); 1176 while (!klass->IsObjectClass()) { 1177 const char* descriptor = klass->GetDescriptor(&temp); 1178 std::pair<std::unordered_set<std::string>::iterator, bool> result = 1179 image_classes->insert(descriptor); 1180 if (!result.second) { // Previously inserted. 1181 break; 1182 } 1183 VLOG(compiler) << "Adding " << descriptor << " to image classes"; 1184 for (size_t i = 0, num_interfaces = klass->NumDirectInterfaces(); i != num_interfaces; ++i) { 1185 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, klass, i); 1186 DCHECK(interface != nullptr); 1187 MaybeAddToImageClasses(self, interface, image_classes); 1188 } 1189 for (auto& m : klass->GetVirtualMethods(pointer_size)) { 1190 MaybeAddToImageClasses(self, m.GetDeclaringClass(), image_classes); 1191 } 1192 if (klass->IsArrayClass()) { 1193 MaybeAddToImageClasses(self, klass->GetComponentType(), image_classes); 1194 } 1195 klass.Assign(klass->GetSuperClass()); 1196 } 1197} 1198 1199// Keeps all the data for the update together. Also doubles as the reference visitor. 1200// Note: we can use object pointers because we suspend all threads. 1201class ClinitImageUpdate { 1202 public: 1203 static ClinitImageUpdate* Create(VariableSizedHandleScope& hs, 1204 std::unordered_set<std::string>* image_class_descriptors, 1205 Thread* self, 1206 ClassLinker* linker) { 1207 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(hs, 1208 image_class_descriptors, 1209 self, 1210 linker)); 1211 return res.release(); 1212 } 1213 1214 ~ClinitImageUpdate() { 1215 // Allow others to suspend again. 1216 self_->EndAssertNoThreadSuspension(old_cause_); 1217 } 1218 1219 // Visitor for VisitReferences. 1220 void operator()(ObjPtr<mirror::Object> object, 1221 MemberOffset field_offset, 1222 bool /* is_static */) const 1223 REQUIRES_SHARED(Locks::mutator_lock_) { 1224 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset); 1225 if (ref != nullptr) { 1226 VisitClinitClassesObject(ref); 1227 } 1228 } 1229 1230 // java.lang.ref.Reference visitor for VisitReferences. 1231 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED, 1232 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const {} 1233 1234 // Ignore class native roots. 1235 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) 1236 const {} 1237 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {} 1238 1239 void Walk() REQUIRES_SHARED(Locks::mutator_lock_) { 1240 // Use the initial classes as roots for a search. 1241 for (Handle<mirror::Class> klass_root : image_classes_) { 1242 VisitClinitClassesObject(klass_root.Get()); 1243 } 1244 Thread* self = Thread::Current(); 1245 ScopedAssertNoThreadSuspension ants(__FUNCTION__); 1246 for (Handle<mirror::Class> h_klass : to_insert_) { 1247 MaybeAddToImageClasses(self, h_klass.Get(), image_class_descriptors_); 1248 } 1249 } 1250 1251 private: 1252 class FindImageClassesVisitor : public ClassVisitor { 1253 public: 1254 explicit FindImageClassesVisitor(VariableSizedHandleScope& hs, 1255 ClinitImageUpdate* data) 1256 : data_(data), 1257 hs_(hs) {} 1258 1259 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) { 1260 std::string temp; 1261 const char* name = klass->GetDescriptor(&temp); 1262 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) { 1263 data_->image_classes_.push_back(hs_.NewHandle(klass)); 1264 } else { 1265 // Check whether it is initialized and has a clinit. They must be kept, too. 1266 if (klass->IsInitialized() && klass->FindClassInitializer( 1267 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) { 1268 data_->image_classes_.push_back(hs_.NewHandle(klass)); 1269 } 1270 } 1271 return true; 1272 } 1273 1274 private: 1275 ClinitImageUpdate* const data_; 1276 VariableSizedHandleScope& hs_; 1277 }; 1278 1279 ClinitImageUpdate(VariableSizedHandleScope& hs, 1280 std::unordered_set<std::string>* image_class_descriptors, 1281 Thread* self, 1282 ClassLinker* linker) REQUIRES_SHARED(Locks::mutator_lock_) 1283 : hs_(hs), 1284 image_class_descriptors_(image_class_descriptors), 1285 self_(self) { 1286 CHECK(linker != nullptr); 1287 CHECK(image_class_descriptors != nullptr); 1288 1289 // Make sure nobody interferes with us. 1290 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure"); 1291 1292 // Find all the already-marked classes. 1293 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 1294 FindImageClassesVisitor visitor(hs_, this); 1295 linker->VisitClasses(&visitor); 1296 } 1297 1298 void VisitClinitClassesObject(mirror::Object* object) const 1299 REQUIRES_SHARED(Locks::mutator_lock_) { 1300 DCHECK(object != nullptr); 1301 if (marked_objects_.find(object) != marked_objects_.end()) { 1302 // Already processed. 1303 return; 1304 } 1305 1306 // Mark it. 1307 marked_objects_.insert(object); 1308 1309 if (object->IsClass()) { 1310 // Add to the TODO list since MaybeAddToImageClasses may cause thread suspension. Thread 1311 // suspensionb is not safe to do in VisitObjects or VisitReferences. 1312 to_insert_.push_back(hs_.NewHandle(object->AsClass())); 1313 } else { 1314 // Else visit the object's class. 1315 VisitClinitClassesObject(object->GetClass()); 1316 } 1317 1318 // If it is not a DexCache, visit all references. 1319 if (!object->IsDexCache()) { 1320 object->VisitReferences(*this, *this); 1321 } 1322 } 1323 1324 VariableSizedHandleScope& hs_; 1325 mutable std::vector<Handle<mirror::Class>> to_insert_; 1326 mutable std::unordered_set<mirror::Object*> marked_objects_; 1327 std::unordered_set<std::string>* const image_class_descriptors_; 1328 std::vector<Handle<mirror::Class>> image_classes_; 1329 Thread* const self_; 1330 const char* old_cause_; 1331 1332 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate); 1333}; 1334 1335void CompilerDriver::UpdateImageClasses(TimingLogger* timings) { 1336 if (GetCompilerOptions().IsBootImage()) { 1337 TimingLogger::ScopedTiming t("UpdateImageClasses", timings); 1338 1339 Runtime* runtime = Runtime::Current(); 1340 1341 // Suspend all threads. 1342 ScopedSuspendAll ssa(__FUNCTION__); 1343 1344 VariableSizedHandleScope hs(Thread::Current()); 1345 std::string error_msg; 1346 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(hs, 1347 image_classes_.get(), 1348 Thread::Current(), 1349 runtime->GetClassLinker())); 1350 1351 // Do the marking. 1352 update->Walk(); 1353 } 1354} 1355 1356bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) { 1357 Runtime* runtime = Runtime::Current(); 1358 if (!runtime->IsAotCompiler()) { 1359 DCHECK(runtime->UseJitCompilation()); 1360 // Having the klass reference here implies that the klass is already loaded. 1361 return true; 1362 } 1363 if (!GetCompilerOptions().IsBootImage()) { 1364 // Assume loaded only if klass is in the boot image. App classes cannot be assumed 1365 // loaded because we don't even know what class loader will be used to load them. 1366 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace(); 1367 return class_in_image; 1368 } 1369 std::string temp; 1370 const char* descriptor = klass->GetDescriptor(&temp); 1371 return IsImageClass(descriptor); 1372} 1373 1374void CompilerDriver::MarkForDexToDexCompilation(Thread* self, const MethodReference& method_ref) { 1375 MutexLock lock(self, dex_to_dex_references_lock_); 1376 // Since we're compiling one dex file at a time, we need to look for the 1377 // current dex file entry only at the end of dex_to_dex_references_. 1378 if (dex_to_dex_references_.empty() || 1379 &dex_to_dex_references_.back().GetDexFile() != method_ref.dex_file) { 1380 dex_to_dex_references_.emplace_back(*method_ref.dex_file); 1381 } 1382 dex_to_dex_references_.back().GetMethodIndexes().SetBit(method_ref.dex_method_index); 1383} 1384 1385bool CompilerDriver::CanAccessTypeWithoutChecks(ObjPtr<mirror::Class> referrer_class, 1386 ObjPtr<mirror::Class> resolved_class) { 1387 if (resolved_class == nullptr) { 1388 stats_->TypeNeedsAccessCheck(); 1389 return false; // Unknown class needs access checks. 1390 } 1391 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible. 1392 if (!is_accessible) { 1393 if (referrer_class == nullptr) { 1394 stats_->TypeNeedsAccessCheck(); 1395 return false; // Incomplete referrer knowledge needs access check. 1396 } 1397 // Perform access check, will return true if access is ok or false if we're going to have to 1398 // check this at runtime (for example for class loaders). 1399 is_accessible = referrer_class->CanAccess(resolved_class); 1400 } 1401 if (is_accessible) { 1402 stats_->TypeDoesntNeedAccessCheck(); 1403 } else { 1404 stats_->TypeNeedsAccessCheck(); 1405 } 1406 return is_accessible; 1407} 1408 1409bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(ObjPtr<mirror::Class> referrer_class, 1410 ObjPtr<mirror::Class> resolved_class, 1411 bool* finalizable) { 1412 if (resolved_class == nullptr) { 1413 stats_->TypeNeedsAccessCheck(); 1414 // Be conservative. 1415 *finalizable = true; 1416 return false; // Unknown class needs access checks. 1417 } 1418 *finalizable = resolved_class->IsFinalizable(); 1419 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible. 1420 if (!is_accessible) { 1421 if (referrer_class == nullptr) { 1422 stats_->TypeNeedsAccessCheck(); 1423 return false; // Incomplete referrer knowledge needs access check. 1424 } 1425 // Perform access and instantiable checks, will return true if access is ok or false if we're 1426 // going to have to check this at runtime (for example for class loaders). 1427 is_accessible = referrer_class->CanAccess(resolved_class); 1428 } 1429 bool result = is_accessible && resolved_class->IsInstantiable(); 1430 if (result) { 1431 stats_->TypeDoesntNeedAccessCheck(); 1432 } else { 1433 stats_->TypeNeedsAccessCheck(); 1434 } 1435 return result; 1436} 1437 1438void CompilerDriver::ProcessedInstanceField(bool resolved) { 1439 if (!resolved) { 1440 stats_->UnresolvedInstanceField(); 1441 } else { 1442 stats_->ResolvedInstanceField(); 1443 } 1444} 1445 1446void CompilerDriver::ProcessedStaticField(bool resolved, bool local) { 1447 if (!resolved) { 1448 stats_->UnresolvedStaticField(); 1449 } else if (local) { 1450 stats_->ResolvedLocalStaticField(); 1451 } else { 1452 stats_->ResolvedStaticField(); 1453 } 1454} 1455 1456ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, 1457 const DexCompilationUnit* mUnit, bool is_put, 1458 const ScopedObjectAccess& soa) { 1459 // Try to resolve the field and compiling method's class. 1460 ArtField* resolved_field; 1461 mirror::Class* referrer_class; 1462 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache()); 1463 { 1464 Handle<mirror::ClassLoader> class_loader_handle = mUnit->GetClassLoader(); 1465 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false); 1466 referrer_class = resolved_field != nullptr 1467 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr; 1468 } 1469 bool can_link = false; 1470 if (resolved_field != nullptr && referrer_class != nullptr) { 1471 std::pair<bool, bool> fast_path = IsFastInstanceField( 1472 dex_cache.Get(), referrer_class, resolved_field, field_idx); 1473 can_link = is_put ? fast_path.second : fast_path.first; 1474 } 1475 ProcessedInstanceField(can_link); 1476 return can_link ? resolved_field : nullptr; 1477} 1478 1479bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit, 1480 bool is_put, MemberOffset* field_offset, 1481 bool* is_volatile) { 1482 ScopedObjectAccess soa(Thread::Current()); 1483 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa); 1484 1485 if (resolved_field == nullptr) { 1486 // Conservative defaults. 1487 *is_volatile = true; 1488 *field_offset = MemberOffset(static_cast<size_t>(-1)); 1489 return false; 1490 } else { 1491 *is_volatile = resolved_field->IsVolatile(); 1492 *field_offset = resolved_field->GetOffset(); 1493 return true; 1494 } 1495} 1496 1497const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file, 1498 uint32_t method_idx) const { 1499 MethodReference ref(dex_file, method_idx); 1500 return verification_results_->GetVerifiedMethod(ref); 1501} 1502 1503bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) { 1504 if (!compiler_options_->IsVerificationEnabled()) { 1505 // If we didn't verify, every cast has to be treated as non-safe. 1506 return false; 1507 } 1508 DCHECK(mUnit->GetVerifiedMethod() != nullptr); 1509 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc); 1510 if (result) { 1511 stats_->SafeCast(); 1512 } else { 1513 stats_->NotASafeCast(); 1514 } 1515 return result; 1516} 1517 1518class CompilationVisitor { 1519 public: 1520 virtual ~CompilationVisitor() {} 1521 virtual void Visit(size_t index) = 0; 1522}; 1523 1524class ParallelCompilationManager { 1525 public: 1526 ParallelCompilationManager(ClassLinker* class_linker, 1527 jobject class_loader, 1528 CompilerDriver* compiler, 1529 const DexFile* dex_file, 1530 const std::vector<const DexFile*>& dex_files, 1531 ThreadPool* thread_pool) 1532 : index_(0), 1533 class_linker_(class_linker), 1534 class_loader_(class_loader), 1535 compiler_(compiler), 1536 dex_file_(dex_file), 1537 dex_files_(dex_files), 1538 thread_pool_(thread_pool) {} 1539 1540 ClassLinker* GetClassLinker() const { 1541 CHECK(class_linker_ != nullptr); 1542 return class_linker_; 1543 } 1544 1545 jobject GetClassLoader() const { 1546 return class_loader_; 1547 } 1548 1549 CompilerDriver* GetCompiler() const { 1550 CHECK(compiler_ != nullptr); 1551 return compiler_; 1552 } 1553 1554 const DexFile* GetDexFile() const { 1555 CHECK(dex_file_ != nullptr); 1556 return dex_file_; 1557 } 1558 1559 const std::vector<const DexFile*>& GetDexFiles() const { 1560 return dex_files_; 1561 } 1562 1563 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units) 1564 REQUIRES(!*Locks::mutator_lock_) { 1565 Thread* self = Thread::Current(); 1566 self->AssertNoPendingException(); 1567 CHECK_GT(work_units, 0U); 1568 1569 index_.StoreRelaxed(begin); 1570 for (size_t i = 0; i < work_units; ++i) { 1571 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor)); 1572 } 1573 thread_pool_->StartWorkers(self); 1574 1575 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker 1576 // thread destructor's called below perform join). 1577 CHECK_NE(self->GetState(), kRunnable); 1578 1579 // Wait for all the worker threads to finish. 1580 thread_pool_->Wait(self, true, false); 1581 1582 // And stop the workers accepting jobs. 1583 thread_pool_->StopWorkers(self); 1584 } 1585 1586 size_t NextIndex() { 1587 return index_.FetchAndAddSequentiallyConsistent(1); 1588 } 1589 1590 private: 1591 class ForAllClosure : public Task { 1592 public: 1593 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor) 1594 : manager_(manager), 1595 end_(end), 1596 visitor_(visitor) {} 1597 1598 virtual void Run(Thread* self) { 1599 while (true) { 1600 const size_t index = manager_->NextIndex(); 1601 if (UNLIKELY(index >= end_)) { 1602 break; 1603 } 1604 visitor_->Visit(index); 1605 self->AssertNoPendingException(); 1606 } 1607 } 1608 1609 virtual void Finalize() { 1610 delete this; 1611 } 1612 1613 private: 1614 ParallelCompilationManager* const manager_; 1615 const size_t end_; 1616 CompilationVisitor* const visitor_; 1617 }; 1618 1619 AtomicInteger index_; 1620 ClassLinker* const class_linker_; 1621 const jobject class_loader_; 1622 CompilerDriver* const compiler_; 1623 const DexFile* const dex_file_; 1624 const std::vector<const DexFile*>& dex_files_; 1625 ThreadPool* const thread_pool_; 1626 1627 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager); 1628}; 1629 1630// A fast version of SkipClass above if the class pointer is available 1631// that avoids the expensive FindInClassPath search. 1632static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass) 1633 REQUIRES_SHARED(Locks::mutator_lock_) { 1634 DCHECK(klass != nullptr); 1635 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile(); 1636 if (&dex_file != &original_dex_file) { 1637 if (class_loader == nullptr) { 1638 LOG(WARNING) << "Skipping class " << klass->PrettyDescriptor() << " from " 1639 << dex_file.GetLocation() << " previously found in " 1640 << original_dex_file.GetLocation(); 1641 } 1642 return true; 1643 } 1644 return false; 1645} 1646 1647static void CheckAndClearResolveException(Thread* self) 1648 REQUIRES_SHARED(Locks::mutator_lock_) { 1649 CHECK(self->IsExceptionPending()); 1650 mirror::Throwable* exception = self->GetException(); 1651 std::string temp; 1652 const char* descriptor = exception->GetClass()->GetDescriptor(&temp); 1653 const char* expected_exceptions[] = { 1654 "Ljava/lang/IllegalAccessError;", 1655 "Ljava/lang/IncompatibleClassChangeError;", 1656 "Ljava/lang/InstantiationError;", 1657 "Ljava/lang/LinkageError;", 1658 "Ljava/lang/NoClassDefFoundError;", 1659 "Ljava/lang/NoSuchFieldError;", 1660 "Ljava/lang/NoSuchMethodError;" 1661 }; 1662 bool found = false; 1663 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) { 1664 if (strcmp(descriptor, expected_exceptions[i]) == 0) { 1665 found = true; 1666 } 1667 } 1668 if (!found) { 1669 LOG(FATAL) << "Unexpected exception " << exception->Dump(); 1670 } 1671 self->ClearException(); 1672} 1673 1674bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file, 1675 uint16_t class_def_idx) const { 1676 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx); 1677 const uint8_t* class_data = dex_file.GetClassData(class_def); 1678 if (class_data == nullptr) { 1679 // Empty class such as a marker interface. 1680 return false; 1681 } 1682 ClassDataItemIterator it(dex_file, class_data); 1683 while (it.HasNextStaticField()) { 1684 it.Next(); 1685 } 1686 // We require a constructor barrier if there are final instance fields. 1687 while (it.HasNextInstanceField()) { 1688 if (it.MemberIsFinal()) { 1689 return true; 1690 } 1691 it.Next(); 1692 } 1693 return false; 1694} 1695 1696class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor { 1697 public: 1698 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager) 1699 : manager_(manager) {} 1700 1701 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) { 1702 ATRACE_CALL(); 1703 Thread* const self = Thread::Current(); 1704 jobject jclass_loader = manager_->GetClassLoader(); 1705 const DexFile& dex_file = *manager_->GetDexFile(); 1706 ClassLinker* class_linker = manager_->GetClassLinker(); 1707 1708 // If an instance field is final then we need to have a barrier on the return, static final 1709 // fields are assigned within the lock held for class initialization. Conservatively assume 1710 // constructor barriers are always required. 1711 bool requires_constructor_barrier = true; 1712 1713 // Method and Field are the worst. We can't resolve without either 1714 // context from the code use (to disambiguate virtual vs direct 1715 // method and instance vs static field) or from class 1716 // definitions. While the compiler will resolve what it can as it 1717 // needs it, here we try to resolve fields and methods used in class 1718 // definitions, since many of them many never be referenced by 1719 // generated code. 1720 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index); 1721 ScopedObjectAccess soa(self); 1722 StackHandleScope<2> hs(soa.Self()); 1723 Handle<mirror::ClassLoader> class_loader( 1724 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader))); 1725 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache( 1726 soa.Self(), dex_file))); 1727 // Resolve the class. 1728 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache, 1729 class_loader); 1730 bool resolve_fields_and_methods; 1731 if (klass == nullptr) { 1732 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't 1733 // attempt to resolve methods and fields when there is no declaring class. 1734 CheckAndClearResolveException(soa.Self()); 1735 resolve_fields_and_methods = false; 1736 } else { 1737 // We successfully resolved a class, should we skip it? 1738 if (SkipClass(jclass_loader, dex_file, klass)) { 1739 return; 1740 } 1741 // We want to resolve the methods and fields eagerly. 1742 resolve_fields_and_methods = true; 1743 } 1744 // Note the class_data pointer advances through the headers, 1745 // static fields, instance fields, direct methods, and virtual 1746 // methods. 1747 const uint8_t* class_data = dex_file.GetClassData(class_def); 1748 if (class_data == nullptr) { 1749 // Empty class such as a marker interface. 1750 requires_constructor_barrier = false; 1751 } else { 1752 ClassDataItemIterator it(dex_file, class_data); 1753 while (it.HasNextStaticField()) { 1754 if (resolve_fields_and_methods) { 1755 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), 1756 dex_cache, class_loader, true); 1757 if (field == nullptr) { 1758 CheckAndClearResolveException(soa.Self()); 1759 } 1760 } 1761 it.Next(); 1762 } 1763 // We require a constructor barrier if there are final instance fields. 1764 requires_constructor_barrier = false; 1765 while (it.HasNextInstanceField()) { 1766 if (it.MemberIsFinal()) { 1767 requires_constructor_barrier = true; 1768 } 1769 if (resolve_fields_and_methods) { 1770 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), 1771 dex_cache, class_loader, false); 1772 if (field == nullptr) { 1773 CheckAndClearResolveException(soa.Self()); 1774 } 1775 } 1776 it.Next(); 1777 } 1778 if (resolve_fields_and_methods) { 1779 while (it.HasNextDirectMethod()) { 1780 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>( 1781 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr, 1782 it.GetMethodInvokeType(class_def)); 1783 if (method == nullptr) { 1784 CheckAndClearResolveException(soa.Self()); 1785 } 1786 it.Next(); 1787 } 1788 while (it.HasNextVirtualMethod()) { 1789 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>( 1790 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr, 1791 it.GetMethodInvokeType(class_def)); 1792 if (method == nullptr) { 1793 CheckAndClearResolveException(soa.Self()); 1794 } 1795 it.Next(); 1796 } 1797 DCHECK(!it.HasNext()); 1798 } 1799 } 1800 manager_->GetCompiler()->SetRequiresConstructorBarrier(self, 1801 &dex_file, 1802 class_def_index, 1803 requires_constructor_barrier); 1804 } 1805 1806 private: 1807 const ParallelCompilationManager* const manager_; 1808}; 1809 1810class ResolveTypeVisitor : public CompilationVisitor { 1811 public: 1812 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) { 1813 } 1814 void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) { 1815 // Class derived values are more complicated, they require the linker and loader. 1816 ScopedObjectAccess soa(Thread::Current()); 1817 ClassLinker* class_linker = manager_->GetClassLinker(); 1818 const DexFile& dex_file = *manager_->GetDexFile(); 1819 StackHandleScope<2> hs(soa.Self()); 1820 Handle<mirror::ClassLoader> class_loader( 1821 hs.NewHandle(soa.Decode<mirror::ClassLoader>(manager_->GetClassLoader()))); 1822 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile( 1823 dex_file, 1824 class_loader.Get()))); 1825 ObjPtr<mirror::Class> klass = (dex_cache != nullptr) 1826 ? class_linker->ResolveType(dex_file, dex::TypeIndex(type_idx), dex_cache, class_loader) 1827 : nullptr; 1828 1829 if (klass == nullptr) { 1830 soa.Self()->AssertPendingException(); 1831 mirror::Throwable* exception = soa.Self()->GetException(); 1832 VLOG(compiler) << "Exception during type resolution: " << exception->Dump(); 1833 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) { 1834 // There's little point continuing compilation if the heap is exhausted. 1835 LOG(FATAL) << "Out of memory during type resolution for compilation"; 1836 } 1837 soa.Self()->ClearException(); 1838 } 1839 } 1840 1841 private: 1842 const ParallelCompilationManager* const manager_; 1843}; 1844 1845void CompilerDriver::ResolveDexFile(jobject class_loader, 1846 const DexFile& dex_file, 1847 const std::vector<const DexFile*>& dex_files, 1848 ThreadPool* thread_pool, 1849 size_t thread_count, 1850 TimingLogger* timings) { 1851 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 1852 1853 // TODO: we could resolve strings here, although the string table is largely filled with class 1854 // and method names. 1855 1856 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files, 1857 thread_pool); 1858 if (GetCompilerOptions().IsBootImage()) { 1859 // For images we resolve all types, such as array, whereas for applications just those with 1860 // classdefs are resolved by ResolveClassFieldsAndMethods. 1861 TimingLogger::ScopedTiming t("Resolve Types", timings); 1862 ResolveTypeVisitor visitor(&context); 1863 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count); 1864 } 1865 1866 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings); 1867 ResolveClassFieldsAndMethodsVisitor visitor(&context); 1868 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count); 1869} 1870 1871void CompilerDriver::SetVerified(jobject class_loader, 1872 const std::vector<const DexFile*>& dex_files, 1873 TimingLogger* timings) { 1874 // This can be run in parallel. 1875 for (const DexFile* dex_file : dex_files) { 1876 CHECK(dex_file != nullptr); 1877 SetVerifiedDexFile(class_loader, 1878 *dex_file, 1879 dex_files, 1880 parallel_thread_pool_.get(), 1881 parallel_thread_count_, 1882 timings); 1883 } 1884} 1885 1886static void PopulateVerifiedMethods(const DexFile& dex_file, 1887 uint32_t class_def_index, 1888 VerificationResults* verification_results) { 1889 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index); 1890 const uint8_t* class_data = dex_file.GetClassData(class_def); 1891 if (class_data == nullptr) { 1892 return; 1893 } 1894 ClassDataItemIterator it(dex_file, class_data); 1895 // Skip fields 1896 while (it.HasNextStaticField()) { 1897 it.Next(); 1898 } 1899 while (it.HasNextInstanceField()) { 1900 it.Next(); 1901 } 1902 1903 while (it.HasNextDirectMethod()) { 1904 verification_results->CreateVerifiedMethodFor(MethodReference(&dex_file, it.GetMemberIndex())); 1905 it.Next(); 1906 } 1907 1908 while (it.HasNextVirtualMethod()) { 1909 verification_results->CreateVerifiedMethodFor(MethodReference(&dex_file, it.GetMemberIndex())); 1910 it.Next(); 1911 } 1912 DCHECK(!it.HasNext()); 1913} 1914 1915static void LoadAndUpdateStatus(const DexFile& dex_file, 1916 const DexFile::ClassDef& class_def, 1917 mirror::Class::Status status, 1918 Handle<mirror::ClassLoader> class_loader, 1919 Thread* self) 1920 REQUIRES_SHARED(Locks::mutator_lock_) { 1921 StackHandleScope<1> hs(self); 1922 const char* descriptor = dex_file.GetClassDescriptor(class_def); 1923 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 1924 Handle<mirror::Class> cls(hs.NewHandle<mirror::Class>( 1925 class_linker->FindClass(self, descriptor, class_loader))); 1926 if (cls != nullptr) { 1927 // Check that the class is resolved with the current dex file. We might get 1928 // a boot image class, or a class in a different dex file for multidex, and 1929 // we should not update the status in that case. 1930 if (&cls->GetDexFile() == &dex_file) { 1931 ObjectLock<mirror::Class> lock(self, cls); 1932 mirror::Class::SetStatus(cls, status, self); 1933 } 1934 } else { 1935 DCHECK(self->IsExceptionPending()); 1936 self->ClearException(); 1937 } 1938} 1939 1940bool CompilerDriver::FastVerify(jobject jclass_loader, 1941 const std::vector<const DexFile*>& dex_files, 1942 TimingLogger* timings) { 1943 verifier::VerifierDeps* verifier_deps = 1944 Runtime::Current()->GetCompilerCallbacks()->GetVerifierDeps(); 1945 // If there is an existing `VerifierDeps`, try to use it for fast verification. 1946 if (verifier_deps == nullptr) { 1947 return false; 1948 } 1949 TimingLogger::ScopedTiming t("Fast Verify", timings); 1950 ScopedObjectAccess soa(Thread::Current()); 1951 StackHandleScope<2> hs(soa.Self()); 1952 Handle<mirror::ClassLoader> class_loader( 1953 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader))); 1954 if (!verifier_deps->ValidateDependencies(class_loader, soa.Self())) { 1955 return false; 1956 } 1957 1958 bool compiler_only_verifies = !GetCompilerOptions().IsAnyCompilationEnabled(); 1959 1960 // We successfully validated the dependencies, now update class status 1961 // of verified classes. Note that the dependencies also record which classes 1962 // could not be fully verified; we could try again, but that would hurt verification 1963 // time. So instead we assume these classes still need to be verified at 1964 // runtime. 1965 for (const DexFile* dex_file : dex_files) { 1966 // Fetch the list of unverified classes and turn it into a set for faster 1967 // lookups. 1968 const std::vector<dex::TypeIndex>& unverified_classes = 1969 verifier_deps->GetUnverifiedClasses(*dex_file); 1970 std::set<dex::TypeIndex> set(unverified_classes.begin(), unverified_classes.end()); 1971 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) { 1972 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i); 1973 if (set.find(class_def.class_idx_) == set.end()) { 1974 if (compiler_only_verifies) { 1975 // Just update the compiled_classes_ map. The compiler doesn't need to resolve 1976 // the type. 1977 compiled_classes_.Overwrite(ClassReference(dex_file, i), mirror::Class::kStatusVerified); 1978 } else { 1979 // Update the class status, so later compilation stages know they don't need to verify 1980 // the class. 1981 LoadAndUpdateStatus( 1982 *dex_file, class_def, mirror::Class::kStatusVerified, class_loader, soa.Self()); 1983 // Create `VerifiedMethod`s for each methods, the compiler expects one for 1984 // quickening or compiling. 1985 // Note that this means: 1986 // - We're only going to compile methods that did verify. 1987 // - Quickening will not do checkcast ellision. 1988 // TODO(ngeoffray): Reconsider this once we refactor compiler filters. 1989 PopulateVerifiedMethods(*dex_file, i, verification_results_); 1990 } 1991 } else if (!compiler_only_verifies) { 1992 // Make sure later compilation stages know they should not try to verify 1993 // this class again. 1994 LoadAndUpdateStatus(*dex_file, 1995 class_def, 1996 mirror::Class::kStatusRetryVerificationAtRuntime, 1997 class_loader, 1998 soa.Self()); 1999 } 2000 } 2001 } 2002 return true; 2003} 2004 2005void CompilerDriver::Verify(jobject jclass_loader, 2006 const std::vector<const DexFile*>& dex_files, 2007 TimingLogger* timings) { 2008 if (FastVerify(jclass_loader, dex_files, timings)) { 2009 return; 2010 } 2011 2012 // If there is no existing `verifier_deps` (because of non-existing vdex), or 2013 // the existing `verifier_deps` is not valid anymore, create a new one for 2014 // non boot image compilation. The verifier will need it to record the new dependencies. 2015 // Then dex2oat can update the vdex file with these new dependencies. 2016 if (!GetCompilerOptions().IsBootImage()) { 2017 // Create the main VerifierDeps, and set it to this thread. 2018 verifier::VerifierDeps* verifier_deps = new verifier::VerifierDeps(dex_files); 2019 Runtime::Current()->GetCompilerCallbacks()->SetVerifierDeps(verifier_deps); 2020 Thread::Current()->SetVerifierDeps(verifier_deps); 2021 // Create per-thread VerifierDeps to avoid contention on the main one. 2022 // We will merge them after verification. 2023 for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) { 2024 worker->GetThread()->SetVerifierDeps(new verifier::VerifierDeps(dex_files)); 2025 } 2026 } 2027 2028 // Verification updates VerifierDeps and needs to run single-threaded to be deterministic. 2029 bool force_determinism = GetCompilerOptions().IsForceDeterminism(); 2030 ThreadPool* verify_thread_pool = 2031 force_determinism ? single_thread_pool_.get() : parallel_thread_pool_.get(); 2032 size_t verify_thread_count = force_determinism ? 1U : parallel_thread_count_; 2033 for (const DexFile* dex_file : dex_files) { 2034 CHECK(dex_file != nullptr); 2035 VerifyDexFile(jclass_loader, 2036 *dex_file, 2037 dex_files, 2038 verify_thread_pool, 2039 verify_thread_count, 2040 timings); 2041 } 2042 2043 if (!GetCompilerOptions().IsBootImage()) { 2044 // Merge all VerifierDeps into the main one. 2045 verifier::VerifierDeps* verifier_deps = Thread::Current()->GetVerifierDeps(); 2046 for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) { 2047 verifier::VerifierDeps* thread_deps = worker->GetThread()->GetVerifierDeps(); 2048 worker->GetThread()->SetVerifierDeps(nullptr); 2049 verifier_deps->MergeWith(*thread_deps, dex_files);; 2050 delete thread_deps; 2051 } 2052 Thread::Current()->SetVerifierDeps(nullptr); 2053 } 2054} 2055 2056class VerifyClassVisitor : public CompilationVisitor { 2057 public: 2058 VerifyClassVisitor(const ParallelCompilationManager* manager, verifier::HardFailLogMode log_level) 2059 : manager_(manager), log_level_(log_level) {} 2060 2061 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE { 2062 ATRACE_CALL(); 2063 ScopedObjectAccess soa(Thread::Current()); 2064 const DexFile& dex_file = *manager_->GetDexFile(); 2065 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index); 2066 const char* descriptor = dex_file.GetClassDescriptor(class_def); 2067 ClassLinker* class_linker = manager_->GetClassLinker(); 2068 jobject jclass_loader = manager_->GetClassLoader(); 2069 StackHandleScope<3> hs(soa.Self()); 2070 Handle<mirror::ClassLoader> class_loader( 2071 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader))); 2072 Handle<mirror::Class> klass( 2073 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader))); 2074 verifier::FailureKind failure_kind; 2075 if (klass == nullptr) { 2076 CHECK(soa.Self()->IsExceptionPending()); 2077 soa.Self()->ClearException(); 2078 2079 /* 2080 * At compile time, we can still structurally verify the class even if FindClass fails. 2081 * This is to ensure the class is structurally sound for compilation. An unsound class 2082 * will be rejected by the verifier and later skipped during compilation in the compiler. 2083 */ 2084 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache( 2085 soa.Self(), dex_file))); 2086 std::string error_msg; 2087 failure_kind = 2088 verifier::MethodVerifier::VerifyClass(soa.Self(), 2089 &dex_file, 2090 dex_cache, 2091 class_loader, 2092 class_def, 2093 Runtime::Current()->GetCompilerCallbacks(), 2094 true /* allow soft failures */, 2095 log_level_, 2096 &error_msg); 2097 if (failure_kind == verifier::FailureKind::kHardFailure) { 2098 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor) 2099 << " because: " << error_msg; 2100 manager_->GetCompiler()->SetHadHardVerifierFailure(); 2101 } else { 2102 // Force a soft failure for the VerifierDeps. This is a sanity measure, as 2103 // the vdex file already records that the class hasn't been resolved. It avoids 2104 // trying to do future verification optimizations when processing the vdex file. 2105 DCHECK(failure_kind == verifier::FailureKind::kSoftFailure || 2106 failure_kind == verifier::FailureKind::kNoFailure) 2107 << failure_kind; 2108 failure_kind = verifier::FailureKind::kSoftFailure; 2109 } 2110 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) { 2111 CHECK(klass->IsResolved()) << klass->PrettyClass(); 2112 failure_kind = class_linker->VerifyClass(soa.Self(), klass, log_level_); 2113 2114 if (klass->IsErroneous()) { 2115 // ClassLinker::VerifyClass throws, which isn't useful in the compiler. 2116 CHECK(soa.Self()->IsExceptionPending()); 2117 soa.Self()->ClearException(); 2118 manager_->GetCompiler()->SetHadHardVerifierFailure(); 2119 } 2120 2121 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerified() || klass->IsErroneous()) 2122 << klass->PrettyDescriptor() << ": state=" << klass->GetStatus(); 2123 2124 // Class has a meaningful status for the compiler now, record it. 2125 ClassReference ref(manager_->GetDexFile(), class_def_index); 2126 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus()); 2127 2128 // It is *very* problematic if there are verification errors in the boot classpath. For example, 2129 // we rely on things working OK without verification when the decryption dialog is brought up. 2130 // So abort in a debug build if we find this violated. 2131 if (kIsDebugBuild) { 2132 // TODO(narayan): Remove this special case for signature polymorphic 2133 // invokes once verifier support is fully implemented. 2134 if (manager_->GetCompiler()->GetCompilerOptions().IsBootImage() && 2135 !android::base::StartsWith(descriptor, "Ljava/lang/invoke/")) { 2136 DCHECK(klass->IsVerified()) << "Boot classpath class " << klass->PrettyClass() 2137 << " failed to fully verify: state= " << klass->GetStatus(); 2138 } 2139 if (klass->IsVerified()) { 2140 DCHECK_EQ(failure_kind, verifier::FailureKind::kNoFailure); 2141 } else if (klass->ShouldVerifyAtRuntime()) { 2142 DCHECK_EQ(failure_kind, verifier::FailureKind::kSoftFailure); 2143 } else { 2144 DCHECK_EQ(failure_kind, verifier::FailureKind::kHardFailure); 2145 } 2146 } 2147 } else { 2148 // Make the skip a soft failure, essentially being considered as verify at runtime. 2149 failure_kind = verifier::FailureKind::kSoftFailure; 2150 } 2151 verifier::VerifierDeps::MaybeRecordVerificationStatus( 2152 dex_file, class_def.class_idx_, failure_kind); 2153 soa.Self()->AssertNoPendingException(); 2154 } 2155 2156 private: 2157 const ParallelCompilationManager* const manager_; 2158 const verifier::HardFailLogMode log_level_; 2159}; 2160 2161void CompilerDriver::VerifyDexFile(jobject class_loader, 2162 const DexFile& dex_file, 2163 const std::vector<const DexFile*>& dex_files, 2164 ThreadPool* thread_pool, 2165 size_t thread_count, 2166 TimingLogger* timings) { 2167 TimingLogger::ScopedTiming t("Verify Dex File", timings); 2168 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 2169 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files, 2170 thread_pool); 2171 verifier::HardFailLogMode log_level = GetCompilerOptions().AbortOnHardVerifierFailure() 2172 ? verifier::HardFailLogMode::kLogInternalFatal 2173 : verifier::HardFailLogMode::kLogWarning; 2174 VerifyClassVisitor visitor(&context, log_level); 2175 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count); 2176} 2177 2178class SetVerifiedClassVisitor : public CompilationVisitor { 2179 public: 2180 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {} 2181 2182 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE { 2183 ATRACE_CALL(); 2184 ScopedObjectAccess soa(Thread::Current()); 2185 const DexFile& dex_file = *manager_->GetDexFile(); 2186 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index); 2187 const char* descriptor = dex_file.GetClassDescriptor(class_def); 2188 ClassLinker* class_linker = manager_->GetClassLinker(); 2189 jobject jclass_loader = manager_->GetClassLoader(); 2190 StackHandleScope<3> hs(soa.Self()); 2191 Handle<mirror::ClassLoader> class_loader( 2192 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader))); 2193 Handle<mirror::Class> klass( 2194 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader))); 2195 // Class might have failed resolution. Then don't set it to verified. 2196 if (klass != nullptr) { 2197 // Only do this if the class is resolved. If even resolution fails, quickening will go very, 2198 // very wrong. 2199 if (klass->IsResolved() && !klass->IsErroneousResolved()) { 2200 if (klass->GetStatus() < mirror::Class::kStatusVerified) { 2201 ObjectLock<mirror::Class> lock(soa.Self(), klass); 2202 // Set class status to verified. 2203 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self()); 2204 // Mark methods as pre-verified. If we don't do this, the interpreter will run with 2205 // access checks. 2206 klass->SetSkipAccessChecksFlagOnAllMethods( 2207 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet())); 2208 klass->SetVerificationAttempted(); 2209 } 2210 // Record the final class status if necessary. 2211 ClassReference ref(manager_->GetDexFile(), class_def_index); 2212 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus()); 2213 } 2214 } else { 2215 Thread* self = soa.Self(); 2216 DCHECK(self->IsExceptionPending()); 2217 self->ClearException(); 2218 } 2219 } 2220 2221 private: 2222 const ParallelCompilationManager* const manager_; 2223}; 2224 2225void CompilerDriver::SetVerifiedDexFile(jobject class_loader, 2226 const DexFile& dex_file, 2227 const std::vector<const DexFile*>& dex_files, 2228 ThreadPool* thread_pool, 2229 size_t thread_count, 2230 TimingLogger* timings) { 2231 TimingLogger::ScopedTiming t("Verify Dex File", timings); 2232 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 2233 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files, 2234 thread_pool); 2235 SetVerifiedClassVisitor visitor(&context); 2236 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count); 2237} 2238 2239class InitializeClassVisitor : public CompilationVisitor { 2240 public: 2241 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {} 2242 2243 void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE { 2244 ATRACE_CALL(); 2245 jobject jclass_loader = manager_->GetClassLoader(); 2246 const DexFile& dex_file = *manager_->GetDexFile(); 2247 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index); 2248 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_); 2249 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_); 2250 2251 ScopedObjectAccess soa(Thread::Current()); 2252 StackHandleScope<3> hs(soa.Self()); 2253 Handle<mirror::ClassLoader> class_loader( 2254 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader))); 2255 Handle<mirror::Class> klass( 2256 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader))); 2257 2258 if (klass != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) { 2259 // Only try to initialize classes that were successfully verified. 2260 if (klass->IsVerified()) { 2261 // Attempt to initialize the class but bail if we either need to initialize the super-class 2262 // or static fields. 2263 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false); 2264 if (!klass->IsInitialized()) { 2265 // We don't want non-trivial class initialization occurring on multiple threads due to 2266 // deadlock problems. For example, a parent class is initialized (holding its lock) that 2267 // refers to a sub-class in its static/class initializer causing it to try to acquire the 2268 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock) 2269 // after first initializing its parents, whose locks are acquired. This leads to a 2270 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock. 2271 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather 2272 // than use a special Object for the purpose we use the Class of java.lang.Class. 2273 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass())); 2274 ObjectLock<mirror::Class> lock(soa.Self(), h_klass); 2275 // Attempt to initialize allowing initialization of parent classes but still not static 2276 // fields. 2277 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true); 2278 if (!klass->IsInitialized()) { 2279 // We need to initialize static fields, we only do this for image classes that aren't 2280 // marked with the $NoPreloadHolder (which implies this should not be initialized early). 2281 bool can_init_static_fields = 2282 manager_->GetCompiler()->GetCompilerOptions().IsBootImage() && 2283 manager_->GetCompiler()->IsImageClass(descriptor) && 2284 !StringPiece(descriptor).ends_with("$NoPreloadHolder;"); 2285 if (can_init_static_fields) { 2286 VLOG(compiler) << "Initializing: " << descriptor; 2287 // TODO multithreading support. We should ensure the current compilation thread has 2288 // exclusive access to the runtime and the transaction. To achieve this, we could use 2289 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity 2290 // checks in Thread::AssertThreadSuspensionIsAllowable. 2291 Runtime* const runtime = Runtime::Current(); 2292 Transaction transaction; 2293 2294 // Run the class initializer in transaction mode. 2295 runtime->EnterTransactionMode(&transaction); 2296 const mirror::Class::Status old_status = klass->GetStatus(); 2297 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true, 2298 true); 2299 // TODO we detach transaction from runtime to indicate we quit the transactional 2300 // mode which prevents the GC from visiting objects modified during the transaction. 2301 // Ensure GC is not run so don't access freed objects when aborting transaction. 2302 2303 { 2304 ScopedAssertNoThreadSuspension ants("Transaction end"); 2305 runtime->ExitTransactionMode(); 2306 2307 if (!success) { 2308 CHECK(soa.Self()->IsExceptionPending()); 2309 mirror::Throwable* exception = soa.Self()->GetException(); 2310 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of " 2311 << exception->Dump(); 2312 std::ostream* file_log = manager_->GetCompiler()-> 2313 GetCompilerOptions().GetInitFailureOutput(); 2314 if (file_log != nullptr) { 2315 *file_log << descriptor << "\n"; 2316 *file_log << exception->Dump() << "\n"; 2317 } 2318 soa.Self()->ClearException(); 2319 transaction.Rollback(); 2320 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored"; 2321 } 2322 } 2323 2324 if (!success) { 2325 // On failure, still intern strings of static fields and seen in <clinit>, as these 2326 // will be created in the zygote. This is separated from the transaction code just 2327 // above as we will allocate strings, so must be allowed to suspend. 2328 InternStrings(klass, class_loader); 2329 } 2330 } 2331 } 2332 soa.Self()->AssertNoPendingException(); 2333 } 2334 } 2335 // Record the final class status if necessary. 2336 ClassReference ref(manager_->GetDexFile(), class_def_index); 2337 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus()); 2338 } 2339 // Clear any class not found or verification exceptions. 2340 soa.Self()->ClearException(); 2341 } 2342 2343 private: 2344 void InternStrings(Handle<mirror::Class> klass, Handle<mirror::ClassLoader> class_loader) 2345 REQUIRES_SHARED(Locks::mutator_lock_) { 2346 DCHECK(manager_->GetCompiler()->GetCompilerOptions().IsBootImage()); 2347 DCHECK(klass->IsVerified()); 2348 DCHECK(!klass->IsInitialized()); 2349 2350 StackHandleScope<1> hs(Thread::Current()); 2351 Handle<mirror::DexCache> h_dex_cache = hs.NewHandle(klass->GetDexCache()); 2352 const DexFile* dex_file = manager_->GetDexFile(); 2353 const DexFile::ClassDef* class_def = klass->GetClassDef(); 2354 ClassLinker* class_linker = manager_->GetClassLinker(); 2355 2356 // Check encoded final field values for strings and intern. 2357 annotations::RuntimeEncodedStaticFieldValueIterator value_it(*dex_file, 2358 &h_dex_cache, 2359 &class_loader, 2360 manager_->GetClassLinker(), 2361 *class_def); 2362 for ( ; value_it.HasNext(); value_it.Next()) { 2363 if (value_it.GetValueType() == annotations::RuntimeEncodedStaticFieldValueIterator::kString) { 2364 // Resolve the string. This will intern the string. 2365 art::ObjPtr<mirror::String> resolved = class_linker->ResolveString( 2366 *dex_file, dex::StringIndex(value_it.GetJavaValue().i), h_dex_cache); 2367 CHECK(resolved != nullptr); 2368 } 2369 } 2370 2371 // Intern strings seen in <clinit>. 2372 ArtMethod* clinit = klass->FindClassInitializer(class_linker->GetImagePointerSize()); 2373 if (clinit != nullptr) { 2374 const DexFile::CodeItem* code_item = clinit->GetCodeItem(); 2375 DCHECK(code_item != nullptr); 2376 const Instruction* inst = Instruction::At(code_item->insns_); 2377 2378 const uint32_t insns_size = code_item->insns_size_in_code_units_; 2379 for (uint32_t dex_pc = 0; dex_pc < insns_size;) { 2380 if (inst->Opcode() == Instruction::CONST_STRING) { 2381 ObjPtr<mirror::String> s = class_linker->ResolveString( 2382 *dex_file, dex::StringIndex(inst->VRegB_21c()), h_dex_cache); 2383 CHECK(s != nullptr); 2384 } else if (inst->Opcode() == Instruction::CONST_STRING_JUMBO) { 2385 ObjPtr<mirror::String> s = class_linker->ResolveString( 2386 *dex_file, dex::StringIndex(inst->VRegB_31c()), h_dex_cache); 2387 CHECK(s != nullptr); 2388 } 2389 dex_pc += inst->SizeInCodeUnits(); 2390 inst = inst->Next(); 2391 } 2392 } 2393 } 2394 2395 const ParallelCompilationManager* const manager_; 2396}; 2397 2398void CompilerDriver::InitializeClasses(jobject jni_class_loader, 2399 const DexFile& dex_file, 2400 const std::vector<const DexFile*>& dex_files, 2401 TimingLogger* timings) { 2402 TimingLogger::ScopedTiming t("InitializeNoClinit", timings); 2403 2404 // Initialization allocates objects and needs to run single-threaded to be deterministic. 2405 bool force_determinism = GetCompilerOptions().IsForceDeterminism(); 2406 ThreadPool* init_thread_pool = force_determinism 2407 ? single_thread_pool_.get() 2408 : parallel_thread_pool_.get(); 2409 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_; 2410 2411 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 2412 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files, 2413 init_thread_pool); 2414 if (GetCompilerOptions().IsBootImage()) { 2415 // TODO: remove this when transactional mode supports multithreading. 2416 init_thread_count = 1U; 2417 } 2418 InitializeClassVisitor visitor(&context); 2419 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count); 2420} 2421 2422class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor { 2423 public: 2424 explicit InitializeArrayClassesAndCreateConflictTablesVisitor(VariableSizedHandleScope& hs) 2425 : hs_(hs) {} 2426 2427 virtual bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE 2428 REQUIRES_SHARED(Locks::mutator_lock_) { 2429 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) { 2430 return true; 2431 } 2432 if (klass->IsArrayClass()) { 2433 StackHandleScope<1> hs(Thread::Current()); 2434 auto h_klass = hs.NewHandleWrapper(&klass); 2435 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(), h_klass, true, true); 2436 } 2437 // Collect handles since there may be thread suspension in future EnsureInitialized. 2438 to_visit_.push_back(hs_.NewHandle(klass)); 2439 return true; 2440 } 2441 2442 void FillAllIMTAndConflictTables() REQUIRES_SHARED(Locks::mutator_lock_) { 2443 for (Handle<mirror::Class> c : to_visit_) { 2444 // Create the conflict tables. 2445 FillIMTAndConflictTables(c.Get()); 2446 } 2447 } 2448 2449 private: 2450 void FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) 2451 REQUIRES_SHARED(Locks::mutator_lock_) { 2452 if (!klass->ShouldHaveImt()) { 2453 return; 2454 } 2455 if (visited_classes_.find(klass) != visited_classes_.end()) { 2456 return; 2457 } 2458 if (klass->HasSuperClass()) { 2459 FillIMTAndConflictTables(klass->GetSuperClass()); 2460 } 2461 if (!klass->IsTemp()) { 2462 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass); 2463 } 2464 visited_classes_.insert(klass); 2465 } 2466 2467 VariableSizedHandleScope& hs_; 2468 std::vector<Handle<mirror::Class>> to_visit_; 2469 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> visited_classes_; 2470}; 2471 2472void CompilerDriver::InitializeClasses(jobject class_loader, 2473 const std::vector<const DexFile*>& dex_files, 2474 TimingLogger* timings) { 2475 for (size_t i = 0; i != dex_files.size(); ++i) { 2476 const DexFile* dex_file = dex_files[i]; 2477 CHECK(dex_file != nullptr); 2478 InitializeClasses(class_loader, *dex_file, dex_files, timings); 2479 } 2480 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsAppImage()) { 2481 // Make sure that we call EnsureIntiailized on all the array classes to call 2482 // SetVerificationAttempted so that the access flags are set. If we do not do this they get 2483 // changed at runtime resulting in more dirty image pages. 2484 // Also create conflict tables. 2485 // Only useful if we are compiling an image (image_classes_ is not null). 2486 ScopedObjectAccess soa(Thread::Current()); 2487 VariableSizedHandleScope hs(soa.Self()); 2488 InitializeArrayClassesAndCreateConflictTablesVisitor visitor(hs); 2489 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor); 2490 visitor.FillAllIMTAndConflictTables(); 2491 } 2492 if (GetCompilerOptions().IsBootImage()) { 2493 // Prune garbage objects created during aborted transactions. 2494 Runtime::Current()->GetHeap()->CollectGarbage(true); 2495 } 2496} 2497 2498void CompilerDriver::Compile(jobject class_loader, 2499 const std::vector<const DexFile*>& dex_files, 2500 TimingLogger* timings) { 2501 if (kDebugProfileGuidedCompilation) { 2502 LOG(INFO) << "[ProfileGuidedCompilation] " << 2503 ((profile_compilation_info_ == nullptr) 2504 ? "null" 2505 : profile_compilation_info_->DumpInfo(&dex_files)); 2506 } 2507 2508 DCHECK(current_dex_to_dex_methods_ == nullptr); 2509 for (const DexFile* dex_file : dex_files) { 2510 CHECK(dex_file != nullptr); 2511 CompileDexFile(class_loader, 2512 *dex_file, 2513 dex_files, 2514 parallel_thread_pool_.get(), 2515 parallel_thread_count_, 2516 timings); 2517 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool(); 2518 const size_t arena_alloc = arena_pool->GetBytesAllocated(); 2519 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_); 2520 Runtime::Current()->ReclaimArenaPoolMemory(); 2521 } 2522 2523 ArrayRef<DexFileMethodSet> dex_to_dex_references; 2524 { 2525 // From this point on, we shall not modify dex_to_dex_references_, so 2526 // just grab a reference to it that we use without holding the mutex. 2527 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_); 2528 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_); 2529 } 2530 for (const auto& method_set : dex_to_dex_references) { 2531 current_dex_to_dex_methods_ = &method_set.GetMethodIndexes(); 2532 CompileDexFile(class_loader, 2533 method_set.GetDexFile(), 2534 dex_files, 2535 parallel_thread_pool_.get(), 2536 parallel_thread_count_, 2537 timings); 2538 } 2539 current_dex_to_dex_methods_ = nullptr; 2540 2541 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false); 2542} 2543 2544class CompileClassVisitor : public CompilationVisitor { 2545 public: 2546 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {} 2547 2548 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE { 2549 ATRACE_CALL(); 2550 const DexFile& dex_file = *manager_->GetDexFile(); 2551 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index); 2552 ClassLinker* class_linker = manager_->GetClassLinker(); 2553 jobject jclass_loader = manager_->GetClassLoader(); 2554 ClassReference ref(&dex_file, class_def_index); 2555 // Skip compiling classes with generic verifier failures since they will still fail at runtime 2556 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) { 2557 return; 2558 } 2559 // Use a scoped object access to perform to the quick SkipClass check. 2560 const char* descriptor = dex_file.GetClassDescriptor(class_def); 2561 ScopedObjectAccess soa(Thread::Current()); 2562 StackHandleScope<3> hs(soa.Self()); 2563 Handle<mirror::ClassLoader> class_loader( 2564 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader))); 2565 Handle<mirror::Class> klass( 2566 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader))); 2567 Handle<mirror::DexCache> dex_cache; 2568 if (klass == nullptr) { 2569 soa.Self()->AssertPendingException(); 2570 soa.Self()->ClearException(); 2571 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file)); 2572 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) { 2573 return; 2574 } else { 2575 dex_cache = hs.NewHandle(klass->GetDexCache()); 2576 } 2577 2578 const uint8_t* class_data = dex_file.GetClassData(class_def); 2579 if (class_data == nullptr) { 2580 // empty class, probably a marker interface 2581 return; 2582 } 2583 2584 // Go to native so that we don't block GC during compilation. 2585 ScopedThreadSuspension sts(soa.Self(), kNative); 2586 2587 CompilerDriver* const driver = manager_->GetCompiler(); 2588 2589 // Can we run DEX-to-DEX compiler on this class ? 2590 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level = 2591 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def); 2592 2593 ClassDataItemIterator it(dex_file, class_data); 2594 // Skip fields 2595 while (it.HasNextStaticField()) { 2596 it.Next(); 2597 } 2598 while (it.HasNextInstanceField()) { 2599 it.Next(); 2600 } 2601 2602 bool compilation_enabled = driver->IsClassToCompile( 2603 dex_file.StringByTypeIdx(class_def.class_idx_)); 2604 2605 // Compile direct methods 2606 int64_t previous_direct_method_idx = -1; 2607 while (it.HasNextDirectMethod()) { 2608 uint32_t method_idx = it.GetMemberIndex(); 2609 if (method_idx == previous_direct_method_idx) { 2610 // smali can create dex files with two encoded_methods sharing the same method_idx 2611 // http://code.google.com/p/smali/issues/detail?id=119 2612 it.Next(); 2613 continue; 2614 } 2615 previous_direct_method_idx = method_idx; 2616 CompileMethod(soa.Self(), 2617 driver, 2618 it.GetMethodCodeItem(), 2619 it.GetMethodAccessFlags(), 2620 it.GetMethodInvokeType(class_def), 2621 class_def_index, 2622 method_idx, 2623 class_loader, 2624 dex_file, 2625 dex_to_dex_compilation_level, 2626 compilation_enabled, 2627 dex_cache); 2628 it.Next(); 2629 } 2630 // Compile virtual methods 2631 int64_t previous_virtual_method_idx = -1; 2632 while (it.HasNextVirtualMethod()) { 2633 uint32_t method_idx = it.GetMemberIndex(); 2634 if (method_idx == previous_virtual_method_idx) { 2635 // smali can create dex files with two encoded_methods sharing the same method_idx 2636 // http://code.google.com/p/smali/issues/detail?id=119 2637 it.Next(); 2638 continue; 2639 } 2640 previous_virtual_method_idx = method_idx; 2641 CompileMethod(soa.Self(), 2642 driver, it.GetMethodCodeItem(), 2643 it.GetMethodAccessFlags(), 2644 it.GetMethodInvokeType(class_def), 2645 class_def_index, 2646 method_idx, 2647 class_loader, 2648 dex_file, 2649 dex_to_dex_compilation_level, 2650 compilation_enabled, 2651 dex_cache); 2652 it.Next(); 2653 } 2654 DCHECK(!it.HasNext()); 2655 } 2656 2657 private: 2658 const ParallelCompilationManager* const manager_; 2659}; 2660 2661void CompilerDriver::CompileDexFile(jobject class_loader, 2662 const DexFile& dex_file, 2663 const std::vector<const DexFile*>& dex_files, 2664 ThreadPool* thread_pool, 2665 size_t thread_count, 2666 TimingLogger* timings) { 2667 TimingLogger::ScopedTiming t("Compile Dex File", timings); 2668 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this, 2669 &dex_file, dex_files, thread_pool); 2670 CompileClassVisitor visitor(&context); 2671 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count); 2672} 2673 2674void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref, 2675 CompiledMethod* const compiled_method, 2676 size_t non_relative_linker_patch_count) { 2677 DCHECK(GetCompiledMethod(method_ref) == nullptr) 2678 << method_ref.dex_file->PrettyMethod(method_ref.dex_method_index); 2679 MethodTable::InsertResult result = compiled_methods_.Insert(method_ref, 2680 /*expected*/ nullptr, 2681 compiled_method); 2682 CHECK(result == MethodTable::kInsertResultSuccess); 2683 non_relative_linker_patch_count_.FetchAndAddRelaxed(non_relative_linker_patch_count); 2684 DCHECK(GetCompiledMethod(method_ref) != nullptr) 2685 << method_ref.dex_file->PrettyMethod(method_ref.dex_method_index); 2686} 2687 2688bool CompilerDriver::GetCompiledClass(ClassReference ref, mirror::Class::Status* status) const { 2689 DCHECK(status != nullptr); 2690 MutexLock mu(Thread::Current(), compiled_classes_lock_); 2691 ClassStateTable::const_iterator it = compiled_classes_.find(ref); 2692 if (it == compiled_classes_.end()) { 2693 return false; 2694 } 2695 *status = it->second; 2696 return true; 2697} 2698 2699void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) { 2700 switch (status) { 2701 case mirror::Class::kStatusNotReady: 2702 case mirror::Class::kStatusErrorResolved: 2703 case mirror::Class::kStatusErrorUnresolved: 2704 case mirror::Class::kStatusRetryVerificationAtRuntime: 2705 case mirror::Class::kStatusVerified: 2706 case mirror::Class::kStatusInitialized: 2707 case mirror::Class::kStatusResolved: 2708 break; // Expected states. 2709 default: 2710 LOG(FATAL) << "Unexpected class status for class " 2711 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second))) 2712 << " of " << status; 2713 } 2714 2715 MutexLock mu(Thread::Current(), compiled_classes_lock_); 2716 auto it = compiled_classes_.find(ref); 2717 if (it == compiled_classes_.end()) { 2718 compiled_classes_.Overwrite(ref, status); 2719 } else if (status > it->second) { 2720 // Update the status if we now have a greater one. This happens with vdex, 2721 // which records a class is verified, but does not resolve it. 2722 it->second = status; 2723 } 2724} 2725 2726CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const { 2727 CompiledMethod* compiled_method = nullptr; 2728 compiled_methods_.Get(ref, &compiled_method); 2729 return compiled_method; 2730} 2731 2732bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx, 2733 uint16_t class_def_idx, 2734 const DexFile& dex_file) const { 2735 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx); 2736 if (verified_method != nullptr) { 2737 return !verified_method->HasVerificationFailures(); 2738 } 2739 2740 // If we can't find verification metadata, check if this is a system class (we trust that system 2741 // classes have their methods verified). If it's not, be conservative and assume the method 2742 // has not been verified successfully. 2743 2744 // TODO: When compiling the boot image it should be safe to assume that everything is verified, 2745 // even if methods are not found in the verification cache. 2746 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx)); 2747 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 2748 Thread* self = Thread::Current(); 2749 ScopedObjectAccess soa(self); 2750 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr; 2751 if (!is_system_class) { 2752 self->ClearException(); 2753 } 2754 return is_system_class; 2755} 2756 2757size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const { 2758 return non_relative_linker_patch_count_.LoadRelaxed(); 2759} 2760 2761void CompilerDriver::SetRequiresConstructorBarrier(Thread* self, 2762 const DexFile* dex_file, 2763 uint16_t class_def_index, 2764 bool requires) { 2765 WriterMutexLock mu(self, requires_constructor_barrier_lock_); 2766 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires); 2767} 2768 2769bool CompilerDriver::RequiresConstructorBarrier(Thread* self, 2770 const DexFile* dex_file, 2771 uint16_t class_def_index) { 2772 ClassReference class_ref(dex_file, class_def_index); 2773 { 2774 ReaderMutexLock mu(self, requires_constructor_barrier_lock_); 2775 auto it = requires_constructor_barrier_.find(class_ref); 2776 if (it != requires_constructor_barrier_.end()) { 2777 return it->second; 2778 } 2779 } 2780 WriterMutexLock mu(self, requires_constructor_barrier_lock_); 2781 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index); 2782 requires_constructor_barrier_.emplace(class_ref, requires); 2783 return requires; 2784} 2785 2786std::string CompilerDriver::GetMemoryUsageString(bool extended) const { 2787 std::ostringstream oss; 2788 const gc::Heap* const heap = Runtime::Current()->GetHeap(); 2789 const size_t java_alloc = heap->GetBytesAllocated(); 2790 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)"; 2791 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)"; 2792#if defined(__BIONIC__) || defined(__GLIBC__) 2793 const struct mallinfo info = mallinfo(); 2794 const size_t allocated_space = static_cast<size_t>(info.uordblks); 2795 const size_t free_space = static_cast<size_t>(info.fordblks); 2796 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)" 2797 << " free=" << PrettySize(free_space) << " (" << free_space << "B)"; 2798#endif 2799 compiled_method_storage_.DumpMemoryUsage(oss, extended); 2800 return oss.str(); 2801} 2802 2803bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from, 2804 const DexFile* inlined_into) const { 2805 // We're not allowed to inline across dex files if we're the no-inline-from dex file. 2806 if (inlined_from != inlined_into && 2807 compiler_options_->GetNoInlineFromDexFile() != nullptr && 2808 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) { 2809 return false; 2810 } 2811 2812 return true; 2813} 2814 2815void CompilerDriver::InitializeThreadPools() { 2816 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0; 2817 parallel_thread_pool_.reset( 2818 new ThreadPool("Compiler driver thread pool", parallel_count)); 2819 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0)); 2820} 2821 2822void CompilerDriver::FreeThreadPools() { 2823 parallel_thread_pool_.reset(); 2824 single_thread_pool_.reset(); 2825} 2826 2827} // namespace art 2828