blob: f64b1cb6ae9e14ebc16a0354a931b0d766b3e02e [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
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 */
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070016
17#include "compiler.h"
18
Elliott Hughesd9c67be2012-02-02 19:54:06 -080019#include <vector>
20
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080021#include <dlfcn.h>
Brian Carlstrom27ec9612011-09-19 20:20:38 -070022#include <sys/mman.h>
Elliott Hughesd9c67be2012-02-02 19:54:06 -080023#include <unistd.h>
Brian Carlstrom27ec9612011-09-19 20:20:38 -070024
Brian Carlstrom2cc022b2011-08-25 10:05:39 -070025#include "assembler.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070026#include "class_linker.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070027#include "class_loader.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070028#include "dex_cache.h"
jeffhaof56197c2012-03-05 18:01:54 -080029#include "dex_verifier.h"
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -070030#include "jni_internal.h"
Logan Chien4dd96f52012-02-29 01:26:58 +080031#include "oat_compilation_unit.h"
Brian Carlstrom3320cf42011-10-04 14:58:28 -070032#include "oat_file.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080033#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070034#include "runtime.h"
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080035#include "space.h"
Brian Carlstrom3320cf42011-10-04 14:58:28 -070036#include "stl_util.h"
Elliott Hughes601a1232012-02-02 17:47:38 -080037#include "timing_logger.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070038
Elliott Hughes059d5c12012-03-12 17:39:18 -070039#if defined(__APPLE__)
40#include <mach-o/dyld.h>
41#endif
42
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070043namespace art {
44
Shih-wei Liaoc486c112011-09-13 16:43:52 -070045namespace arm {
Ian Rogersbdb03912011-09-14 00:55:44 -070046 ByteArray* CreateAbstractMethodErrorStub();
Ian Rogers1cb0a1d2011-10-06 15:24:35 -070047 ByteArray* ArmCreateResolutionTrampoline(Runtime::TrampolineType type);
Elliott Hughes8add92d2012-01-18 18:18:43 -080048 ByteArray* CreateJniDlsymLookupStub();
Shih-wei Liaoc486c112011-09-13 16:43:52 -070049}
Shih-wei Liaoc486c112011-09-13 16:43:52 -070050namespace x86 {
Ian Rogersbdb03912011-09-14 00:55:44 -070051 ByteArray* CreateAbstractMethodErrorStub();
Ian Rogers1cb0a1d2011-10-06 15:24:35 -070052 ByteArray* X86CreateResolutionTrampoline(Runtime::TrampolineType type);
Elliott Hughes8add92d2012-01-18 18:18:43 -080053 ByteArray* CreateJniDlsymLookupStub();
Brian Carlstrome24fa612011-09-29 00:53:55 -070054}
55
Ian Rogers996cc582012-02-14 22:23:29 -080056static double Percentage(size_t x, size_t y) {
57 return 100.0 * ((double)x) / ((double)(x + y));
58}
59
60static void DumpStat(size_t x, size_t y, const char* str) {
61 if (x == 0 && y == 0) {
62 return;
63 }
64 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
65}
66
Ian Rogersc8b306f2012-02-17 21:34:44 -080067class AOTCompilationStats {
68 public:
69 AOTCompilationStats() : stats_lock_("AOT compilation statistics lock"),
70 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
71 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
72 resolved_types_(0), unresolved_types_(0),
73 resolved_instance_fields_(0), unresolved_instance_fields_(0),
Ian Rogersfb6adba2012-03-04 21:51:51 -080074 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
75 virtual_made_direct_(0) {
Ian Rogersc8b306f2012-02-17 21:34:44 -080076 for (size_t i = 0; i < kMaxInvokeType; i++) {
77 resolved_methods_[i] = 0;
78 unresolved_methods_[i] = 0;
79 }
80 }
81
82 void Dump() {
83 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
84 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
85 DumpStat(resolved_types_, unresolved_types_, "types resolved");
86 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
87 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
88 "static fields resolved");
89 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
90 "static fields local to a class");
91
92 for (size_t i = 0; i < kMaxInvokeType; i++) {
93 std::ostringstream oss;
94 oss << "resolved " << static_cast<InvokeType>(i) << " methods";
95 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
96 }
Ian Rogersfb6adba2012-03-04 21:51:51 -080097 DumpStat(virtual_made_direct_, resolved_methods_[kVirtual] + unresolved_methods_[kVirtual],
98 "made direct from virtual");
Ian Rogersc8b306f2012-02-17 21:34:44 -080099 }
Ian Rogers996cc582012-02-14 22:23:29 -0800100
101// Allow lossy statistics in non-debug builds
102#ifndef NDEBUG
103#define STATS_LOCK() MutexLock mu(stats_lock_)
104#else
105#define STATS_LOCK()
106#endif
107
Ian Rogersc8b306f2012-02-17 21:34:44 -0800108 void TypeInDexCache() {
109 STATS_LOCK();
110 types_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800111 }
Ian Rogers996cc582012-02-14 22:23:29 -0800112
Ian Rogersc8b306f2012-02-17 21:34:44 -0800113 void TypeNotInDexCache() {
114 STATS_LOCK();
115 types_not_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800116 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800117
118 void StringInDexCache() {
119 STATS_LOCK();
120 strings_in_dex_cache_++;
121 }
122
123 void StringNotInDexCache() {
124 STATS_LOCK();
125 strings_not_in_dex_cache_++;
126 }
127
128 void TypeDoesntNeedAccessCheck() {
129 STATS_LOCK();
130 resolved_types_++;
131 }
132
133 void TypeNeedsAccessCheck() {
134 STATS_LOCK();
135 unresolved_types_++;
136 }
137
138 void ResolvedInstanceField() {
139 STATS_LOCK();
140 resolved_instance_fields_++;
141 }
142
143 void UnresolvedInstanceField(){
144 STATS_LOCK();
145 unresolved_instance_fields_++;
146 }
147
148 void ResolvedLocalStaticField() {
149 STATS_LOCK();
150 resolved_local_static_fields_++;
151 }
152
153 void ResolvedStaticField() {
154 STATS_LOCK();
155 resolved_static_fields_++;
156 }
157
158 void UnresolvedStaticField() {
159 STATS_LOCK();
160 unresolved_static_fields_++;
161 }
162
163 void ResolvedMethod(InvokeType type) {
164 DCHECK_LE(type, kMaxInvokeType);
165 STATS_LOCK();
166 resolved_methods_[type]++;
167 }
168
169 void UnresolvedMethod(InvokeType type) {
170 DCHECK_LE(type, kMaxInvokeType);
171 STATS_LOCK();
172 unresolved_methods_[type]++;
173 }
174
Ian Rogersfb6adba2012-03-04 21:51:51 -0800175 void VirtualMadeDirect() {
176 STATS_LOCK();
177 virtual_made_direct_++;
178 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800179 private:
180 Mutex stats_lock_;
181
182 size_t types_in_dex_cache_;
183 size_t types_not_in_dex_cache_;
184
185 size_t strings_in_dex_cache_;
186 size_t strings_not_in_dex_cache_;
187
188 size_t resolved_types_;
189 size_t unresolved_types_;
190
191 size_t resolved_instance_fields_;
192 size_t unresolved_instance_fields_;
193
194 size_t resolved_local_static_fields_;
195 size_t resolved_static_fields_;
196 size_t unresolved_static_fields_;
197
198 size_t resolved_methods_[kMaxInvokeType + 1];
199 size_t unresolved_methods_[kMaxInvokeType + 1];
Ian Rogersfb6adba2012-03-04 21:51:51 -0800200 size_t virtual_made_direct_;
Ian Rogersc8b306f2012-02-17 21:34:44 -0800201
202 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);;
203};
Ian Rogers996cc582012-02-14 22:23:29 -0800204
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800205static std::string MakeCompilerSoName(InstructionSet instruction_set) {
206 // TODO: is the ARM/Thumb2 instruction set distinction really buying us anything,
207 // or just causing hassle like this?
208 if (instruction_set == kThumb2) {
209 instruction_set = kArm;
210 }
211
Elliott Hughes059d5c12012-03-12 17:39:18 -0700212 // Capitalize the instruction set, because that's what we do in the build system.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800213 std::ostringstream instruction_set_name_os;
214 instruction_set_name_os << instruction_set;
215 std::string instruction_set_name(instruction_set_name_os.str());
216 for (size_t i = 0; i < instruction_set_name.size(); ++i) {
217 instruction_set_name[i] = toupper(instruction_set_name[i]);
218 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700219
220 // Bad things happen if we pull in the libartd-compiler to a libart dex2oat or vice versa,
221 // because we end up with both libart and libartd in the same address space!
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800222#ifndef NDEBUG
223 const char* suffix = "d";
224#else
225 const char* suffix = "";
226#endif
Elliott Hughes059d5c12012-03-12 17:39:18 -0700227
228 // Work out the filename for the compiler library.
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800229#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes059d5c12012-03-12 17:39:18 -0700230 std::string library_name(StringPrintf("art%s-compiler-%s", suffix, instruction_set_name.c_str()));
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800231#else
232 std::string library_name(StringPrintf("art%s-compiler-llvm", suffix));
233#endif
Elliott Hughes059d5c12012-03-12 17:39:18 -0700234 std::string filename(StringPrintf(OS_SHARED_LIB_FORMAT_STR, library_name.c_str()));
235
236#if defined(__APPLE__)
237 // On Linux, dex2oat will have been built with an RPATH of $ORIGIN/../lib, so dlopen(3) will find
238 // the .so by itself. On Mac OS, there isn't really an equivalent, so we have to manually do the
239 // same work.
240 std::vector<char> executable_path(1);
241 uint32_t executable_path_length = 0;
242 _NSGetExecutablePath(&executable_path[0], &executable_path_length);
243 while (_NSGetExecutablePath(&executable_path[0], &executable_path_length) == -1) {
244 executable_path.resize(executable_path_length);
245 }
246
247 executable_path.resize(executable_path.size() - 1); // Strip trailing NUL.
248 std::string path(&executable_path[0]);
249
250 // Strip the "/dex2oat".
251 size_t last_slash = path.find_last_of('/');
252 CHECK_NE(last_slash, std::string::npos) << path;
253 path.resize(last_slash);
254
255 // Strip the "/bin".
256 last_slash = path.find_last_of('/');
257 path.resize(last_slash);
258
259 filename = path + "/lib/" + filename;
260#endif
261 return filename;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800262}
263
Elliott Hughes46f060a2012-03-09 17:36:50 -0800264template<typename Fn>
265static Fn FindFunction(const std::string& compiler_so_name, void* library, const char* name) {
266 Fn fn = reinterpret_cast<Fn>(dlsym(library, name));
267 if (fn == NULL) {
268 LOG(FATAL) << "Couldn't find \"" << name << "\" in compiler library " << compiler_so_name << ": " << dlerror();
269 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700270 VLOG(compiler) << "Found \"" << name << "\" at " << reinterpret_cast<void*>(fn);
Elliott Hughes46f060a2012-03-09 17:36:50 -0800271 return fn;
272}
273
Elliott Hughes5523ee02012-02-03 18:18:34 -0800274Compiler::Compiler(InstructionSet instruction_set, bool image, size_t thread_count,
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800275 bool support_debugging, const std::set<std::string>* image_classes)
Brian Carlstromaded5f72011-10-07 17:15:04 -0700276 : instruction_set_(instruction_set),
Elliott Hughesc225caa2012-02-03 15:43:37 -0800277 compiled_classes_lock_("compiled classes lock"),
278 compiled_methods_lock_("compiled method lock"),
279 compiled_invoke_stubs_lock_("compiled invoke stubs lock"),
Brian Carlstromaded5f72011-10-07 17:15:04 -0700280 image_(image),
Elliott Hughes5523ee02012-02-03 18:18:34 -0800281 thread_count_(thread_count),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800282 support_debugging_(support_debugging),
Ian Rogersc8b306f2012-02-17 21:34:44 -0800283 stats_(new AOTCompilationStats),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800284 image_classes_(image_classes),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800285 compiler_library_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800286 compiler_(NULL),
Elliott Hughes6f4976c2012-03-13 21:19:01 -0700287 compiler_context_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800288 jni_compiler_(NULL),
289 create_invoke_stub_(NULL)
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800290{
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800291 std::string compiler_so_name(MakeCompilerSoName(instruction_set_));
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800292 compiler_library_ = dlopen(compiler_so_name.c_str(), RTLD_LAZY);
293 if (compiler_library_ == NULL) {
294 LOG(FATAL) << "Couldn't find compiler library " << compiler_so_name << ": " << dlerror();
295 }
296 VLOG(compiler) << "dlopen(\"" << compiler_so_name << "\", RTLD_LAZY) returned " << compiler_library_;
297
Elliott Hughes3fa1b7e2012-03-13 17:06:22 -0700298 compiler_ = FindFunction<CompilerFn>(compiler_so_name, compiler_library_, "ArtCompileMethod");
Elliott Hughes46f060a2012-03-09 17:36:50 -0800299 jni_compiler_ = FindFunction<JniCompilerFn>(compiler_so_name, compiler_library_, "ArtJniCompileMethod");
300 create_invoke_stub_ = FindFunction<CreateInvokeStubFn>(compiler_so_name, compiler_library_, "ArtCreateInvokeStub");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800301
Brian Carlstrom25c33252011-09-18 15:58:35 -0700302 CHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800303 if (!image_) {
304 CHECK(image_classes_ == NULL);
305 }
Shih-wei Liaoc486c112011-09-13 16:43:52 -0700306}
307
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700308Compiler::~Compiler() {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800309 {
310 MutexLock mu(compiled_classes_lock_);
311 STLDeleteValues(&compiled_classes_);
312 }
313 {
314 MutexLock mu(compiled_methods_lock_);
315 STLDeleteValues(&compiled_methods_);
316 }
317 {
318 MutexLock mu(compiled_invoke_stubs_lock_);
319 STLDeleteValues(&compiled_invoke_stubs_);
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800320 }
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800321#if defined(ART_USE_LLVM_COMPILER)
322 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
323 compiler_library_,
324 "compilerLLVMDispose");
325 (*f)(*this);
326#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800327 if (compiler_library_ != NULL) {
328 VLOG(compiler) << "dlclose(" << compiler_library_ << ")";
329 dlclose(compiler_library_);
330 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700331}
332
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700333ByteArray* Compiler::CreateResolutionStub(InstructionSet instruction_set,
334 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700335 if (instruction_set == kX86) {
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700336 return x86::X86CreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700337 } else {
338 CHECK(instruction_set == kArm || instruction_set == kThumb2);
339 // Generates resolution stub using ARM instruction set
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700340 return arm::ArmCreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700341 }
342}
343
Elliott Hughes8add92d2012-01-18 18:18:43 -0800344ByteArray* Compiler::CreateJniDlsymLookupStub(InstructionSet instruction_set) {
Ian Rogers169c9a72011-11-13 20:13:17 -0800345 switch (instruction_set) {
346 case kArm:
347 case kThumb2:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800348 return arm::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800349 case kX86:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800350 return x86::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800351 default:
Ian Rogers49c48942012-03-11 15:15:37 -0700352 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
Ian Rogers169c9a72011-11-13 20:13:17 -0800353 return NULL;
354 }
355}
356
Ian Rogersad25ac52011-10-04 19:13:33 -0700357ByteArray* Compiler::CreateAbstractMethodErrorStub(InstructionSet instruction_set) {
358 if (instruction_set == kX86) {
359 return x86::CreateAbstractMethodErrorStub();
360 } else {
361 CHECK(instruction_set == kArm || instruction_set == kThumb2);
362 // Generates resolution stub using ARM instruction set
363 return arm::CreateAbstractMethodErrorStub();
364 }
365}
366
Jesse Wilson254db0f2011-11-16 16:44:11 -0500367void Compiler::CompileAll(const ClassLoader* class_loader,
Brian Carlstromae826982011-11-09 01:33:42 -0800368 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700369 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800370
Elliott Hughes601a1232012-02-02 17:47:38 -0800371 TimingLogger timings("compiler");
372
373 PreCompile(class_loader, dex_files, timings);
374
Brian Carlstromae826982011-11-09 01:33:42 -0800375 Compile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800376 timings.AddSplit("Compile");
377
Brian Carlstromae826982011-11-09 01:33:42 -0800378 PostCompile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800379 timings.AddSplit("PostCompile");
380
381 if (timings.GetTotalNs() > MsToNs(1000)) {
382 timings.Dump();
383 }
Ian Rogers996cc582012-02-14 22:23:29 -0800384
Ian Rogersc8b306f2012-02-17 21:34:44 -0800385 stats_->Dump();
Brian Carlstrom8a487412011-08-29 20:08:52 -0700386}
387
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700388void Compiler::CompileOne(const Method* method) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700389 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800390
Brian Carlstrom8a487412011-08-29 20:08:52 -0700391 const ClassLoader* class_loader = method->GetDeclaringClass()->GetClassLoader();
Brian Carlstromae826982011-11-09 01:33:42 -0800392
Ian Rogers0571d352011-11-03 19:51:38 -0700393 // Find the dex_file
394 const DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
395 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
Brian Carlstromae826982011-11-09 01:33:42 -0800396 std::vector<const DexFile*> dex_files;
397 dex_files.push_back(&dex_file);
398
Elliott Hughes601a1232012-02-02 17:47:38 -0800399 TimingLogger timings("CompileOne");
400 PreCompile(class_loader, dex_files, timings);
Brian Carlstromae826982011-11-09 01:33:42 -0800401
Ian Rogers0571d352011-11-03 19:51:38 -0700402 uint32_t method_idx = method->GetDexMethodIndex();
Ian Rogersa3760aa2011-11-14 14:32:37 -0800403 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
404 CompileMethod(code_item, method->GetAccessFlags(), method_idx, class_loader, dex_file);
Brian Carlstromae826982011-11-09 01:33:42 -0800405
406 PostCompile(class_loader, dex_files);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700407}
408
Brian Carlstromae826982011-11-09 01:33:42 -0800409void Compiler::Resolve(const ClassLoader* class_loader,
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800410 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -0800411 for (size_t i = 0; i != dex_files.size(); ++i) {
412 const DexFile* dex_file = dex_files[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700413 CHECK(dex_file != NULL);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800414 ResolveDexFile(class_loader, *dex_file, timings);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700415 }
416}
417
Brian Carlstromae826982011-11-09 01:33:42 -0800418void Compiler::PreCompile(const ClassLoader* class_loader,
Elliott Hughes601a1232012-02-02 17:47:38 -0800419 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800420 Resolve(class_loader, dex_files, timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800421
Brian Carlstromae826982011-11-09 01:33:42 -0800422 Verify(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800423 timings.AddSplit("PreCompile.Verify");
424
Brian Carlstromae826982011-11-09 01:33:42 -0800425 InitializeClassesWithoutClinit(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800426 timings.AddSplit("PreCompile.InitializeClassesWithoutClinit");
Brian Carlstromae826982011-11-09 01:33:42 -0800427}
428
429void Compiler::PostCompile(const ClassLoader* class_loader,
430 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800431 SetGcMaps(class_loader, dex_files);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800432#if defined(ART_USE_LLVM_COMPILER)
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800433 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
434 compiler_library_,
435 "compilerLLVMMaterializeRemainder");
436 (*f)(*this);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800437#endif
Brian Carlstromae826982011-11-09 01:33:42 -0800438}
439
440bool Compiler::IsImageClass(const std::string& descriptor) const {
441 if (image_classes_ == NULL) {
442 return true;
443 }
444 return image_classes_->find(descriptor) != image_classes_->end();
445}
446
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800447bool Compiler::CanAssumeTypeIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800448 uint32_t type_idx) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800449 if (!IsImage()) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800450 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800451 return false;
452 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800453 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800454 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800455 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800456 return false;
457 }
Ian Rogers996cc582012-02-14 22:23:29 -0800458 bool result = IsImageClass(ClassHelper(resolved_class).GetDescriptor());
459 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800460 stats_->TypeInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800461 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800462 stats_->TypeNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800463 }
464 return result;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800465}
466
Ian Rogers1bddec32012-02-04 12:27:34 -0800467bool Compiler::CanAssumeStringIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800468 uint32_t string_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800469 // TODO: Add support for loading strings referenced by image_classes_
470 // See also Compiler::ResolveDexFile
471
472 // The following is a test saying that if we're building the image without a restricted set of
473 // image classes then we can assume the string is present in the dex cache if it is there now
Ian Rogers996cc582012-02-14 22:23:29 -0800474 bool result = IsImage() && image_classes_ == NULL && dex_cache->GetResolvedString(string_idx) != NULL;
475 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800476 stats_->StringInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800477 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800478 stats_->StringNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800479 }
480 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800481}
482
483bool Compiler::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800484 const DexFile& dex_file, uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800485 // Get type from dex cache assuming it was populated by the verifier
486 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
487 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800488 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800489 return false; // Unknown class needs access checks.
490 }
491 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
492 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
493 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800494 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800495 return false; // Incomplete referrer knowledge needs access check.
496 }
497 // Perform access check, will return true if access is ok or false if we're going to have to
498 // check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800499 bool result = referrer_class->CanAccess(resolved_class);
500 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800501 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800502 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800503 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800504 }
505 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800506}
507
508bool Compiler::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
509 const DexCache* dex_cache,
510 const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800511 uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800512 // Get type from dex cache assuming it was populated by the verifier.
513 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
514 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800515 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800516 return false; // Unknown class needs access checks.
517 }
518 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
519 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
520 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800521 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800522 return false; // Incomplete referrer knowledge needs access check.
523 }
524 // Perform access and instantiable checks, will return true if access is ok or false if we're
525 // going to have to check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800526 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
527 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800528 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800529 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800530 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800531 }
532 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800533}
534
Logan Chien4dd96f52012-02-29 01:26:58 +0800535static Class* ComputeReferrerClass(OatCompilationUnit* mUnit) {
536 const DexFile::MethodId& referrer_method_id =
537 mUnit->dex_file_->GetMethodId(mUnit->method_idx_);
538
539 return mUnit->class_linker_->ResolveType(
540 *mUnit->dex_file_, referrer_method_id.class_idx_,
541 mUnit->dex_cache_, mUnit->class_loader_);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800542}
543
Logan Chien4dd96f52012-02-29 01:26:58 +0800544static Field* ComputeReferrerField(OatCompilationUnit* mUnit, uint32_t field_idx) {
545 return mUnit->class_linker_->ResolveField(
546 *mUnit->dex_file_, field_idx, mUnit->dex_cache_,
547 mUnit->class_loader_, false);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800548}
549
Logan Chien4dd96f52012-02-29 01:26:58 +0800550static Method* ComputeReferrerMethod(OatCompilationUnit* mUnit, uint32_t method_idx) {
551 return mUnit->class_linker_->ResolveMethod(
552 *mUnit->dex_file_, method_idx, mUnit->dex_cache_,
553 mUnit->class_loader_, true);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800554}
555
Logan Chien4dd96f52012-02-29 01:26:58 +0800556bool Compiler::ComputeInstanceFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
jeffhao8cd6dda2012-02-22 10:15:34 -0800557 int& field_offset, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800558 // Conservative defaults
559 field_offset = -1;
560 is_volatile = true;
561 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800562 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800563 if (resolved_field != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800564 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800565 // Try to resolve referring class then access check, failure to pass the
566 Class* fields_class = resolved_field->GetDeclaringClass();
jeffhao8cd6dda2012-02-22 10:15:34 -0800567 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal() &&
568 fields_class != referrer_class;
569 if (referrer_class != NULL && referrer_class->CanAccess(fields_class) &&
570 referrer_class->CanAccessMember(fields_class, resolved_field->GetAccessFlags()) &&
571 !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800572 field_offset = resolved_field->GetOffset().Int32Value();
573 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800574 stats_->ResolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800575 return true; // Fast path.
576 }
577 }
578 // Clean up any exception left by field/type resolution
579 Thread* thread = Thread::Current();
580 if (thread->IsExceptionPending()) {
581 thread->ClearException();
582 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800583 stats_->UnresolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800584 return false; // Incomplete knowledge needs slow path.
585}
586
Logan Chien4dd96f52012-02-29 01:26:58 +0800587bool Compiler::ComputeStaticFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
Ian Rogers1bddec32012-02-04 12:27:34 -0800588 int& field_offset, int& ssb_index,
jeffhao8cd6dda2012-02-22 10:15:34 -0800589 bool& is_referrers_class, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800590 // Conservative defaults
591 field_offset = -1;
592 ssb_index = -1;
593 is_referrers_class = false;
594 is_volatile = true;
595 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800596 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800597 if (resolved_field != NULL) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800598 DCHECK(resolved_field->IsStatic());
Logan Chien4dd96f52012-02-29 01:26:58 +0800599 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800600 if (referrer_class != NULL) {
jeffhao8cd6dda2012-02-22 10:15:34 -0800601 Class* fields_class = resolved_field->GetDeclaringClass();
602 if (fields_class == referrer_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800603 is_referrers_class = true; // implies no worrying about class initialization
604 field_offset = resolved_field->GetOffset().Int32Value();
605 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800606 stats_->ResolvedLocalStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800607 return true; // fast path
608 } else {
jeffhao8cd6dda2012-02-22 10:15:34 -0800609 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal();
Ian Rogers1bddec32012-02-04 12:27:34 -0800610 if (referrer_class->CanAccess(fields_class) &&
jeffhao8cd6dda2012-02-22 10:15:34 -0800611 referrer_class->CanAccessMember(fields_class, resolved_field->GetAccessFlags()) &&
612 !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800613 // We have the resolved field, we must make it into a ssbIndex for the referrer
614 // in its static storage base (which may fail if it doesn't have a slot for it)
Ian Rogers4103ad22012-02-06 09:18:25 -0800615 // TODO: for images we can elide the static storage base null check
616 // if we know there's a non-null entry in the image
Logan Chien4dd96f52012-02-29 01:26:58 +0800617 if (fields_class->GetDexCache() == mUnit->dex_cache_) {
Ian Rogers4103ad22012-02-06 09:18:25 -0800618 // common case where the dex cache of both the referrer and the field are the same,
619 // no need to search the dex file
620 ssb_index = fields_class->GetDexTypeIndex();
621 field_offset = resolved_field->GetOffset().Int32Value();
622 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800623 stats_->ResolvedStaticField();
Ian Rogers4103ad22012-02-06 09:18:25 -0800624 return true;
625 }
626 // Search dex file for localized ssb index
Ian Rogers1bddec32012-02-04 12:27:34 -0800627 std::string descriptor(FieldHelper(resolved_field).GetDeclaringClassDescriptor());
628 const DexFile::StringId* string_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800629 mUnit->dex_file_->FindStringId(descriptor);
Ian Rogers1bddec32012-02-04 12:27:34 -0800630 if (string_id != NULL) {
631 const DexFile::TypeId* type_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800632 mUnit->dex_file_->FindTypeId(mUnit->dex_file_->GetIndexForStringId(*string_id));
Ian Rogers1bddec32012-02-04 12:27:34 -0800633 if(type_id != NULL) {
634 // medium path, needs check of static storage base being initialized
Logan Chien4dd96f52012-02-29 01:26:58 +0800635 ssb_index = mUnit->dex_file_->GetIndexForTypeId(*type_id);
Ian Rogers1bddec32012-02-04 12:27:34 -0800636 field_offset = resolved_field->GetOffset().Int32Value();
637 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800638 stats_->ResolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800639 return true;
640 }
641 }
642 }
643 }
644 }
645 }
646 // Clean up any exception left by field/type resolution
647 Thread* thread = Thread::Current();
648 if (thread->IsExceptionPending()) {
649 thread->ClearException();
650 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800651 stats_->UnresolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800652 return false; // Incomplete knowledge needs slow path.
653}
654
Ian Rogersfb6adba2012-03-04 21:51:51 -0800655bool Compiler::ComputeInvokeInfo(uint32_t method_idx, OatCompilationUnit* mUnit, InvokeType& type,
Ian Rogers996cc582012-02-14 22:23:29 -0800656 int& vtable_idx) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800657 vtable_idx = -1;
Logan Chien4dd96f52012-02-29 01:26:58 +0800658 Method* resolved_method = ComputeReferrerMethod(mUnit, method_idx);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800659 if (resolved_method != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800660 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800661 if (referrer_class != NULL) {
662 Class* methods_class = resolved_method->GetDeclaringClass();
663 if (!referrer_class->CanAccess(methods_class) ||
664 !referrer_class->CanAccessMember(methods_class,
Ian Rogers996cc582012-02-14 22:23:29 -0800665 resolved_method->GetAccessFlags())) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800666 // The referring class can't access the resolved method, this may occur as a result of a
667 // protected method being made public by implementing an interface that re-declares the
668 // method public. Resort to the dex file to determine the correct class for the access check
Logan Chien4dd96f52012-02-29 01:26:58 +0800669 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800670 methods_class =
Logan Chien4dd96f52012-02-29 01:26:58 +0800671 mUnit->class_linker_->ResolveType(dex_file,
672 dex_file.GetMethodId(method_idx).class_idx_,
673 referrer_class);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800674
675 }
676 if (referrer_class->CanAccess(methods_class) &&
677 referrer_class->CanAccessMember(methods_class,
678 resolved_method->GetAccessFlags())) {
679 vtable_idx = resolved_method->GetMethodIndex();
Ian Rogersf320b632012-03-13 18:47:47 -0700680 const bool kEnableSharpening = true;
Ian Rogers9a8a8882012-03-08 02:30:55 -0800681 if (kEnableSharpening && type == kVirtual &&
682 (resolved_method->IsFinal() || methods_class->IsFinal())) {
Ian Rogersfb6adba2012-03-04 21:51:51 -0800683 stats_->ResolvedMethod(kVirtual);
684 // Sharpen a virtual call into a direct call. The method_idx is into referrer's
685 // dex cache, check that this resolved method is where we expect it.
686 CHECK(referrer_class->GetDexCache()->GetResolvedMethod(method_idx) == resolved_method)
687 << PrettyMethod(resolved_method);
688 type = kDirect;
689 stats_->VirtualMadeDirect();
690 return true;
691 } else if (type != kSuper) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800692 // nothing left to do for static/direct/virtual/interface dispatch
693 stats_->ResolvedMethod(type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800694 return true;
695 } else {
696 // ensure the vtable index will be correct to dispatch in the vtable of the super class
Ian Rogers996cc582012-02-14 22:23:29 -0800697 if (referrer_class->IsSubClass(methods_class) &&
698 vtable_idx < methods_class->GetVTable()->GetLength()) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800699 stats_->ResolvedMethod(type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800700 return true;
701 }
702 }
703 }
704 }
705 }
706 // Clean up any exception left by method/type resolution
707 Thread* thread = Thread::Current();
708 if (thread->IsExceptionPending()) {
709 thread->ClearException();
710 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800711 stats_->UnresolvedMethod(type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800712 return false; // Incomplete knowledge needs slow path.
713}
714
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800715// Return true if the class should be skipped during compilation. We
716// never skip classes in the boot class loader. However, if we have a
717// non-boot class loader and we can resolve the class in the boot
718// class loader, we do skip the class. This happens if an app bundles
719// classes found in the boot classpath. Since at runtime we will
720// select the class from the boot classpath, do not attempt to resolve
721// or compile it now.
722static bool SkipClass(const ClassLoader* class_loader,
723 const DexFile& dex_file,
724 const DexFile::ClassDef& class_def) {
725 if (class_loader == NULL) {
726 return false;
727 }
728 const char* descriptor = dex_file.GetClassDescriptor(class_def);
729 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
730 Class* klass = class_linker->FindClass(descriptor, NULL);
731 if (klass == NULL) {
732 Thread* self = Thread::Current();
733 CHECK(self->IsExceptionPending());
734 self->ClearException();
735 return false;
736 }
737 return true;
738}
739
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800740class Context {
741 public:
742 Context(ClassLinker* class_linker,
743 const ClassLoader* class_loader,
744 Compiler* compiler,
745 DexCache* dex_cache,
746 const DexFile* dex_file)
747 : class_linker_(class_linker),
748 class_loader_(class_loader),
749 compiler_(compiler),
750 dex_cache_(dex_cache),
751 dex_file_(dex_file) {}
752
753 ClassLinker* GetClassLinker() {
754 CHECK(class_linker_ != NULL);
755 return class_linker_;
756 }
757 const ClassLoader* GetClassLoader() {
758 return class_loader_;
759 }
760 Compiler* GetCompiler() {
761 CHECK(compiler_ != NULL);
762 return compiler_;
763 }
764 DexCache* GetDexCache() {
765 CHECK(dex_cache_ != NULL);
766 return dex_cache_;
767 }
768 const DexFile* GetDexFile() {
769 CHECK(dex_file_ != NULL);
770 return dex_file_;
771 }
772
773 private:
774 ClassLinker* class_linker_;
775 const ClassLoader* class_loader_;
776 Compiler* compiler_;
777 DexCache* dex_cache_;
778 const DexFile* dex_file_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800779};
780
781typedef void Callback(Context* context, size_t index);
782
783class WorkerThread {
784 public:
Elliott Hughes1e409252012-02-06 11:21:27 -0800785 WorkerThread(Context* context, size_t begin, size_t end, Callback callback, size_t stripe, bool spawn)
786 : spawn_(spawn), context_(context), begin_(begin), end_(end), callback_(callback), stripe_(stripe) {
787 if (spawn_) {
788 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, NULL, &Go, this), "compiler worker thread");
789 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800790 }
791
792 ~WorkerThread() {
Elliott Hughes1e409252012-02-06 11:21:27 -0800793 if (spawn_) {
794 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
795 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800796 }
797
798 private:
Elliott Hughes1e409252012-02-06 11:21:27 -0800799 static void* Go(void* arg) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800800 WorkerThread* worker = reinterpret_cast<WorkerThread*>(arg);
801 Runtime* runtime = Runtime::Current();
Elliott Hughes1e409252012-02-06 11:21:27 -0800802 if (worker->spawn_) {
803 runtime->AttachCurrentThread("Compiler Worker", true);
804 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800805 Thread::Current()->SetState(Thread::kRunnable);
806 worker->Run();
Elliott Hughes1e409252012-02-06 11:21:27 -0800807 if (worker->spawn_) {
808 Thread::Current()->SetState(Thread::kNative);
809 runtime->DetachCurrentThread();
810 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800811 return NULL;
812 }
813
Elliott Hughes1e409252012-02-06 11:21:27 -0800814 void Go() {
815 Go(this);
816 }
817
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800818 void Run() {
819 for (size_t i = begin_; i < end_; i += stripe_) {
820 callback_(context_, i);
821 }
822 }
823
824 pthread_t pthread_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800825 bool spawn_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800826
827 Context* context_;
828 size_t begin_;
829 size_t end_;
830 Callback* callback_;
831 size_t stripe_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800832
833 friend void ForAll(Context*, size_t, size_t, Callback, size_t);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800834};
835
Elliott Hughes5523ee02012-02-03 18:18:34 -0800836void ForAll(Context* context, size_t begin, size_t end, Callback callback, size_t thread_count) {
Elliott Hughes1e409252012-02-06 11:21:27 -0800837 CHECK_GT(thread_count, 0U);
Elliott Hughes81d91512012-02-03 16:38:43 -0800838
Elliott Hughes1e409252012-02-06 11:21:27 -0800839 std::vector<WorkerThread*> threads;
Elliott Hughes81d91512012-02-03 16:38:43 -0800840 for (size_t i = 0; i < thread_count; ++i) {
Elliott Hughes1e409252012-02-06 11:21:27 -0800841 threads.push_back(new WorkerThread(context, begin + i, end, callback, thread_count, (i != 0)));
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800842 }
Elliott Hughes1e409252012-02-06 11:21:27 -0800843 threads[0]->Go();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800844
Elliott Hughes81d91512012-02-03 16:38:43 -0800845 // Switch to kVmWait while we're blocked waiting for the other threads to finish.
846 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
847 STLDeleteElements(&threads);
848}
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800849
850static void ResolveClassFieldsAndMethods(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800851 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800852
853 // Method and Field are the worst. We can't resolve without either
854 // context from the code use (to disambiguate virtual vs direct
855 // method and instance vs static field) or from class
856 // definitions. While the compiler will resolve what it can as it
857 // needs it, here we try to resolve fields and methods used in class
858 // definitions, since many of them many never be referenced by
859 // generated code.
860 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800861 if (SkipClass(context->GetClassLoader(), dex_file, class_def)) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800862 return;
863 }
864
865 // Note the class_data pointer advances through the headers,
866 // static fields, instance fields, direct methods, and virtual
867 // methods.
868 const byte* class_data = dex_file.GetClassData(class_def);
869 if (class_data == NULL) {
870 // empty class such as a marker interface
871 return;
872 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800873 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800874 ClassLinker* class_linker = context->GetClassLinker();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800875 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
876 ClassDataItemIterator it(dex_file, class_data);
877 while (it.HasNextStaticField()) {
878 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800879 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800880 if (field == NULL) {
881 CHECK(self->IsExceptionPending());
882 self->ClearException();
883 }
884 it.Next();
885 }
886 while (it.HasNextInstanceField()) {
887 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800888 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800889 if (field == NULL) {
890 CHECK(self->IsExceptionPending());
891 self->ClearException();
892 }
893 it.Next();
894 }
895 while (it.HasNextDirectMethod()) {
896 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800897 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800898 if (method == NULL) {
899 CHECK(self->IsExceptionPending());
900 self->ClearException();
901 }
902 it.Next();
903 }
904 while (it.HasNextVirtualMethod()) {
905 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800906 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800907 if (method == NULL) {
908 CHECK(self->IsExceptionPending());
909 self->ClearException();
910 }
911 it.Next();
912 }
913 DCHECK(!it.HasNext());
914}
915
916static void ResolveType(Context* context, size_t type_idx) {
917 // Class derived values are more complicated, they require the linker and loader.
918 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800919 Class* klass = context->GetClassLinker()->ResolveType(*context->GetDexFile(),
920 type_idx,
921 context->GetDexCache(),
922 context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800923 if (klass == NULL) {
924 CHECK(self->IsExceptionPending());
925 Thread::Current()->ClearException();
926 }
927}
928
929void Compiler::ResolveDexFile(const ClassLoader* class_loader, const DexFile& dex_file, TimingLogger& timings) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700930 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromaded5f72011-10-07 17:15:04 -0700931 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700932
Brian Carlstromae826982011-11-09 01:33:42 -0800933 // Strings are easy in that they always are simply resolved to literals in the same file
934 if (image_ && image_classes_ == NULL) {
935 // TODO: Add support for loading strings referenced by image_classes_
936 // See also Compiler::CanAssumeTypeIsPresentInDexCache.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700937 for (size_t string_idx = 0; string_idx < dex_cache->NumStrings(); string_idx++) {
938 class_linker->ResolveString(dex_file, string_idx, dex_cache);
939 }
Elliott Hughesff738062012-02-03 15:00:42 -0800940 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Strings");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700941 }
942
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800943 Context context(class_linker, class_loader, this, dex_cache, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -0800944 ForAll(&context, 0, dex_cache->NumResolvedTypes(), ResolveType, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -0800945 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Types");
Brian Carlstrom845490b2011-09-19 15:56:53 -0700946
Elliott Hughes5523ee02012-02-03 18:18:34 -0800947 ForAll(&context, 0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -0800948 timings.AddSplit("Resolve " + dex_file.GetLocation() + " MethodsAndFields");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700949}
950
Brian Carlstromae826982011-11-09 01:33:42 -0800951void Compiler::Verify(const ClassLoader* class_loader,
952 const std::vector<const DexFile*>& dex_files) {
953 for (size_t i = 0; i != dex_files.size(); ++i) {
954 const DexFile* dex_file = dex_files[i];
jeffhao98eacac2011-09-14 16:11:53 -0700955 CHECK(dex_file != NULL);
956 VerifyDexFile(class_loader, *dex_file);
957 }
958}
959
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800960static void VerifyClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800961 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
962 const char* descriptor = context->GetDexFile()->GetClassDescriptor(class_def);
963 Class* klass = context->GetClassLinker()->FindClass(descriptor, context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800964 if (klass == NULL) {
965 Thread* self = Thread::Current();
966 CHECK(self->IsExceptionPending());
967 self->ClearException();
jeffhaof56197c2012-03-05 18:01:54 -0800968
969 /*
970 * At compile time, we can still structurally verify the class even if FindClass fails.
971 * This is to ensure the class is structurally sound for compilation. An unsound class
972 * will be rejected by the verifier and later skipped during compilation in the compiler.
973 */
974 std::string error_msg;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800975 if (!verifier::DexVerifier::VerifyClass(context->GetDexFile(), context->GetDexCache(),
976 context->GetClassLoader(), class_def_index, error_msg)) {
977 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
jeffhaof56197c2012-03-05 18:01:54 -0800978 LOG(ERROR) << "Verification failed on class "
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800979 << PrettyDescriptor(context->GetDexFile()->GetClassDescriptor(class_def))
jeffhaof56197c2012-03-05 18:01:54 -0800980 << " because: " << error_msg;
981 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800982 return;
983 }
984 CHECK(klass->IsResolved()) << PrettyClass(klass);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800985 context->GetClassLinker()->VerifyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800986
987 if (klass->IsErroneous()) {
988 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
989 CHECK(Thread::Current()->IsExceptionPending());
990 Thread::Current()->ClearException();
991 // We want to try verification again at run-time, so move back into the resolved state.
992 klass->SetStatus(Class::kStatusResolved);
993 }
994
995 CHECK(klass->IsVerified() || klass->IsResolved()) << PrettyClass(klass);
996 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
997}
998
jeffhao98eacac2011-09-14 16:11:53 -0700999void Compiler::VerifyDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
jeffhaob4df5142011-09-19 20:25:32 -07001000 dex_file.ChangePermissions(PROT_READ | PROT_WRITE);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001001
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001002 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1003 Context context(class_linker, class_loader, this, class_linker->FindDexCache(dex_file), &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001004 ForAll(&context, 0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001005
jeffhaob4df5142011-09-19 20:25:32 -07001006 dex_file.ChangePermissions(PROT_READ);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001007}
1008
Brian Carlstromae826982011-11-09 01:33:42 -08001009void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader,
1010 const std::vector<const DexFile*>& dex_files) {
1011 for (size_t i = 0; i != dex_files.size(); ++i) {
1012 const DexFile* dex_file = dex_files[i];
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001013 CHECK(dex_file != NULL);
1014 InitializeClassesWithoutClinit(class_loader, *dex_file);
1015 }
1016}
1017
1018void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader, const DexFile& dex_file) {
1019 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001020 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1021 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001022 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1023 Class* klass = class_linker->FindClass(descriptor, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001024 if (klass != NULL) {
1025 class_linker->EnsureInitialized(klass, false);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001026 // record the final class status if necessary
1027 Class::Status status = klass->GetStatus();
1028 ClassReference ref(&dex_file, class_def_index);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001029 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001030 CompiledClass* compiled_class = GetCompiledClass(ref);
1031 if (compiled_class == NULL) {
1032 compiled_class = new CompiledClass(status);
1033 compiled_classes_[ref] = compiled_class;
1034 } else {
1035 DCHECK_EQ(status, compiled_class->GetStatus());
1036 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001037 }
1038 // clear any class not found or verification exceptions
1039 Thread::Current()->ClearException();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001040 }
1041
1042 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1043 for (size_t type_idx = 0; type_idx < dex_cache->NumResolvedTypes(); type_idx++) {
1044 Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001045 if (klass == NULL) {
1046 Thread::Current()->ClearException();
1047 } else if (klass->IsInitialized()) {
Brian Carlstromffca45d2011-09-16 12:10:49 -07001048 dex_cache->GetInitializedStaticStorage()->Set(type_idx, klass);
1049 }
jeffhao98eacac2011-09-14 16:11:53 -07001050 }
1051}
1052
Brian Carlstromae826982011-11-09 01:33:42 -08001053void Compiler::Compile(const ClassLoader* class_loader,
1054 const std::vector<const DexFile*>& dex_files) {
1055 for (size_t i = 0; i != dex_files.size(); ++i) {
1056 const DexFile* dex_file = dex_files[i];
Brian Carlstrom83db7722011-08-26 17:32:56 -07001057 CHECK(dex_file != NULL);
1058 CompileDexFile(class_loader, *dex_file);
1059 }
1060}
1061
Elliott Hughesc225caa2012-02-03 15:43:37 -08001062void Compiler::CompileClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001063 const ClassLoader* class_loader = context->GetClassLoader();
1064 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesc225caa2012-02-03 15:43:37 -08001065 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Logan Chien7f767612012-03-01 18:54:49 +08001066#if defined(ART_USE_LLVM_COMPILER)
Logan Chien7f767612012-03-01 18:54:49 +08001067 // TODO: Remove this. We should not lock the compiler_lock_ in CompileClass()
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001068 // However, without this mutex lock, we will get segmentation fault before
1069 // LLVM becomes multithreaded.
1070 Compiler* cmplr = context->GetCompiler();
1071 CompilerMutexLockFn f =
1072 FindFunction<CompilerMutexLockFn>(MakeCompilerSoName(cmplr->GetInstructionSet()),
1073 cmplr->compiler_library_,
1074 "compilerLLVMMutexLock");
1075 UniquePtr<MutexLock> GUARD((*f)(*cmplr));
Logan Chien7f767612012-03-01 18:54:49 +08001076#endif
1077
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001078 if (SkipClass(class_loader, dex_file, class_def)) {
1079 return;
1080 }
jeffhaod1224c72012-02-29 13:43:08 -08001081 ClassReference ref(&dex_file, class_def_index);
1082 // Skip compiling classes with generic verifier failures since they will still fail at runtime
1083 if (verifier::DexVerifier::IsClassRejected(ref)) {
1084 return;
1085 }
Ian Rogers0571d352011-11-03 19:51:38 -07001086 const byte* class_data = dex_file.GetClassData(class_def);
1087 if (class_data == NULL) {
1088 // empty class, probably a marker interface
1089 return;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001090 }
Ian Rogers0571d352011-11-03 19:51:38 -07001091 ClassDataItemIterator it(dex_file, class_data);
1092 // Skip fields
1093 while (it.HasNextStaticField()) {
1094 it.Next();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001095 }
Ian Rogers0571d352011-11-03 19:51:38 -07001096 while (it.HasNextInstanceField()) {
1097 it.Next();
1098 }
1099 // Compile direct methods
1100 while (it.HasNextDirectMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001101 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1102 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001103 it.Next();
1104 }
1105 // Compile virtual methods
1106 while (it.HasNextVirtualMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001107 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1108 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001109 it.Next();
1110 }
1111 DCHECK(!it.HasNext());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001112}
1113
Elliott Hughesc225caa2012-02-03 15:43:37 -08001114void Compiler::CompileDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001115 Context context(NULL, class_loader, this, NULL, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001116 ForAll(&context, 0, dex_file.NumClassDefs(), Compiler::CompileClass, thread_count_);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001117}
1118
Ian Rogersa3760aa2011-11-14 14:32:37 -08001119void Compiler::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
1120 uint32_t method_idx, const ClassLoader* class_loader,
1121 const DexFile& dex_file) {
Elliott Hughesf09afe82011-10-16 14:24:21 -07001122 CompiledMethod* compiled_method = NULL;
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001123 uint64_t start_ns = NanoTime();
Logan Chien4dd96f52012-02-29 01:26:58 +08001124
Ian Rogers169c9a72011-11-13 20:13:17 -08001125 if ((access_flags & kAccNative) != 0) {
Elliott Hughes46f060a2012-03-09 17:36:50 -08001126 compiled_method = (*jni_compiler_)(*this, access_flags, method_idx, class_loader, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001127 CHECK(compiled_method != NULL);
Ian Rogers169c9a72011-11-13 20:13:17 -08001128 } else if ((access_flags & kAccAbstract) != 0) {
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001129 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001130 compiled_method = (*compiler_)(*this, code_item, access_flags, method_idx, class_loader,
1131 dex_file);
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001132 CHECK(compiled_method != NULL) << PrettyMethod(method_idx, dex_file);
1133 }
Ian Rogers3bb17a62012-01-27 23:56:44 -08001134 uint64_t duration_ns = NanoTime() - start_ns;
buzbee5abfa3e2012-01-31 17:01:43 -08001135 if (duration_ns > MsToNs(100)) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001136 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
Ian Rogers3bb17a62012-01-27 23:56:44 -08001137 << " took " << PrettyDuration(duration_ns);
Elliott Hughesf09afe82011-10-16 14:24:21 -07001138 }
1139
1140 if (compiled_method != NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07001141 MethodReference ref(&dex_file, method_idx);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001142 CHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001143 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001144 compiled_methods_[ref] = compiled_method;
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001145 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001146 }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -07001147
Ian Rogers45619fc2012-02-29 11:15:25 -08001148 uint32_t shorty_len;
1149 const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx), &shorty_len);
Ian Rogers169c9a72011-11-13 20:13:17 -08001150 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001151 const CompiledInvokeStub* compiled_invoke_stub = FindInvokeStub(is_static, shorty);
1152 if (compiled_invoke_stub == NULL) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001153 compiled_invoke_stub = (*create_invoke_stub_)(*this, is_static, shorty, shorty_len);
Ian Rogers0571d352011-11-03 19:51:38 -07001154 CHECK(compiled_invoke_stub != NULL);
1155 InsertInvokeStub(is_static, shorty, compiled_invoke_stub);
Ian Rogers2c8f6532011-09-02 17:16:34 -07001156 }
Ian Rogers0571d352011-11-03 19:51:38 -07001157 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001158}
1159
Ian Rogers0571d352011-11-03 19:51:38 -07001160static std::string MakeInvokeStubKey(bool is_static, const char* shorty) {
1161 std::string key(shorty);
1162 if (is_static) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001163 key += "$"; // Must not be a shorty type character.
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001164 }
Ian Rogers0571d352011-11-03 19:51:38 -07001165 return key;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001166}
1167
Ian Rogers0571d352011-11-03 19:51:38 -07001168const CompiledInvokeStub* Compiler::FindInvokeStub(bool is_static, const char* shorty) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001169 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001170 const std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001171 InvokeStubTable::const_iterator it = compiled_invoke_stubs_.find(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001172 if (it == compiled_invoke_stubs_.end()) {
1173 return NULL;
Ian Rogers0571d352011-11-03 19:51:38 -07001174 } else {
1175 DCHECK(it->second != NULL);
1176 return it->second;
1177 }
1178}
1179
1180void Compiler::InsertInvokeStub(bool is_static, const char* shorty,
1181 const CompiledInvokeStub* compiled_invoke_stub) {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001182 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001183 std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001184 compiled_invoke_stubs_[key] = compiled_invoke_stub;
1185}
1186
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001187CompiledClass* Compiler::GetCompiledClass(ClassReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001188 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001189 ClassTable::const_iterator it = compiled_classes_.find(ref);
1190 if (it == compiled_classes_.end()) {
1191 return NULL;
1192 }
1193 CHECK(it->second != NULL);
1194 return it->second;
1195}
1196
Ian Rogers0571d352011-11-03 19:51:38 -07001197CompiledMethod* Compiler::GetCompiledMethod(MethodReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001198 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001199 MethodTable::const_iterator it = compiled_methods_.find(ref);
1200 if (it == compiled_methods_.end()) {
1201 return NULL;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001202 }
1203 CHECK(it->second != NULL);
1204 return it->second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001205}
1206
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001207void Compiler::SetGcMaps(const ClassLoader* class_loader, const std::vector<const DexFile*>& dex_files) {
1208 for (size_t i = 0; i != dex_files.size(); ++i) {
1209 const DexFile* dex_file = dex_files[i];
1210 CHECK(dex_file != NULL);
1211 SetGcMapsDexFile(class_loader, *dex_file);
1212 }
1213}
1214
1215void Compiler::SetGcMapsDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
1216 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1217 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1218 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1219 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1220 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1221 Class* klass = class_linker->FindClass(descriptor, class_loader);
1222 if (klass == NULL || !klass->IsVerified()) {
1223 Thread::Current()->ClearException();
1224 continue;
1225 }
1226 const byte* class_data = dex_file.GetClassData(class_def);
1227 if (class_data == NULL) {
1228 // empty class such as a marker interface
1229 continue;
1230 }
1231 ClassDataItemIterator it(dex_file, class_data);
1232 while (it.HasNextStaticField()) {
1233 it.Next();
1234 }
1235 while (it.HasNextInstanceField()) {
1236 it.Next();
1237 }
1238 while (it.HasNextDirectMethod()) {
1239 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1240 class_loader, true);
1241 SetGcMapsMethod(dex_file, method);
1242 it.Next();
1243 }
1244 while (it.HasNextVirtualMethod()) {
1245 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1246 class_loader, false);
1247 SetGcMapsMethod(dex_file, method);
1248 it.Next();
1249 }
1250 }
1251}
1252
1253void Compiler::SetGcMapsMethod(const DexFile& dex_file, Method* method) {
1254 if (method == NULL) {
1255 Thread::Current()->ClearException();
1256 return;
1257 }
1258 uint16_t method_idx = method->GetDexMethodIndex();
1259 MethodReference ref(&dex_file, method_idx);
1260 CompiledMethod* compiled_method = GetCompiledMethod(ref);
1261 if (compiled_method == NULL) {
1262 return;
1263 }
1264 const std::vector<uint8_t>* gc_map = verifier::DexVerifier::GetGcMap(ref);
1265 if (gc_map == NULL) {
1266 return;
1267 }
1268 compiled_method->SetGcMap(*gc_map);
1269}
1270
Logan Chien8b977d32012-02-21 19:14:55 +08001271#if defined(ART_USE_LLVM_COMPILER)
1272void Compiler::SetElfFileName(std::string const& filename) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001273 elf_filename_ = filename;
Logan Chien8b977d32012-02-21 19:14:55 +08001274}
1275
1276void Compiler::SetBitcodeFileName(std::string const& filename) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001277 bitcode_filename_ = filename;
1278}
1279std::string const& Compiler::GetElfFileName() {
1280 return elf_filename_;
1281}
1282std::string const& Compiler::GetBitcodeFileName() {
1283 return bitcode_filename_;
Logan Chien8b977d32012-02-21 19:14:55 +08001284}
1285#endif
1286
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001287} // namespace art