blob: ce34f0fefa18bd107b59ff8c6f8f1c9077ea93d3 [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
770 can_sharpen = can_sharpen || (type == kSuper &&
771 referrer_class->IsSubClass(methods_class) &&
772 vtable_idx < methods_class->GetVTable()->GetLength());
773 if (kEnableSharpening && can_sharpen) {
774 stats_->ResolvedMethod(type);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800775 // Sharpen a virtual call into a direct call. The method_idx is into referrer's
776 // dex cache, check that this resolved method is where we expect it.
777 CHECK(referrer_class->GetDexCache()->GetResolvedMethod(method_idx) == resolved_method)
778 << PrettyMethod(resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700779 if (type == kSuper) {
780 CHECK(methods_class->GetVTable()->Get(vtable_idx) == resolved_method)
781 << PrettyMethod(resolved_method);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800782 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700783 stats_->VirtualMadeDirect(type);
784 GetCodeAndMethodForDirectCall(type, kDirect, resolved_method, direct_code, direct_method);
785 type = kDirect;
786 return true;
787 } else if (type == kSuper) {
788 // Unsharpened super calls are suspicious so go slowpath.
789 } else {
790 stats_->ResolvedMethod(type);
791 GetCodeAndMethodForDirectCall(type, type, resolved_method, direct_code, direct_method);
792 return true;
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800793 }
794 }
795 }
796 }
797 // Clean up any exception left by method/type resolution
798 Thread* thread = Thread::Current();
799 if (thread->IsExceptionPending()) {
800 thread->ClearException();
801 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800802 stats_->UnresolvedMethod(type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800803 return false; // Incomplete knowledge needs slow path.
804}
805
Brian Carlstromf5822582012-03-19 22:34:31 -0700806void Compiler::AddCodePatch(DexCache* dex_cache,
807 const DexFile* dex_file,
808 uint32_t referrer_method_idx,
809 uint32_t referrer_access_flags,
810 uint32_t target_method_idx,
811 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700812 size_t literal_offset) {
813 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700814 code_to_patch_.push_back(new PatchInformation(dex_cache,
815 dex_file,
816 referrer_method_idx,
817 referrer_access_flags,
818 target_method_idx,
819 target_is_direct,
820 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700821}
Brian Carlstromf5822582012-03-19 22:34:31 -0700822void Compiler::AddMethodPatch(DexCache* dex_cache,
823 const DexFile* dex_file,
824 uint32_t referrer_method_idx,
825 uint32_t referrer_access_flags,
826 uint32_t target_method_idx,
827 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700828 size_t literal_offset) {
829 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700830 methods_to_patch_.push_back(new PatchInformation(dex_cache,
831 dex_file,
832 referrer_method_idx,
833 referrer_access_flags,
834 target_method_idx,
835 target_is_direct,
836 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700837}
838
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800839// Return true if the class should be skipped during compilation. We
840// never skip classes in the boot class loader. However, if we have a
841// non-boot class loader and we can resolve the class in the boot
842// class loader, we do skip the class. This happens if an app bundles
843// classes found in the boot classpath. Since at runtime we will
844// select the class from the boot classpath, do not attempt to resolve
845// or compile it now.
846static bool SkipClass(const ClassLoader* class_loader,
847 const DexFile& dex_file,
848 const DexFile::ClassDef& class_def) {
849 if (class_loader == NULL) {
850 return false;
851 }
852 const char* descriptor = dex_file.GetClassDescriptor(class_def);
853 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
854 Class* klass = class_linker->FindClass(descriptor, NULL);
855 if (klass == NULL) {
856 Thread* self = Thread::Current();
857 CHECK(self->IsExceptionPending());
858 self->ClearException();
859 return false;
860 }
861 return true;
862}
863
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800864class Context {
865 public:
866 Context(ClassLinker* class_linker,
867 const ClassLoader* class_loader,
868 Compiler* compiler,
869 DexCache* dex_cache,
870 const DexFile* dex_file)
871 : class_linker_(class_linker),
872 class_loader_(class_loader),
873 compiler_(compiler),
874 dex_cache_(dex_cache),
875 dex_file_(dex_file) {}
876
877 ClassLinker* GetClassLinker() {
878 CHECK(class_linker_ != NULL);
879 return class_linker_;
880 }
881 const ClassLoader* GetClassLoader() {
882 return class_loader_;
883 }
884 Compiler* GetCompiler() {
885 CHECK(compiler_ != NULL);
886 return compiler_;
887 }
888 DexCache* GetDexCache() {
889 CHECK(dex_cache_ != NULL);
890 return dex_cache_;
891 }
892 const DexFile* GetDexFile() {
893 CHECK(dex_file_ != NULL);
894 return dex_file_;
895 }
896
897 private:
898 ClassLinker* class_linker_;
899 const ClassLoader* class_loader_;
900 Compiler* compiler_;
901 DexCache* dex_cache_;
902 const DexFile* dex_file_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800903};
904
905typedef void Callback(Context* context, size_t index);
906
907class WorkerThread {
908 public:
Elliott Hughes1e409252012-02-06 11:21:27 -0800909 WorkerThread(Context* context, size_t begin, size_t end, Callback callback, size_t stripe, bool spawn)
910 : spawn_(spawn), context_(context), begin_(begin), end_(end), callback_(callback), stripe_(stripe) {
911 if (spawn_) {
912 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, NULL, &Go, this), "compiler worker thread");
913 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800914 }
915
916 ~WorkerThread() {
Elliott Hughes1e409252012-02-06 11:21:27 -0800917 if (spawn_) {
918 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
919 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800920 }
921
922 private:
Elliott Hughes1e409252012-02-06 11:21:27 -0800923 static void* Go(void* arg) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800924 WorkerThread* worker = reinterpret_cast<WorkerThread*>(arg);
925 Runtime* runtime = Runtime::Current();
Elliott Hughes1e409252012-02-06 11:21:27 -0800926 if (worker->spawn_) {
927 runtime->AttachCurrentThread("Compiler Worker", true);
928 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800929 Thread::Current()->SetState(Thread::kRunnable);
930 worker->Run();
Elliott Hughes1e409252012-02-06 11:21:27 -0800931 if (worker->spawn_) {
932 Thread::Current()->SetState(Thread::kNative);
933 runtime->DetachCurrentThread();
934 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800935 return NULL;
936 }
937
Elliott Hughes1e409252012-02-06 11:21:27 -0800938 void Go() {
939 Go(this);
940 }
941
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800942 void Run() {
943 for (size_t i = begin_; i < end_; i += stripe_) {
944 callback_(context_, i);
945 }
946 }
947
948 pthread_t pthread_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800949 bool spawn_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800950
951 Context* context_;
952 size_t begin_;
953 size_t end_;
954 Callback* callback_;
955 size_t stripe_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800956
957 friend void ForAll(Context*, size_t, size_t, Callback, size_t);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800958};
959
Elliott Hughes5523ee02012-02-03 18:18:34 -0800960void ForAll(Context* context, size_t begin, size_t end, Callback callback, size_t thread_count) {
Elliott Hughes1e409252012-02-06 11:21:27 -0800961 CHECK_GT(thread_count, 0U);
Elliott Hughes81d91512012-02-03 16:38:43 -0800962
Elliott Hughes1e409252012-02-06 11:21:27 -0800963 std::vector<WorkerThread*> threads;
Elliott Hughes81d91512012-02-03 16:38:43 -0800964 for (size_t i = 0; i < thread_count; ++i) {
Elliott Hughes1e409252012-02-06 11:21:27 -0800965 threads.push_back(new WorkerThread(context, begin + i, end, callback, thread_count, (i != 0)));
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800966 }
Elliott Hughes1e409252012-02-06 11:21:27 -0800967 threads[0]->Go();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800968
Elliott Hughes81d91512012-02-03 16:38:43 -0800969 // Switch to kVmWait while we're blocked waiting for the other threads to finish.
970 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
971 STLDeleteElements(&threads);
972}
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800973
974static void ResolveClassFieldsAndMethods(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800975 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800976
977 // Method and Field are the worst. We can't resolve without either
978 // context from the code use (to disambiguate virtual vs direct
979 // method and instance vs static field) or from class
980 // definitions. While the compiler will resolve what it can as it
981 // needs it, here we try to resolve fields and methods used in class
982 // definitions, since many of them many never be referenced by
983 // generated code.
984 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800985 if (SkipClass(context->GetClassLoader(), dex_file, class_def)) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800986 return;
987 }
988
989 // Note the class_data pointer advances through the headers,
990 // static fields, instance fields, direct methods, and virtual
991 // methods.
992 const byte* class_data = dex_file.GetClassData(class_def);
993 if (class_data == NULL) {
994 // empty class such as a marker interface
995 return;
996 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800997 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800998 ClassLinker* class_linker = context->GetClassLinker();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800999 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1000 ClassDataItemIterator it(dex_file, class_data);
1001 while (it.HasNextStaticField()) {
1002 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001003 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001004 if (field == NULL) {
1005 CHECK(self->IsExceptionPending());
1006 self->ClearException();
1007 }
1008 it.Next();
1009 }
1010 while (it.HasNextInstanceField()) {
1011 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001012 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001013 if (field == NULL) {
1014 CHECK(self->IsExceptionPending());
1015 self->ClearException();
1016 }
1017 it.Next();
1018 }
1019 while (it.HasNextDirectMethod()) {
1020 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001021 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001022 if (method == NULL) {
1023 CHECK(self->IsExceptionPending());
1024 self->ClearException();
1025 }
1026 it.Next();
1027 }
1028 while (it.HasNextVirtualMethod()) {
1029 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001030 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001031 if (method == NULL) {
1032 CHECK(self->IsExceptionPending());
1033 self->ClearException();
1034 }
1035 it.Next();
1036 }
1037 DCHECK(!it.HasNext());
1038}
1039
1040static void ResolveType(Context* context, size_t type_idx) {
1041 // Class derived values are more complicated, they require the linker and loader.
1042 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001043 Class* klass = context->GetClassLinker()->ResolveType(*context->GetDexFile(),
1044 type_idx,
1045 context->GetDexCache(),
1046 context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001047 if (klass == NULL) {
1048 CHECK(self->IsExceptionPending());
1049 Thread::Current()->ClearException();
1050 }
1051}
1052
1053void Compiler::ResolveDexFile(const ClassLoader* class_loader, const DexFile& dex_file, TimingLogger& timings) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001054 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001055 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001056
Brian Carlstromae826982011-11-09 01:33:42 -08001057 // Strings are easy in that they always are simply resolved to literals in the same file
1058 if (image_ && image_classes_ == NULL) {
1059 // TODO: Add support for loading strings referenced by image_classes_
1060 // See also Compiler::CanAssumeTypeIsPresentInDexCache.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001061 for (size_t string_idx = 0; string_idx < dex_cache->NumStrings(); string_idx++) {
1062 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1063 }
Elliott Hughesff738062012-02-03 15:00:42 -08001064 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Strings");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001065 }
1066
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001067 Context context(class_linker, class_loader, this, dex_cache, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001068 ForAll(&context, 0, dex_cache->NumResolvedTypes(), ResolveType, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001069 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Types");
Brian Carlstrom845490b2011-09-19 15:56:53 -07001070
Elliott Hughes5523ee02012-02-03 18:18:34 -08001071 ForAll(&context, 0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001072 timings.AddSplit("Resolve " + dex_file.GetLocation() + " MethodsAndFields");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001073}
1074
Brian Carlstromae826982011-11-09 01:33:42 -08001075void Compiler::Verify(const ClassLoader* class_loader,
1076 const std::vector<const DexFile*>& dex_files) {
1077 for (size_t i = 0; i != dex_files.size(); ++i) {
1078 const DexFile* dex_file = dex_files[i];
jeffhao98eacac2011-09-14 16:11:53 -07001079 CHECK(dex_file != NULL);
1080 VerifyDexFile(class_loader, *dex_file);
1081 }
1082}
1083
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001084static void VerifyClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001085 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
1086 const char* descriptor = context->GetDexFile()->GetClassDescriptor(class_def);
1087 Class* klass = context->GetClassLinker()->FindClass(descriptor, context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001088 if (klass == NULL) {
1089 Thread* self = Thread::Current();
1090 CHECK(self->IsExceptionPending());
1091 self->ClearException();
jeffhaof56197c2012-03-05 18:01:54 -08001092
1093 /*
1094 * At compile time, we can still structurally verify the class even if FindClass fails.
1095 * This is to ensure the class is structurally sound for compilation. An unsound class
1096 * will be rejected by the verifier and later skipped during compilation in the compiler.
1097 */
1098 std::string error_msg;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001099 if (!verifier::DexVerifier::VerifyClass(context->GetDexFile(), context->GetDexCache(),
1100 context->GetClassLoader(), class_def_index, error_msg)) {
1101 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
jeffhaof56197c2012-03-05 18:01:54 -08001102 LOG(ERROR) << "Verification failed on class "
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001103 << PrettyDescriptor(context->GetDexFile()->GetClassDescriptor(class_def))
jeffhaof56197c2012-03-05 18:01:54 -08001104 << " because: " << error_msg;
1105 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001106 return;
1107 }
1108 CHECK(klass->IsResolved()) << PrettyClass(klass);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001109 context->GetClassLinker()->VerifyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001110
1111 if (klass->IsErroneous()) {
1112 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1113 CHECK(Thread::Current()->IsExceptionPending());
1114 Thread::Current()->ClearException();
1115 // We want to try verification again at run-time, so move back into the resolved state.
1116 klass->SetStatus(Class::kStatusResolved);
1117 }
1118
1119 CHECK(klass->IsVerified() || klass->IsResolved()) << PrettyClass(klass);
1120 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1121}
1122
jeffhao98eacac2011-09-14 16:11:53 -07001123void Compiler::VerifyDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
jeffhaob4df5142011-09-19 20:25:32 -07001124 dex_file.ChangePermissions(PROT_READ | PROT_WRITE);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001125
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001126 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1127 Context context(class_linker, class_loader, this, class_linker->FindDexCache(dex_file), &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001128 ForAll(&context, 0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001129
jeffhaob4df5142011-09-19 20:25:32 -07001130 dex_file.ChangePermissions(PROT_READ);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001131}
1132
Brian Carlstromae826982011-11-09 01:33:42 -08001133void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader,
1134 const std::vector<const DexFile*>& dex_files) {
1135 for (size_t i = 0; i != dex_files.size(); ++i) {
1136 const DexFile* dex_file = dex_files[i];
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001137 CHECK(dex_file != NULL);
1138 InitializeClassesWithoutClinit(class_loader, *dex_file);
1139 }
1140}
1141
1142void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader, const DexFile& dex_file) {
1143 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001144 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1145 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001146 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1147 Class* klass = class_linker->FindClass(descriptor, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001148 if (klass != NULL) {
1149 class_linker->EnsureInitialized(klass, false);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001150 // record the final class status if necessary
1151 Class::Status status = klass->GetStatus();
1152 ClassReference ref(&dex_file, class_def_index);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001153 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001154 CompiledClass* compiled_class = GetCompiledClass(ref);
1155 if (compiled_class == NULL) {
1156 compiled_class = new CompiledClass(status);
1157 compiled_classes_[ref] = compiled_class;
1158 } else {
1159 DCHECK_EQ(status, compiled_class->GetStatus());
1160 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001161 }
1162 // clear any class not found or verification exceptions
1163 Thread::Current()->ClearException();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001164 }
1165
1166 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1167 for (size_t type_idx = 0; type_idx < dex_cache->NumResolvedTypes(); type_idx++) {
1168 Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001169 if (klass == NULL) {
1170 Thread::Current()->ClearException();
1171 } else if (klass->IsInitialized()) {
Brian Carlstromffca45d2011-09-16 12:10:49 -07001172 dex_cache->GetInitializedStaticStorage()->Set(type_idx, klass);
1173 }
jeffhao98eacac2011-09-14 16:11:53 -07001174 }
1175}
1176
Brian Carlstromae826982011-11-09 01:33:42 -08001177void Compiler::Compile(const ClassLoader* class_loader,
1178 const std::vector<const DexFile*>& dex_files) {
1179 for (size_t i = 0; i != dex_files.size(); ++i) {
1180 const DexFile* dex_file = dex_files[i];
Brian Carlstrom83db7722011-08-26 17:32:56 -07001181 CHECK(dex_file != NULL);
1182 CompileDexFile(class_loader, *dex_file);
1183 }
1184}
1185
Elliott Hughesc225caa2012-02-03 15:43:37 -08001186void Compiler::CompileClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001187 const ClassLoader* class_loader = context->GetClassLoader();
1188 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesc225caa2012-02-03 15:43:37 -08001189 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Logan Chien7f767612012-03-01 18:54:49 +08001190#if defined(ART_USE_LLVM_COMPILER)
Logan Chien7f767612012-03-01 18:54:49 +08001191 // TODO: Remove this. We should not lock the compiler_lock_ in CompileClass()
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001192 // However, without this mutex lock, we will get segmentation fault before
1193 // LLVM becomes multithreaded.
1194 Compiler* cmplr = context->GetCompiler();
1195 CompilerMutexLockFn f =
1196 FindFunction<CompilerMutexLockFn>(MakeCompilerSoName(cmplr->GetInstructionSet()),
1197 cmplr->compiler_library_,
1198 "compilerLLVMMutexLock");
1199 UniquePtr<MutexLock> GUARD((*f)(*cmplr));
Logan Chien7f767612012-03-01 18:54:49 +08001200#endif
1201
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001202 if (SkipClass(class_loader, dex_file, class_def)) {
1203 return;
1204 }
jeffhaod1224c72012-02-29 13:43:08 -08001205 ClassReference ref(&dex_file, class_def_index);
1206 // Skip compiling classes with generic verifier failures since they will still fail at runtime
1207 if (verifier::DexVerifier::IsClassRejected(ref)) {
1208 return;
1209 }
Ian Rogers0571d352011-11-03 19:51:38 -07001210 const byte* class_data = dex_file.GetClassData(class_def);
1211 if (class_data == NULL) {
1212 // empty class, probably a marker interface
1213 return;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001214 }
Ian Rogers0571d352011-11-03 19:51:38 -07001215 ClassDataItemIterator it(dex_file, class_data);
1216 // Skip fields
1217 while (it.HasNextStaticField()) {
1218 it.Next();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001219 }
Ian Rogers0571d352011-11-03 19:51:38 -07001220 while (it.HasNextInstanceField()) {
1221 it.Next();
1222 }
1223 // Compile direct methods
1224 while (it.HasNextDirectMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001225 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1226 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001227 it.Next();
1228 }
1229 // Compile virtual methods
1230 while (it.HasNextVirtualMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001231 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1232 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001233 it.Next();
1234 }
1235 DCHECK(!it.HasNext());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001236}
1237
Elliott Hughesc225caa2012-02-03 15:43:37 -08001238void Compiler::CompileDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001239 Context context(NULL, class_loader, this, NULL, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001240 ForAll(&context, 0, dex_file.NumClassDefs(), Compiler::CompileClass, thread_count_);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001241}
1242
Ian Rogersa3760aa2011-11-14 14:32:37 -08001243void Compiler::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
1244 uint32_t method_idx, const ClassLoader* class_loader,
1245 const DexFile& dex_file) {
Elliott Hughesf09afe82011-10-16 14:24:21 -07001246 CompiledMethod* compiled_method = NULL;
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001247 uint64_t start_ns = NanoTime();
Logan Chien4dd96f52012-02-29 01:26:58 +08001248
Ian Rogers169c9a72011-11-13 20:13:17 -08001249 if ((access_flags & kAccNative) != 0) {
Elliott Hughes46f060a2012-03-09 17:36:50 -08001250 compiled_method = (*jni_compiler_)(*this, access_flags, method_idx, class_loader, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001251 CHECK(compiled_method != NULL);
Ian Rogers169c9a72011-11-13 20:13:17 -08001252 } else if ((access_flags & kAccAbstract) != 0) {
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001253 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001254 compiled_method = (*compiler_)(*this, code_item, access_flags, method_idx, class_loader,
1255 dex_file);
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001256 CHECK(compiled_method != NULL) << PrettyMethod(method_idx, dex_file);
1257 }
Ian Rogers3bb17a62012-01-27 23:56:44 -08001258 uint64_t duration_ns = NanoTime() - start_ns;
buzbee5abfa3e2012-01-31 17:01:43 -08001259 if (duration_ns > MsToNs(100)) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001260 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
Ian Rogers3bb17a62012-01-27 23:56:44 -08001261 << " took " << PrettyDuration(duration_ns);
Elliott Hughesf09afe82011-10-16 14:24:21 -07001262 }
1263
1264 if (compiled_method != NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07001265 MethodReference ref(&dex_file, method_idx);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001266 CHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001267 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001268 compiled_methods_[ref] = compiled_method;
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001269 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001270 }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -07001271
Ian Rogers45619fc2012-02-29 11:15:25 -08001272 uint32_t shorty_len;
1273 const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx), &shorty_len);
Ian Rogers169c9a72011-11-13 20:13:17 -08001274 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001275 const CompiledInvokeStub* compiled_invoke_stub = FindInvokeStub(is_static, shorty);
1276 if (compiled_invoke_stub == NULL) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001277 compiled_invoke_stub = (*create_invoke_stub_)(*this, is_static, shorty, shorty_len);
Ian Rogers0571d352011-11-03 19:51:38 -07001278 CHECK(compiled_invoke_stub != NULL);
1279 InsertInvokeStub(is_static, shorty, compiled_invoke_stub);
Ian Rogers2c8f6532011-09-02 17:16:34 -07001280 }
Ian Rogers0571d352011-11-03 19:51:38 -07001281 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001282}
1283
Ian Rogers0571d352011-11-03 19:51:38 -07001284static std::string MakeInvokeStubKey(bool is_static, const char* shorty) {
1285 std::string key(shorty);
1286 if (is_static) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001287 key += "$"; // Must not be a shorty type character.
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001288 }
Ian Rogers0571d352011-11-03 19:51:38 -07001289 return key;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001290}
1291
Ian Rogers0571d352011-11-03 19:51:38 -07001292const CompiledInvokeStub* Compiler::FindInvokeStub(bool is_static, const char* shorty) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001293 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001294 const std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001295 InvokeStubTable::const_iterator it = compiled_invoke_stubs_.find(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001296 if (it == compiled_invoke_stubs_.end()) {
1297 return NULL;
Ian Rogers0571d352011-11-03 19:51:38 -07001298 } else {
1299 DCHECK(it->second != NULL);
1300 return it->second;
1301 }
1302}
1303
1304void Compiler::InsertInvokeStub(bool is_static, const char* shorty,
1305 const CompiledInvokeStub* compiled_invoke_stub) {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001306 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001307 std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001308 compiled_invoke_stubs_[key] = compiled_invoke_stub;
1309}
1310
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001311CompiledClass* Compiler::GetCompiledClass(ClassReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001312 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001313 ClassTable::const_iterator it = compiled_classes_.find(ref);
1314 if (it == compiled_classes_.end()) {
1315 return NULL;
1316 }
1317 CHECK(it->second != NULL);
1318 return it->second;
1319}
1320
Ian Rogers0571d352011-11-03 19:51:38 -07001321CompiledMethod* Compiler::GetCompiledMethod(MethodReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001322 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001323 MethodTable::const_iterator it = compiled_methods_.find(ref);
1324 if (it == compiled_methods_.end()) {
1325 return NULL;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001326 }
1327 CHECK(it->second != NULL);
1328 return it->second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001329}
1330
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001331void Compiler::SetGcMaps(const ClassLoader* class_loader, const std::vector<const DexFile*>& dex_files) {
1332 for (size_t i = 0; i != dex_files.size(); ++i) {
1333 const DexFile* dex_file = dex_files[i];
1334 CHECK(dex_file != NULL);
1335 SetGcMapsDexFile(class_loader, *dex_file);
1336 }
1337}
1338
1339void Compiler::SetGcMapsDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
1340 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1341 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1342 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1343 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1344 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1345 Class* klass = class_linker->FindClass(descriptor, class_loader);
1346 if (klass == NULL || !klass->IsVerified()) {
1347 Thread::Current()->ClearException();
1348 continue;
1349 }
1350 const byte* class_data = dex_file.GetClassData(class_def);
1351 if (class_data == NULL) {
1352 // empty class such as a marker interface
1353 continue;
1354 }
1355 ClassDataItemIterator it(dex_file, class_data);
1356 while (it.HasNextStaticField()) {
1357 it.Next();
1358 }
1359 while (it.HasNextInstanceField()) {
1360 it.Next();
1361 }
1362 while (it.HasNextDirectMethod()) {
1363 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1364 class_loader, true);
1365 SetGcMapsMethod(dex_file, method);
1366 it.Next();
1367 }
1368 while (it.HasNextVirtualMethod()) {
1369 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1370 class_loader, false);
1371 SetGcMapsMethod(dex_file, method);
1372 it.Next();
1373 }
1374 }
1375}
1376
1377void Compiler::SetGcMapsMethod(const DexFile& dex_file, Method* method) {
1378 if (method == NULL) {
1379 Thread::Current()->ClearException();
1380 return;
1381 }
1382 uint16_t method_idx = method->GetDexMethodIndex();
1383 MethodReference ref(&dex_file, method_idx);
1384 CompiledMethod* compiled_method = GetCompiledMethod(ref);
1385 if (compiled_method == NULL) {
1386 return;
1387 }
1388 const std::vector<uint8_t>* gc_map = verifier::DexVerifier::GetGcMap(ref);
1389 if (gc_map == NULL) {
1390 return;
1391 }
1392 compiled_method->SetGcMap(*gc_map);
1393}
1394
Logan Chien8b977d32012-02-21 19:14:55 +08001395#if defined(ART_USE_LLVM_COMPILER)
1396void Compiler::SetElfFileName(std::string const& filename) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001397 elf_filename_ = filename;
Logan Chien8b977d32012-02-21 19:14:55 +08001398}
1399
1400void Compiler::SetBitcodeFileName(std::string const& filename) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001401 bitcode_filename_ = filename;
1402}
1403std::string const& Compiler::GetElfFileName() {
1404 return elf_filename_;
1405}
1406std::string const& Compiler::GetBitcodeFileName() {
1407 return bitcode_filename_;
Logan Chien8b977d32012-02-21 19:14:55 +08001408}
1409#endif
1410
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001411} // namespace art