blob: 7d71278c53e3bc1e3aff41d61b47d205e4fbfb20 [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 Rogers2ed3b952012-03-17 11:49:39 -070074 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0) {
75 for (size_t i = 0; i <= kMaxInvokeType; i++) {
Ian Rogersc8b306f2012-02-17 21:34:44 -080076 resolved_methods_[i] = 0;
77 unresolved_methods_[i] = 0;
Ian Rogers2ed3b952012-03-17 11:49:39 -070078 virtual_made_direct_[i] = 0;
79 direct_calls_to_boot_[i] = 0;
80 direct_methods_to_boot_[i] = 0;
81 }
Ian Rogersc8b306f2012-02-17 21:34:44 -080082 }
83
84 void Dump() {
85 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
86 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
87 DumpStat(resolved_types_, unresolved_types_, "types resolved");
88 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
89 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
90 "static fields resolved");
91 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
92 "static fields local to a class");
93
Ian Rogers2ed3b952012-03-17 11:49:39 -070094 for (size_t i = 0; i <= kMaxInvokeType; i++) {
Ian Rogersc8b306f2012-02-17 21:34:44 -080095 std::ostringstream oss;
Ian Rogers2ed3b952012-03-17 11:49:39 -070096 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
Ian Rogersc8b306f2012-02-17 21:34:44 -080097 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
Ian Rogers2ed3b952012-03-17 11:49:39 -070098 if (virtual_made_direct_[i] > 0) {
99 std::ostringstream oss2;
100 oss2 << static_cast<InvokeType>(i) << " methods made direct";
101 DumpStat(virtual_made_direct_[i],
102 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
103 oss2.str().c_str());
104 }
105 if (direct_calls_to_boot_[i] > 0) {
106 std::ostringstream oss2;
107 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
108 DumpStat(direct_calls_to_boot_[i],
109 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
110 oss2.str().c_str());
111 }
112 if (direct_methods_to_boot_[i] > 0) {
113 std::ostringstream oss2;
114 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
115 DumpStat(direct_methods_to_boot_[i],
116 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
117 oss2.str().c_str());
118 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800119 }
120 }
Ian Rogers996cc582012-02-14 22:23:29 -0800121
122// Allow lossy statistics in non-debug builds
123#ifndef NDEBUG
124#define STATS_LOCK() MutexLock mu(stats_lock_)
125#else
126#define STATS_LOCK()
127#endif
128
Ian Rogersc8b306f2012-02-17 21:34:44 -0800129 void TypeInDexCache() {
130 STATS_LOCK();
131 types_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800132 }
Ian Rogers996cc582012-02-14 22:23:29 -0800133
Ian Rogersc8b306f2012-02-17 21:34:44 -0800134 void TypeNotInDexCache() {
135 STATS_LOCK();
136 types_not_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800137 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800138
139 void StringInDexCache() {
140 STATS_LOCK();
141 strings_in_dex_cache_++;
142 }
143
144 void StringNotInDexCache() {
145 STATS_LOCK();
146 strings_not_in_dex_cache_++;
147 }
148
149 void TypeDoesntNeedAccessCheck() {
150 STATS_LOCK();
151 resolved_types_++;
152 }
153
154 void TypeNeedsAccessCheck() {
155 STATS_LOCK();
156 unresolved_types_++;
157 }
158
159 void ResolvedInstanceField() {
160 STATS_LOCK();
161 resolved_instance_fields_++;
162 }
163
164 void UnresolvedInstanceField(){
165 STATS_LOCK();
166 unresolved_instance_fields_++;
167 }
168
169 void ResolvedLocalStaticField() {
170 STATS_LOCK();
171 resolved_local_static_fields_++;
172 }
173
174 void ResolvedStaticField() {
175 STATS_LOCK();
176 resolved_static_fields_++;
177 }
178
179 void UnresolvedStaticField() {
180 STATS_LOCK();
181 unresolved_static_fields_++;
182 }
183
184 void ResolvedMethod(InvokeType type) {
185 DCHECK_LE(type, kMaxInvokeType);
186 STATS_LOCK();
187 resolved_methods_[type]++;
188 }
189
190 void UnresolvedMethod(InvokeType type) {
191 DCHECK_LE(type, kMaxInvokeType);
192 STATS_LOCK();
193 unresolved_methods_[type]++;
194 }
195
Ian Rogers2ed3b952012-03-17 11:49:39 -0700196 void VirtualMadeDirect(InvokeType type) {
197 DCHECK_LE(type, kMaxInvokeType);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800198 STATS_LOCK();
Ian Rogers2ed3b952012-03-17 11:49:39 -0700199 virtual_made_direct_[type]++;
Ian Rogersfb6adba2012-03-04 21:51:51 -0800200 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700201
202 void DirectCallsToBoot(InvokeType type) {
203 DCHECK_LE(type, kMaxInvokeType);
204 STATS_LOCK();
205 direct_calls_to_boot_[type]++;
206 }
207
208 void DirectMethodsToBoot(InvokeType type) {
209 DCHECK_LE(type, kMaxInvokeType);
210 STATS_LOCK();
211 direct_methods_to_boot_[type]++;
212 }
213
Ian Rogersc8b306f2012-02-17 21:34:44 -0800214 private:
215 Mutex stats_lock_;
216
217 size_t types_in_dex_cache_;
218 size_t types_not_in_dex_cache_;
219
220 size_t strings_in_dex_cache_;
221 size_t strings_not_in_dex_cache_;
222
223 size_t resolved_types_;
224 size_t unresolved_types_;
225
226 size_t resolved_instance_fields_;
227 size_t unresolved_instance_fields_;
228
229 size_t resolved_local_static_fields_;
230 size_t resolved_static_fields_;
231 size_t unresolved_static_fields_;
232
233 size_t resolved_methods_[kMaxInvokeType + 1];
234 size_t unresolved_methods_[kMaxInvokeType + 1];
Ian Rogers2ed3b952012-03-17 11:49:39 -0700235 size_t virtual_made_direct_[kMaxInvokeType + 1];
236 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
237 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
Ian Rogersc8b306f2012-02-17 21:34:44 -0800238
239 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);;
240};
Ian Rogers996cc582012-02-14 22:23:29 -0800241
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800242static std::string MakeCompilerSoName(InstructionSet instruction_set) {
243 // TODO: is the ARM/Thumb2 instruction set distinction really buying us anything,
244 // or just causing hassle like this?
245 if (instruction_set == kThumb2) {
246 instruction_set = kArm;
247 }
248
Elliott Hughes059d5c12012-03-12 17:39:18 -0700249 // Capitalize the instruction set, because that's what we do in the build system.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800250 std::ostringstream instruction_set_name_os;
251 instruction_set_name_os << instruction_set;
252 std::string instruction_set_name(instruction_set_name_os.str());
253 for (size_t i = 0; i < instruction_set_name.size(); ++i) {
254 instruction_set_name[i] = toupper(instruction_set_name[i]);
255 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700256
257 // Bad things happen if we pull in the libartd-compiler to a libart dex2oat or vice versa,
258 // because we end up with both libart and libartd in the same address space!
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800259#ifndef NDEBUG
260 const char* suffix = "d";
261#else
262 const char* suffix = "";
263#endif
Elliott Hughes059d5c12012-03-12 17:39:18 -0700264
265 // Work out the filename for the compiler library.
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800266#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes059d5c12012-03-12 17:39:18 -0700267 std::string library_name(StringPrintf("art%s-compiler-%s", suffix, instruction_set_name.c_str()));
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800268#else
269 std::string library_name(StringPrintf("art%s-compiler-llvm", suffix));
270#endif
Elliott Hughes059d5c12012-03-12 17:39:18 -0700271 std::string filename(StringPrintf(OS_SHARED_LIB_FORMAT_STR, library_name.c_str()));
272
273#if defined(__APPLE__)
274 // On Linux, dex2oat will have been built with an RPATH of $ORIGIN/../lib, so dlopen(3) will find
275 // the .so by itself. On Mac OS, there isn't really an equivalent, so we have to manually do the
276 // same work.
277 std::vector<char> executable_path(1);
278 uint32_t executable_path_length = 0;
279 _NSGetExecutablePath(&executable_path[0], &executable_path_length);
280 while (_NSGetExecutablePath(&executable_path[0], &executable_path_length) == -1) {
281 executable_path.resize(executable_path_length);
282 }
283
284 executable_path.resize(executable_path.size() - 1); // Strip trailing NUL.
285 std::string path(&executable_path[0]);
286
287 // Strip the "/dex2oat".
288 size_t last_slash = path.find_last_of('/');
289 CHECK_NE(last_slash, std::string::npos) << path;
290 path.resize(last_slash);
291
292 // Strip the "/bin".
293 last_slash = path.find_last_of('/');
294 path.resize(last_slash);
295
296 filename = path + "/lib/" + filename;
297#endif
298 return filename;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800299}
300
Elliott Hughes46f060a2012-03-09 17:36:50 -0800301template<typename Fn>
302static Fn FindFunction(const std::string& compiler_so_name, void* library, const char* name) {
303 Fn fn = reinterpret_cast<Fn>(dlsym(library, name));
304 if (fn == NULL) {
305 LOG(FATAL) << "Couldn't find \"" << name << "\" in compiler library " << compiler_so_name << ": " << dlerror();
306 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700307 VLOG(compiler) << "Found \"" << name << "\" at " << reinterpret_cast<void*>(fn);
Elliott Hughes46f060a2012-03-09 17:36:50 -0800308 return fn;
309}
310
Elliott Hughes5523ee02012-02-03 18:18:34 -0800311Compiler::Compiler(InstructionSet instruction_set, bool image, size_t thread_count,
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800312 bool support_debugging, const std::set<std::string>* image_classes)
Brian Carlstromaded5f72011-10-07 17:15:04 -0700313 : instruction_set_(instruction_set),
Elliott Hughesc225caa2012-02-03 15:43:37 -0800314 compiled_classes_lock_("compiled classes lock"),
315 compiled_methods_lock_("compiled method lock"),
316 compiled_invoke_stubs_lock_("compiled invoke stubs lock"),
Brian Carlstromaded5f72011-10-07 17:15:04 -0700317 image_(image),
Elliott Hughes5523ee02012-02-03 18:18:34 -0800318 thread_count_(thread_count),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800319 support_debugging_(support_debugging),
Ian Rogersc8b306f2012-02-17 21:34:44 -0800320 stats_(new AOTCompilationStats),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800321 image_classes_(image_classes),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800322 compiler_library_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800323 compiler_(NULL),
Elliott Hughes6f4976c2012-03-13 21:19:01 -0700324 compiler_context_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800325 jni_compiler_(NULL),
326 create_invoke_stub_(NULL)
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800327{
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800328 std::string compiler_so_name(MakeCompilerSoName(instruction_set_));
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800329 compiler_library_ = dlopen(compiler_so_name.c_str(), RTLD_LAZY);
330 if (compiler_library_ == NULL) {
331 LOG(FATAL) << "Couldn't find compiler library " << compiler_so_name << ": " << dlerror();
332 }
333 VLOG(compiler) << "dlopen(\"" << compiler_so_name << "\", RTLD_LAZY) returned " << compiler_library_;
334
Elliott Hughes3fa1b7e2012-03-13 17:06:22 -0700335 compiler_ = FindFunction<CompilerFn>(compiler_so_name, compiler_library_, "ArtCompileMethod");
Elliott Hughes46f060a2012-03-09 17:36:50 -0800336 jni_compiler_ = FindFunction<JniCompilerFn>(compiler_so_name, compiler_library_, "ArtJniCompileMethod");
337 create_invoke_stub_ = FindFunction<CreateInvokeStubFn>(compiler_so_name, compiler_library_, "ArtCreateInvokeStub");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800338
Brian Carlstrom25c33252011-09-18 15:58:35 -0700339 CHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800340 if (!image_) {
341 CHECK(image_classes_ == NULL);
342 }
Shih-wei Liaoc486c112011-09-13 16:43:52 -0700343}
344
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700345Compiler::~Compiler() {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800346 {
347 MutexLock mu(compiled_classes_lock_);
348 STLDeleteValues(&compiled_classes_);
349 }
350 {
351 MutexLock mu(compiled_methods_lock_);
352 STLDeleteValues(&compiled_methods_);
353 }
354 {
355 MutexLock mu(compiled_invoke_stubs_lock_);
356 STLDeleteValues(&compiled_invoke_stubs_);
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800357 }
Brian Carlstromf5822582012-03-19 22:34:31 -0700358 {
359 MutexLock mu(compiled_methods_lock_);
360 STLDeleteElements(&code_to_patch_);
361 }
362 {
363 MutexLock mu(compiled_methods_lock_);
364 STLDeleteElements(&methods_to_patch_);
365 }
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800366#if defined(ART_USE_LLVM_COMPILER)
367 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
368 compiler_library_,
369 "compilerLLVMDispose");
370 (*f)(*this);
371#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800372 if (compiler_library_ != NULL) {
373 VLOG(compiler) << "dlclose(" << compiler_library_ << ")";
374 dlclose(compiler_library_);
375 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700376}
377
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700378ByteArray* Compiler::CreateResolutionStub(InstructionSet instruction_set,
379 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700380 if (instruction_set == kX86) {
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700381 return x86::X86CreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700382 } else {
383 CHECK(instruction_set == kArm || instruction_set == kThumb2);
384 // Generates resolution stub using ARM instruction set
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700385 return arm::ArmCreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700386 }
387}
388
Elliott Hughes8add92d2012-01-18 18:18:43 -0800389ByteArray* Compiler::CreateJniDlsymLookupStub(InstructionSet instruction_set) {
Ian Rogers169c9a72011-11-13 20:13:17 -0800390 switch (instruction_set) {
391 case kArm:
392 case kThumb2:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800393 return arm::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800394 case kX86:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800395 return x86::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800396 default:
Ian Rogers49c48942012-03-11 15:15:37 -0700397 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
Ian Rogers169c9a72011-11-13 20:13:17 -0800398 return NULL;
399 }
400}
401
Ian Rogersad25ac52011-10-04 19:13:33 -0700402ByteArray* Compiler::CreateAbstractMethodErrorStub(InstructionSet instruction_set) {
403 if (instruction_set == kX86) {
404 return x86::CreateAbstractMethodErrorStub();
405 } else {
406 CHECK(instruction_set == kArm || instruction_set == kThumb2);
407 // Generates resolution stub using ARM instruction set
408 return arm::CreateAbstractMethodErrorStub();
409 }
410}
411
Jesse Wilson254db0f2011-11-16 16:44:11 -0500412void Compiler::CompileAll(const ClassLoader* class_loader,
Brian Carlstromae826982011-11-09 01:33:42 -0800413 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700414 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800415
Elliott Hughes601a1232012-02-02 17:47:38 -0800416 TimingLogger timings("compiler");
417
418 PreCompile(class_loader, dex_files, timings);
419
Brian Carlstromae826982011-11-09 01:33:42 -0800420 Compile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800421 timings.AddSplit("Compile");
422
Brian Carlstromae826982011-11-09 01:33:42 -0800423 PostCompile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800424 timings.AddSplit("PostCompile");
425
426 if (timings.GetTotalNs() > MsToNs(1000)) {
427 timings.Dump();
428 }
Ian Rogers996cc582012-02-14 22:23:29 -0800429
Ian Rogersc8b306f2012-02-17 21:34:44 -0800430 stats_->Dump();
Brian Carlstrom8a487412011-08-29 20:08:52 -0700431}
432
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700433void Compiler::CompileOne(const Method* method) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700434 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800435
Brian Carlstrom8a487412011-08-29 20:08:52 -0700436 const ClassLoader* class_loader = method->GetDeclaringClass()->GetClassLoader();
Brian Carlstromae826982011-11-09 01:33:42 -0800437
Ian Rogers0571d352011-11-03 19:51:38 -0700438 // Find the dex_file
439 const DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
440 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
Brian Carlstromae826982011-11-09 01:33:42 -0800441 std::vector<const DexFile*> dex_files;
442 dex_files.push_back(&dex_file);
443
Elliott Hughes601a1232012-02-02 17:47:38 -0800444 TimingLogger timings("CompileOne");
445 PreCompile(class_loader, dex_files, timings);
Brian Carlstromae826982011-11-09 01:33:42 -0800446
Ian Rogers0571d352011-11-03 19:51:38 -0700447 uint32_t method_idx = method->GetDexMethodIndex();
Ian Rogersa3760aa2011-11-14 14:32:37 -0800448 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
449 CompileMethod(code_item, method->GetAccessFlags(), method_idx, class_loader, dex_file);
Brian Carlstromae826982011-11-09 01:33:42 -0800450
451 PostCompile(class_loader, dex_files);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700452}
453
Brian Carlstromae826982011-11-09 01:33:42 -0800454void Compiler::Resolve(const ClassLoader* class_loader,
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800455 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -0800456 for (size_t i = 0; i != dex_files.size(); ++i) {
457 const DexFile* dex_file = dex_files[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700458 CHECK(dex_file != NULL);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800459 ResolveDexFile(class_loader, *dex_file, timings);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700460 }
461}
462
Brian Carlstromae826982011-11-09 01:33:42 -0800463void Compiler::PreCompile(const ClassLoader* class_loader,
Elliott Hughes601a1232012-02-02 17:47:38 -0800464 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800465 Resolve(class_loader, dex_files, timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800466
Brian Carlstromae826982011-11-09 01:33:42 -0800467 Verify(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800468 timings.AddSplit("PreCompile.Verify");
469
Brian Carlstromae826982011-11-09 01:33:42 -0800470 InitializeClassesWithoutClinit(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800471 timings.AddSplit("PreCompile.InitializeClassesWithoutClinit");
Brian Carlstromae826982011-11-09 01:33:42 -0800472}
473
474void Compiler::PostCompile(const ClassLoader* class_loader,
475 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800476 SetGcMaps(class_loader, dex_files);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800477#if defined(ART_USE_LLVM_COMPILER)
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800478 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
479 compiler_library_,
480 "compilerLLVMMaterializeRemainder");
481 (*f)(*this);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800482#endif
Brian Carlstromae826982011-11-09 01:33:42 -0800483}
484
485bool Compiler::IsImageClass(const std::string& descriptor) const {
486 if (image_classes_ == NULL) {
487 return true;
488 }
489 return image_classes_->find(descriptor) != image_classes_->end();
490}
491
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800492bool Compiler::CanAssumeTypeIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800493 uint32_t type_idx) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800494 if (!IsImage()) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800495 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800496 return false;
497 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800498 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800499 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800500 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800501 return false;
502 }
Ian Rogers996cc582012-02-14 22:23:29 -0800503 bool result = IsImageClass(ClassHelper(resolved_class).GetDescriptor());
504 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800505 stats_->TypeInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800506 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800507 stats_->TypeNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800508 }
509 return result;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800510}
511
Ian Rogers1bddec32012-02-04 12:27:34 -0800512bool Compiler::CanAssumeStringIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800513 uint32_t string_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800514 // TODO: Add support for loading strings referenced by image_classes_
515 // See also Compiler::ResolveDexFile
516
517 // The following is a test saying that if we're building the image without a restricted set of
518 // 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 -0800519 bool result = IsImage() && image_classes_ == NULL && dex_cache->GetResolvedString(string_idx) != NULL;
520 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800521 stats_->StringInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800522 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800523 stats_->StringNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800524 }
525 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800526}
527
528bool Compiler::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800529 const DexFile& dex_file, uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800530 // Get type from dex cache assuming it was populated by the verifier
531 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
532 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800533 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800534 return false; // Unknown class needs access checks.
535 }
536 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
537 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
538 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800539 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800540 return false; // Incomplete referrer knowledge needs access check.
541 }
542 // Perform access check, will return true if access is ok or false if we're going to have to
543 // check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800544 bool result = referrer_class->CanAccess(resolved_class);
545 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800546 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800547 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800548 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800549 }
550 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800551}
552
553bool Compiler::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
554 const DexCache* dex_cache,
555 const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800556 uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800557 // Get type from dex cache assuming it was populated by the verifier.
558 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
559 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800560 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800561 return false; // Unknown class needs access checks.
562 }
563 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
564 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
565 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800566 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800567 return false; // Incomplete referrer knowledge needs access check.
568 }
569 // Perform access and instantiable checks, will return true if access is ok or false if we're
570 // going to have to check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800571 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
572 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800573 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800574 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800575 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800576 }
577 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800578}
579
Logan Chien4dd96f52012-02-29 01:26:58 +0800580static Class* ComputeReferrerClass(OatCompilationUnit* mUnit) {
581 const DexFile::MethodId& referrer_method_id =
582 mUnit->dex_file_->GetMethodId(mUnit->method_idx_);
583
584 return mUnit->class_linker_->ResolveType(
585 *mUnit->dex_file_, referrer_method_id.class_idx_,
586 mUnit->dex_cache_, mUnit->class_loader_);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800587}
588
Logan Chien4dd96f52012-02-29 01:26:58 +0800589static Field* ComputeReferrerField(OatCompilationUnit* mUnit, uint32_t field_idx) {
590 return mUnit->class_linker_->ResolveField(
591 *mUnit->dex_file_, field_idx, mUnit->dex_cache_,
592 mUnit->class_loader_, false);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800593}
594
Logan Chien4dd96f52012-02-29 01:26:58 +0800595static Method* ComputeReferrerMethod(OatCompilationUnit* mUnit, uint32_t method_idx) {
596 return mUnit->class_linker_->ResolveMethod(
597 *mUnit->dex_file_, method_idx, mUnit->dex_cache_,
598 mUnit->class_loader_, true);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800599}
600
Logan Chien4dd96f52012-02-29 01:26:58 +0800601bool Compiler::ComputeInstanceFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
jeffhao8cd6dda2012-02-22 10:15:34 -0800602 int& field_offset, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800603 // Conservative defaults
604 field_offset = -1;
605 is_volatile = true;
606 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800607 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800608 if (resolved_field != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800609 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800610 // Try to resolve referring class then access check, failure to pass the
611 Class* fields_class = resolved_field->GetDeclaringClass();
jeffhao8cd6dda2012-02-22 10:15:34 -0800612 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal() &&
613 fields_class != referrer_class;
614 if (referrer_class != NULL && referrer_class->CanAccess(fields_class) &&
615 referrer_class->CanAccessMember(fields_class, resolved_field->GetAccessFlags()) &&
616 !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800617 field_offset = resolved_field->GetOffset().Int32Value();
618 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800619 stats_->ResolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800620 return true; // Fast path.
621 }
622 }
623 // Clean up any exception left by field/type resolution
624 Thread* thread = Thread::Current();
625 if (thread->IsExceptionPending()) {
626 thread->ClearException();
627 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800628 stats_->UnresolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800629 return false; // Incomplete knowledge needs slow path.
630}
631
Logan Chien4dd96f52012-02-29 01:26:58 +0800632bool Compiler::ComputeStaticFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
Ian Rogers1bddec32012-02-04 12:27:34 -0800633 int& field_offset, int& ssb_index,
jeffhao8cd6dda2012-02-22 10:15:34 -0800634 bool& is_referrers_class, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800635 // Conservative defaults
636 field_offset = -1;
637 ssb_index = -1;
638 is_referrers_class = false;
639 is_volatile = true;
640 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800641 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800642 if (resolved_field != NULL) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800643 DCHECK(resolved_field->IsStatic());
Logan Chien4dd96f52012-02-29 01:26:58 +0800644 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800645 if (referrer_class != NULL) {
jeffhao8cd6dda2012-02-22 10:15:34 -0800646 Class* fields_class = resolved_field->GetDeclaringClass();
647 if (fields_class == referrer_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800648 is_referrers_class = true; // implies no worrying about class initialization
649 field_offset = resolved_field->GetOffset().Int32Value();
650 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800651 stats_->ResolvedLocalStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800652 return true; // fast path
653 } else {
jeffhao8cd6dda2012-02-22 10:15:34 -0800654 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal();
Ian Rogers1bddec32012-02-04 12:27:34 -0800655 if (referrer_class->CanAccess(fields_class) &&
jeffhao8cd6dda2012-02-22 10:15:34 -0800656 referrer_class->CanAccessMember(fields_class, resolved_field->GetAccessFlags()) &&
657 !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800658 // We have the resolved field, we must make it into a ssbIndex for the referrer
659 // in its static storage base (which may fail if it doesn't have a slot for it)
Ian Rogers4103ad22012-02-06 09:18:25 -0800660 // TODO: for images we can elide the static storage base null check
661 // if we know there's a non-null entry in the image
Logan Chien4dd96f52012-02-29 01:26:58 +0800662 if (fields_class->GetDexCache() == mUnit->dex_cache_) {
Ian Rogers4103ad22012-02-06 09:18:25 -0800663 // common case where the dex cache of both the referrer and the field are the same,
664 // no need to search the dex file
665 ssb_index = fields_class->GetDexTypeIndex();
666 field_offset = resolved_field->GetOffset().Int32Value();
667 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800668 stats_->ResolvedStaticField();
Ian Rogers4103ad22012-02-06 09:18:25 -0800669 return true;
670 }
671 // Search dex file for localized ssb index
Ian Rogers1bddec32012-02-04 12:27:34 -0800672 std::string descriptor(FieldHelper(resolved_field).GetDeclaringClassDescriptor());
673 const DexFile::StringId* string_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800674 mUnit->dex_file_->FindStringId(descriptor);
Ian Rogers1bddec32012-02-04 12:27:34 -0800675 if (string_id != NULL) {
676 const DexFile::TypeId* type_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800677 mUnit->dex_file_->FindTypeId(mUnit->dex_file_->GetIndexForStringId(*string_id));
Ian Rogers1bddec32012-02-04 12:27:34 -0800678 if(type_id != NULL) {
679 // medium path, needs check of static storage base being initialized
Logan Chien4dd96f52012-02-29 01:26:58 +0800680 ssb_index = mUnit->dex_file_->GetIndexForTypeId(*type_id);
Ian Rogers1bddec32012-02-04 12:27:34 -0800681 field_offset = resolved_field->GetOffset().Int32Value();
682 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800683 stats_->ResolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800684 return true;
685 }
686 }
687 }
688 }
689 }
690 }
691 // Clean up any exception left by field/type resolution
692 Thread* thread = Thread::Current();
693 if (thread->IsExceptionPending()) {
694 thread->ClearException();
695 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800696 stats_->UnresolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800697 return false; // Incomplete knowledge needs slow path.
698}
699
Ian Rogers2ed3b952012-03-17 11:49:39 -0700700void Compiler::GetCodeAndMethodForDirectCall(InvokeType type, InvokeType sharp_type, Method* method,
701 uintptr_t& direct_code, uintptr_t& direct_method) {
702 direct_code = 0;
703 direct_method = 0;
704 if (sharp_type != kStatic && sharp_type != kDirect) {
705 return;
706 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700707 bool method_code_in_boot = method->GetDeclaringClass()->GetClassLoader() == NULL;
708 if (!method_code_in_boot) {
709 return;
710 }
711 bool has_clinit_trampoline = method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
712 if (has_clinit_trampoline) {
713 return;
714 }
715 stats_->DirectCallsToBoot(type);
716 stats_->DirectMethodsToBoot(type);
Ian Rogers3fa13792012-03-18 15:53:45 -0700717 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
718 if (compiling_boot) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700719 const bool kSupportBootImageFixup = true;
Ian Rogers3fa13792012-03-18 15:53:45 -0700720 if (kSupportBootImageFixup) {
721 MethodHelper mh(method);
722 if (IsImageClass(mh.GetDeclaringClassDescriptor())) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700723 // We can only branch directly to Methods that are resolved in the DexCache.
724 // Otherwise we won't invoke the resolution trampoline.
Ian Rogers3fa13792012-03-18 15:53:45 -0700725 direct_method = -1;
Brian Carlstrom0637e272012-03-20 01:07:52 -0700726 direct_code = -1;
Ian Rogers3fa13792012-03-18 15:53:45 -0700727 }
Ian Rogers3fa13792012-03-18 15:53:45 -0700728 }
729 } else {
730 if (Runtime::Current()->GetHeap()->GetImageSpace()->Contains(method)) {
731 direct_method = reinterpret_cast<uintptr_t>(method);
732 }
733 direct_code = reinterpret_cast<uintptr_t>(method->GetCode());
Ian Rogers2ed3b952012-03-17 11:49:39 -0700734 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700735}
736
Ian Rogersfb6adba2012-03-04 21:51:51 -0800737bool Compiler::ComputeInvokeInfo(uint32_t method_idx, OatCompilationUnit* mUnit, InvokeType& type,
Ian Rogers2ed3b952012-03-17 11:49:39 -0700738 int& vtable_idx, uintptr_t& direct_code,
739 uintptr_t& direct_method) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800740 vtable_idx = -1;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700741 direct_code = 0;
742 direct_method = 0;
Logan Chien4dd96f52012-02-29 01:26:58 +0800743 Method* resolved_method = ComputeReferrerMethod(mUnit, method_idx);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800744 if (resolved_method != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800745 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800746 if (referrer_class != NULL) {
747 Class* methods_class = resolved_method->GetDeclaringClass();
748 if (!referrer_class->CanAccess(methods_class) ||
749 !referrer_class->CanAccessMember(methods_class,
Ian Rogers996cc582012-02-14 22:23:29 -0800750 resolved_method->GetAccessFlags())) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800751 // The referring class can't access the resolved method, this may occur as a result of a
752 // protected method being made public by implementing an interface that re-declares the
753 // method public. Resort to the dex file to determine the correct class for the access check
Logan Chien4dd96f52012-02-29 01:26:58 +0800754 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800755 methods_class =
Logan Chien4dd96f52012-02-29 01:26:58 +0800756 mUnit->class_linker_->ResolveType(dex_file,
757 dex_file.GetMethodId(method_idx).class_idx_,
758 referrer_class);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800759
760 }
761 if (referrer_class->CanAccess(methods_class) &&
762 referrer_class->CanAccessMember(methods_class,
763 resolved_method->GetAccessFlags())) {
764 vtable_idx = resolved_method->GetMethodIndex();
Ian Rogersf320b632012-03-13 18:47:47 -0700765 const bool kEnableSharpening = true;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700766 // Sharpen a virtual call into a direct call when the target is known.
767 bool can_sharpen = type == kVirtual && (resolved_method->IsFinal() ||
768 methods_class->IsFinal());
769 // ensure the vtable index will be correct to dispatch in the vtable of the super class
jeffhao4155fcd2012-03-21 11:42:12 -0700770 can_sharpen = can_sharpen || (type == kSuper && referrer_class != methods_class &&
Ian Rogers2ed3b952012-03-17 11:49:39 -0700771 referrer_class->IsSubClass(methods_class) &&
jeffhao4155fcd2012-03-21 11:42:12 -0700772 vtable_idx < methods_class->GetVTable()->GetLength() &&
773 methods_class->GetVTable()->Get(vtable_idx) == resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700774 if (kEnableSharpening && can_sharpen) {
775 stats_->ResolvedMethod(type);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800776 // Sharpen a virtual call into a direct call. The method_idx is into referrer's
777 // dex cache, check that this resolved method is where we expect it.
778 CHECK(referrer_class->GetDexCache()->GetResolvedMethod(method_idx) == resolved_method)
779 << PrettyMethod(resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700780 stats_->VirtualMadeDirect(type);
781 GetCodeAndMethodForDirectCall(type, kDirect, resolved_method, direct_code, direct_method);
782 type = kDirect;
783 return true;
784 } else if (type == kSuper) {
785 // Unsharpened super calls are suspicious so go slowpath.
786 } else {
787 stats_->ResolvedMethod(type);
788 GetCodeAndMethodForDirectCall(type, type, resolved_method, direct_code, direct_method);
789 return true;
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800790 }
791 }
792 }
793 }
794 // Clean up any exception left by method/type resolution
795 Thread* thread = Thread::Current();
796 if (thread->IsExceptionPending()) {
797 thread->ClearException();
798 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800799 stats_->UnresolvedMethod(type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800800 return false; // Incomplete knowledge needs slow path.
801}
802
Brian Carlstromf5822582012-03-19 22:34:31 -0700803void Compiler::AddCodePatch(DexCache* dex_cache,
804 const DexFile* dex_file,
805 uint32_t referrer_method_idx,
806 uint32_t referrer_access_flags,
807 uint32_t target_method_idx,
808 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700809 size_t literal_offset) {
810 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700811 code_to_patch_.push_back(new PatchInformation(dex_cache,
812 dex_file,
813 referrer_method_idx,
814 referrer_access_flags,
815 target_method_idx,
816 target_is_direct,
817 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700818}
Brian Carlstromf5822582012-03-19 22:34:31 -0700819void Compiler::AddMethodPatch(DexCache* dex_cache,
820 const DexFile* dex_file,
821 uint32_t referrer_method_idx,
822 uint32_t referrer_access_flags,
823 uint32_t target_method_idx,
824 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700825 size_t literal_offset) {
826 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700827 methods_to_patch_.push_back(new PatchInformation(dex_cache,
828 dex_file,
829 referrer_method_idx,
830 referrer_access_flags,
831 target_method_idx,
832 target_is_direct,
833 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700834}
835
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800836// Return true if the class should be skipped during compilation. We
837// never skip classes in the boot class loader. However, if we have a
838// non-boot class loader and we can resolve the class in the boot
839// class loader, we do skip the class. This happens if an app bundles
840// classes found in the boot classpath. Since at runtime we will
841// select the class from the boot classpath, do not attempt to resolve
842// or compile it now.
843static bool SkipClass(const ClassLoader* class_loader,
844 const DexFile& dex_file,
845 const DexFile::ClassDef& class_def) {
846 if (class_loader == NULL) {
847 return false;
848 }
849 const char* descriptor = dex_file.GetClassDescriptor(class_def);
850 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
851 Class* klass = class_linker->FindClass(descriptor, NULL);
852 if (klass == NULL) {
853 Thread* self = Thread::Current();
854 CHECK(self->IsExceptionPending());
855 self->ClearException();
856 return false;
857 }
858 return true;
859}
860
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800861class Context {
862 public:
863 Context(ClassLinker* class_linker,
864 const ClassLoader* class_loader,
865 Compiler* compiler,
866 DexCache* dex_cache,
867 const DexFile* dex_file)
868 : class_linker_(class_linker),
869 class_loader_(class_loader),
870 compiler_(compiler),
871 dex_cache_(dex_cache),
872 dex_file_(dex_file) {}
873
874 ClassLinker* GetClassLinker() {
875 CHECK(class_linker_ != NULL);
876 return class_linker_;
877 }
878 const ClassLoader* GetClassLoader() {
879 return class_loader_;
880 }
881 Compiler* GetCompiler() {
882 CHECK(compiler_ != NULL);
883 return compiler_;
884 }
885 DexCache* GetDexCache() {
886 CHECK(dex_cache_ != NULL);
887 return dex_cache_;
888 }
889 const DexFile* GetDexFile() {
890 CHECK(dex_file_ != NULL);
891 return dex_file_;
892 }
893
894 private:
895 ClassLinker* class_linker_;
896 const ClassLoader* class_loader_;
897 Compiler* compiler_;
898 DexCache* dex_cache_;
899 const DexFile* dex_file_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800900};
901
902typedef void Callback(Context* context, size_t index);
903
904class WorkerThread {
905 public:
Elliott Hughes1e409252012-02-06 11:21:27 -0800906 WorkerThread(Context* context, size_t begin, size_t end, Callback callback, size_t stripe, bool spawn)
907 : spawn_(spawn), context_(context), begin_(begin), end_(end), callback_(callback), stripe_(stripe) {
908 if (spawn_) {
909 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, NULL, &Go, this), "compiler worker thread");
910 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800911 }
912
913 ~WorkerThread() {
Elliott Hughes1e409252012-02-06 11:21:27 -0800914 if (spawn_) {
915 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
916 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800917 }
918
919 private:
Elliott Hughes1e409252012-02-06 11:21:27 -0800920 static void* Go(void* arg) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800921 WorkerThread* worker = reinterpret_cast<WorkerThread*>(arg);
922 Runtime* runtime = Runtime::Current();
Elliott Hughes1e409252012-02-06 11:21:27 -0800923 if (worker->spawn_) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700924 runtime->AttachCurrentThread("Compiler Worker", true, NULL);
Elliott Hughes1e409252012-02-06 11:21:27 -0800925 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800926 Thread::Current()->SetState(Thread::kRunnable);
927 worker->Run();
Elliott Hughes1e409252012-02-06 11:21:27 -0800928 if (worker->spawn_) {
929 Thread::Current()->SetState(Thread::kNative);
930 runtime->DetachCurrentThread();
931 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800932 return NULL;
933 }
934
Elliott Hughes1e409252012-02-06 11:21:27 -0800935 void Go() {
936 Go(this);
937 }
938
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800939 void Run() {
940 for (size_t i = begin_; i < end_; i += stripe_) {
941 callback_(context_, i);
942 }
943 }
944
945 pthread_t pthread_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800946 bool spawn_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800947
948 Context* context_;
949 size_t begin_;
950 size_t end_;
951 Callback* callback_;
952 size_t stripe_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800953
954 friend void ForAll(Context*, size_t, size_t, Callback, size_t);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800955};
956
Elliott Hughes5523ee02012-02-03 18:18:34 -0800957void ForAll(Context* context, size_t begin, size_t end, Callback callback, size_t thread_count) {
Elliott Hughes1e409252012-02-06 11:21:27 -0800958 CHECK_GT(thread_count, 0U);
Elliott Hughes81d91512012-02-03 16:38:43 -0800959
Elliott Hughes1e409252012-02-06 11:21:27 -0800960 std::vector<WorkerThread*> threads;
Elliott Hughes81d91512012-02-03 16:38:43 -0800961 for (size_t i = 0; i < thread_count; ++i) {
Elliott Hughes1e409252012-02-06 11:21:27 -0800962 threads.push_back(new WorkerThread(context, begin + i, end, callback, thread_count, (i != 0)));
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800963 }
Elliott Hughes1e409252012-02-06 11:21:27 -0800964 threads[0]->Go();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800965
Elliott Hughes81d91512012-02-03 16:38:43 -0800966 // Switch to kVmWait while we're blocked waiting for the other threads to finish.
967 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
968 STLDeleteElements(&threads);
969}
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800970
971static void ResolveClassFieldsAndMethods(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800972 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800973
974 // Method and Field are the worst. We can't resolve without either
975 // context from the code use (to disambiguate virtual vs direct
976 // method and instance vs static field) or from class
977 // definitions. While the compiler will resolve what it can as it
978 // needs it, here we try to resolve fields and methods used in class
979 // definitions, since many of them many never be referenced by
980 // generated code.
981 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800982 if (SkipClass(context->GetClassLoader(), dex_file, class_def)) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800983 return;
984 }
985
986 // Note the class_data pointer advances through the headers,
987 // static fields, instance fields, direct methods, and virtual
988 // methods.
989 const byte* class_data = dex_file.GetClassData(class_def);
990 if (class_data == NULL) {
991 // empty class such as a marker interface
992 return;
993 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800994 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800995 ClassLinker* class_linker = context->GetClassLinker();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800996 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
997 ClassDataItemIterator it(dex_file, class_data);
998 while (it.HasNextStaticField()) {
999 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001000 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001001 if (field == NULL) {
1002 CHECK(self->IsExceptionPending());
1003 self->ClearException();
1004 }
1005 it.Next();
1006 }
1007 while (it.HasNextInstanceField()) {
1008 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001009 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001010 if (field == NULL) {
1011 CHECK(self->IsExceptionPending());
1012 self->ClearException();
1013 }
1014 it.Next();
1015 }
1016 while (it.HasNextDirectMethod()) {
1017 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001018 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001019 if (method == NULL) {
1020 CHECK(self->IsExceptionPending());
1021 self->ClearException();
1022 }
1023 it.Next();
1024 }
1025 while (it.HasNextVirtualMethod()) {
1026 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001027 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001028 if (method == NULL) {
1029 CHECK(self->IsExceptionPending());
1030 self->ClearException();
1031 }
1032 it.Next();
1033 }
1034 DCHECK(!it.HasNext());
1035}
1036
1037static void ResolveType(Context* context, size_t type_idx) {
1038 // Class derived values are more complicated, they require the linker and loader.
1039 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001040 Class* klass = context->GetClassLinker()->ResolveType(*context->GetDexFile(),
1041 type_idx,
1042 context->GetDexCache(),
1043 context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001044 if (klass == NULL) {
1045 CHECK(self->IsExceptionPending());
1046 Thread::Current()->ClearException();
1047 }
1048}
1049
1050void Compiler::ResolveDexFile(const ClassLoader* class_loader, const DexFile& dex_file, TimingLogger& timings) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001051 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001052 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001053
Brian Carlstromae826982011-11-09 01:33:42 -08001054 // Strings are easy in that they always are simply resolved to literals in the same file
1055 if (image_ && image_classes_ == NULL) {
1056 // TODO: Add support for loading strings referenced by image_classes_
1057 // See also Compiler::CanAssumeTypeIsPresentInDexCache.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001058 for (size_t string_idx = 0; string_idx < dex_cache->NumStrings(); string_idx++) {
1059 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1060 }
Elliott Hughesff738062012-02-03 15:00:42 -08001061 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Strings");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001062 }
1063
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001064 Context context(class_linker, class_loader, this, dex_cache, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001065 ForAll(&context, 0, dex_cache->NumResolvedTypes(), ResolveType, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001066 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Types");
Brian Carlstrom845490b2011-09-19 15:56:53 -07001067
Elliott Hughes5523ee02012-02-03 18:18:34 -08001068 ForAll(&context, 0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001069 timings.AddSplit("Resolve " + dex_file.GetLocation() + " MethodsAndFields");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001070}
1071
Brian Carlstromae826982011-11-09 01:33:42 -08001072void Compiler::Verify(const ClassLoader* class_loader,
1073 const std::vector<const DexFile*>& dex_files) {
1074 for (size_t i = 0; i != dex_files.size(); ++i) {
1075 const DexFile* dex_file = dex_files[i];
jeffhao98eacac2011-09-14 16:11:53 -07001076 CHECK(dex_file != NULL);
1077 VerifyDexFile(class_loader, *dex_file);
1078 }
1079}
1080
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001081static void VerifyClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001082 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
1083 const char* descriptor = context->GetDexFile()->GetClassDescriptor(class_def);
1084 Class* klass = context->GetClassLinker()->FindClass(descriptor, context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001085 if (klass == NULL) {
1086 Thread* self = Thread::Current();
1087 CHECK(self->IsExceptionPending());
1088 self->ClearException();
jeffhaof56197c2012-03-05 18:01:54 -08001089
1090 /*
1091 * At compile time, we can still structurally verify the class even if FindClass fails.
1092 * This is to ensure the class is structurally sound for compilation. An unsound class
1093 * will be rejected by the verifier and later skipped during compilation in the compiler.
1094 */
1095 std::string error_msg;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001096 if (!verifier::DexVerifier::VerifyClass(context->GetDexFile(), context->GetDexCache(),
1097 context->GetClassLoader(), class_def_index, error_msg)) {
1098 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
jeffhaof56197c2012-03-05 18:01:54 -08001099 LOG(ERROR) << "Verification failed on class "
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001100 << PrettyDescriptor(context->GetDexFile()->GetClassDescriptor(class_def))
jeffhaof56197c2012-03-05 18:01:54 -08001101 << " because: " << error_msg;
1102 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001103 return;
1104 }
1105 CHECK(klass->IsResolved()) << PrettyClass(klass);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001106 context->GetClassLinker()->VerifyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001107
1108 if (klass->IsErroneous()) {
1109 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1110 CHECK(Thread::Current()->IsExceptionPending());
1111 Thread::Current()->ClearException();
jeffhao1ac29442012-03-26 11:37:32 -07001112 art::Compiler::ClassReference ref(context->GetDexFile(), class_def_index);
1113 if (!verifier::DexVerifier::IsClassRejected(ref)) {
1114 // If the erroneous class wasn't rejected by the verifier, it was a soft error. We want
1115 // to try verification again at run-time, so move back into the resolved state.
1116 klass->SetStatus(Class::kStatusResolved);
1117 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001118 }
1119
jeffhao1ac29442012-03-26 11:37:32 -07001120 CHECK(klass->IsVerified() || klass->IsResolved() || klass->IsErroneous()) << PrettyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001121 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1122}
1123
jeffhao98eacac2011-09-14 16:11:53 -07001124void Compiler::VerifyDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
jeffhaob4df5142011-09-19 20:25:32 -07001125 dex_file.ChangePermissions(PROT_READ | PROT_WRITE);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001126
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001127 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1128 Context context(class_linker, class_loader, this, class_linker->FindDexCache(dex_file), &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001129 ForAll(&context, 0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001130
jeffhaob4df5142011-09-19 20:25:32 -07001131 dex_file.ChangePermissions(PROT_READ);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001132}
1133
Brian Carlstromae826982011-11-09 01:33:42 -08001134void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader,
1135 const std::vector<const DexFile*>& dex_files) {
1136 for (size_t i = 0; i != dex_files.size(); ++i) {
1137 const DexFile* dex_file = dex_files[i];
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001138 CHECK(dex_file != NULL);
1139 InitializeClassesWithoutClinit(class_loader, *dex_file);
1140 }
1141}
1142
1143void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader, const DexFile& dex_file) {
1144 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001145 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1146 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001147 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1148 Class* klass = class_linker->FindClass(descriptor, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001149 if (klass != NULL) {
jeffhao1ac29442012-03-26 11:37:32 -07001150 if (klass->IsVerified()) {
1151 // Only try to initialize classes that were successfully verified.
1152 class_linker->EnsureInitialized(klass, false);
1153 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001154 // record the final class status if necessary
1155 Class::Status status = klass->GetStatus();
1156 ClassReference ref(&dex_file, class_def_index);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001157 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001158 CompiledClass* compiled_class = GetCompiledClass(ref);
1159 if (compiled_class == NULL) {
1160 compiled_class = new CompiledClass(status);
1161 compiled_classes_[ref] = compiled_class;
1162 } else {
1163 DCHECK_EQ(status, compiled_class->GetStatus());
1164 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001165 }
1166 // clear any class not found or verification exceptions
1167 Thread::Current()->ClearException();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001168 }
1169
1170 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1171 for (size_t type_idx = 0; type_idx < dex_cache->NumResolvedTypes(); type_idx++) {
1172 Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001173 if (klass == NULL) {
1174 Thread::Current()->ClearException();
1175 } else if (klass->IsInitialized()) {
Brian Carlstromffca45d2011-09-16 12:10:49 -07001176 dex_cache->GetInitializedStaticStorage()->Set(type_idx, klass);
1177 }
jeffhao98eacac2011-09-14 16:11:53 -07001178 }
1179}
1180
Brian Carlstromae826982011-11-09 01:33:42 -08001181void Compiler::Compile(const ClassLoader* class_loader,
1182 const std::vector<const DexFile*>& dex_files) {
1183 for (size_t i = 0; i != dex_files.size(); ++i) {
1184 const DexFile* dex_file = dex_files[i];
Brian Carlstrom83db7722011-08-26 17:32:56 -07001185 CHECK(dex_file != NULL);
1186 CompileDexFile(class_loader, *dex_file);
1187 }
1188}
1189
Elliott Hughesc225caa2012-02-03 15:43:37 -08001190void Compiler::CompileClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001191 const ClassLoader* class_loader = context->GetClassLoader();
1192 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesc225caa2012-02-03 15:43:37 -08001193 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Logan Chien7f767612012-03-01 18:54:49 +08001194#if defined(ART_USE_LLVM_COMPILER)
Logan Chien7f767612012-03-01 18:54:49 +08001195 // TODO: Remove this. We should not lock the compiler_lock_ in CompileClass()
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001196 // However, without this mutex lock, we will get segmentation fault before
1197 // LLVM becomes multithreaded.
1198 Compiler* cmplr = context->GetCompiler();
1199 CompilerMutexLockFn f =
1200 FindFunction<CompilerMutexLockFn>(MakeCompilerSoName(cmplr->GetInstructionSet()),
1201 cmplr->compiler_library_,
1202 "compilerLLVMMutexLock");
1203 UniquePtr<MutexLock> GUARD((*f)(*cmplr));
Logan Chien7f767612012-03-01 18:54:49 +08001204#endif
1205
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001206 if (SkipClass(class_loader, dex_file, class_def)) {
1207 return;
1208 }
jeffhaod1224c72012-02-29 13:43:08 -08001209 ClassReference ref(&dex_file, class_def_index);
1210 // Skip compiling classes with generic verifier failures since they will still fail at runtime
1211 if (verifier::DexVerifier::IsClassRejected(ref)) {
1212 return;
1213 }
Ian Rogers0571d352011-11-03 19:51:38 -07001214 const byte* class_data = dex_file.GetClassData(class_def);
1215 if (class_data == NULL) {
1216 // empty class, probably a marker interface
1217 return;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001218 }
Ian Rogers0571d352011-11-03 19:51:38 -07001219 ClassDataItemIterator it(dex_file, class_data);
1220 // Skip fields
1221 while (it.HasNextStaticField()) {
1222 it.Next();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001223 }
Ian Rogers0571d352011-11-03 19:51:38 -07001224 while (it.HasNextInstanceField()) {
1225 it.Next();
1226 }
1227 // Compile direct methods
1228 while (it.HasNextDirectMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001229 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1230 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001231 it.Next();
1232 }
1233 // Compile virtual methods
1234 while (it.HasNextVirtualMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001235 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1236 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001237 it.Next();
1238 }
1239 DCHECK(!it.HasNext());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001240}
1241
Elliott Hughesc225caa2012-02-03 15:43:37 -08001242void Compiler::CompileDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001243 Context context(NULL, class_loader, this, NULL, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001244 ForAll(&context, 0, dex_file.NumClassDefs(), Compiler::CompileClass, thread_count_);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001245}
1246
Ian Rogersa3760aa2011-11-14 14:32:37 -08001247void Compiler::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
1248 uint32_t method_idx, const ClassLoader* class_loader,
1249 const DexFile& dex_file) {
Elliott Hughesf09afe82011-10-16 14:24:21 -07001250 CompiledMethod* compiled_method = NULL;
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001251 uint64_t start_ns = NanoTime();
Logan Chien4dd96f52012-02-29 01:26:58 +08001252
Ian Rogers169c9a72011-11-13 20:13:17 -08001253 if ((access_flags & kAccNative) != 0) {
Elliott Hughes46f060a2012-03-09 17:36:50 -08001254 compiled_method = (*jni_compiler_)(*this, access_flags, method_idx, class_loader, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001255 CHECK(compiled_method != NULL);
Ian Rogers169c9a72011-11-13 20:13:17 -08001256 } else if ((access_flags & kAccAbstract) != 0) {
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001257 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001258 compiled_method = (*compiler_)(*this, code_item, access_flags, method_idx, class_loader,
1259 dex_file);
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001260 CHECK(compiled_method != NULL) << PrettyMethod(method_idx, dex_file);
1261 }
Ian Rogers3bb17a62012-01-27 23:56:44 -08001262 uint64_t duration_ns = NanoTime() - start_ns;
buzbee5abfa3e2012-01-31 17:01:43 -08001263 if (duration_ns > MsToNs(100)) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001264 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
Ian Rogers3bb17a62012-01-27 23:56:44 -08001265 << " took " << PrettyDuration(duration_ns);
Elliott Hughesf09afe82011-10-16 14:24:21 -07001266 }
1267
1268 if (compiled_method != NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07001269 MethodReference ref(&dex_file, method_idx);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001270 CHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001271 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001272 compiled_methods_[ref] = compiled_method;
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001273 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001274 }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -07001275
Ian Rogers45619fc2012-02-29 11:15:25 -08001276 uint32_t shorty_len;
1277 const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx), &shorty_len);
Ian Rogers169c9a72011-11-13 20:13:17 -08001278 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001279 const CompiledInvokeStub* compiled_invoke_stub = FindInvokeStub(is_static, shorty);
1280 if (compiled_invoke_stub == NULL) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001281 compiled_invoke_stub = (*create_invoke_stub_)(*this, is_static, shorty, shorty_len);
Ian Rogers0571d352011-11-03 19:51:38 -07001282 CHECK(compiled_invoke_stub != NULL);
1283 InsertInvokeStub(is_static, shorty, compiled_invoke_stub);
Ian Rogers2c8f6532011-09-02 17:16:34 -07001284 }
Ian Rogers0571d352011-11-03 19:51:38 -07001285 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001286}
1287
Ian Rogers0571d352011-11-03 19:51:38 -07001288static std::string MakeInvokeStubKey(bool is_static, const char* shorty) {
1289 std::string key(shorty);
1290 if (is_static) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001291 key += "$"; // Must not be a shorty type character.
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001292 }
Ian Rogers0571d352011-11-03 19:51:38 -07001293 return key;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001294}
1295
Ian Rogers0571d352011-11-03 19:51:38 -07001296const CompiledInvokeStub* Compiler::FindInvokeStub(bool is_static, const char* shorty) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001297 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001298 const std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001299 InvokeStubTable::const_iterator it = compiled_invoke_stubs_.find(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001300 if (it == compiled_invoke_stubs_.end()) {
1301 return NULL;
Ian Rogers0571d352011-11-03 19:51:38 -07001302 } else {
1303 DCHECK(it->second != NULL);
1304 return it->second;
1305 }
1306}
1307
1308void Compiler::InsertInvokeStub(bool is_static, const char* shorty,
1309 const CompiledInvokeStub* compiled_invoke_stub) {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001310 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001311 std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001312 compiled_invoke_stubs_[key] = compiled_invoke_stub;
1313}
1314
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001315CompiledClass* Compiler::GetCompiledClass(ClassReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001316 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001317 ClassTable::const_iterator it = compiled_classes_.find(ref);
1318 if (it == compiled_classes_.end()) {
1319 return NULL;
1320 }
1321 CHECK(it->second != NULL);
1322 return it->second;
1323}
1324
Ian Rogers0571d352011-11-03 19:51:38 -07001325CompiledMethod* Compiler::GetCompiledMethod(MethodReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001326 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001327 MethodTable::const_iterator it = compiled_methods_.find(ref);
1328 if (it == compiled_methods_.end()) {
1329 return NULL;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001330 }
1331 CHECK(it->second != NULL);
1332 return it->second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001333}
1334
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001335void Compiler::SetGcMaps(const ClassLoader* class_loader, const std::vector<const DexFile*>& dex_files) {
1336 for (size_t i = 0; i != dex_files.size(); ++i) {
1337 const DexFile* dex_file = dex_files[i];
1338 CHECK(dex_file != NULL);
1339 SetGcMapsDexFile(class_loader, *dex_file);
1340 }
1341}
1342
1343void Compiler::SetGcMapsDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
1344 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1345 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1346 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1347 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1348 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1349 Class* klass = class_linker->FindClass(descriptor, class_loader);
1350 if (klass == NULL || !klass->IsVerified()) {
1351 Thread::Current()->ClearException();
1352 continue;
1353 }
1354 const byte* class_data = dex_file.GetClassData(class_def);
1355 if (class_data == NULL) {
1356 // empty class such as a marker interface
1357 continue;
1358 }
1359 ClassDataItemIterator it(dex_file, class_data);
1360 while (it.HasNextStaticField()) {
1361 it.Next();
1362 }
1363 while (it.HasNextInstanceField()) {
1364 it.Next();
1365 }
1366 while (it.HasNextDirectMethod()) {
1367 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1368 class_loader, true);
1369 SetGcMapsMethod(dex_file, method);
1370 it.Next();
1371 }
1372 while (it.HasNextVirtualMethod()) {
1373 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1374 class_loader, false);
1375 SetGcMapsMethod(dex_file, method);
1376 it.Next();
1377 }
1378 }
1379}
1380
1381void Compiler::SetGcMapsMethod(const DexFile& dex_file, Method* method) {
1382 if (method == NULL) {
1383 Thread::Current()->ClearException();
1384 return;
1385 }
1386 uint16_t method_idx = method->GetDexMethodIndex();
1387 MethodReference ref(&dex_file, method_idx);
1388 CompiledMethod* compiled_method = GetCompiledMethod(ref);
1389 if (compiled_method == NULL) {
1390 return;
1391 }
1392 const std::vector<uint8_t>* gc_map = verifier::DexVerifier::GetGcMap(ref);
1393 if (gc_map == NULL) {
1394 return;
1395 }
1396 compiled_method->SetGcMap(*gc_map);
1397}
1398
Logan Chien8b977d32012-02-21 19:14:55 +08001399#if defined(ART_USE_LLVM_COMPILER)
1400void Compiler::SetElfFileName(std::string const& filename) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001401 elf_filename_ = filename;
Logan Chien8b977d32012-02-21 19:14:55 +08001402}
1403
1404void Compiler::SetBitcodeFileName(std::string const& filename) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001405 bitcode_filename_ = filename;
1406}
1407std::string const& Compiler::GetElfFileName() {
1408 return elf_filename_;
1409}
1410std::string const& Compiler::GetBitcodeFileName() {
1411 return bitcode_filename_;
Logan Chien8b977d32012-02-21 19:14:55 +08001412}
1413#endif
1414
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001415} // namespace art