blob: 0431d74ef91e1d401acb7f8bba599937bbaf16bb [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) {
Elliott Hughes398f64b2012-03-26 18:05:48 -070057 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
Ian Rogers996cc582012-02-14 22:23:29 -080058}
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;
Elliott Hughesb25c3f62012-03-26 16:35:06 -070081 }
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
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700164 void UnresolvedInstanceField() {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800165 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
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700239 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
Ian Rogersc8b306f2012-02-17 21:34:44 -0800240};
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 Hughes67d92002012-03-26 15:08:51 -0700259 const char* suffix = (kIsDebugBuild ? "d" : "");
Elliott Hughes059d5c12012-03-12 17:39:18 -0700260
261 // Work out the filename for the compiler library.
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800262#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes059d5c12012-03-12 17:39:18 -0700263 std::string library_name(StringPrintf("art%s-compiler-%s", suffix, instruction_set_name.c_str()));
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800264#else
265 std::string library_name(StringPrintf("art%s-compiler-llvm", suffix));
266#endif
Elliott Hughes059d5c12012-03-12 17:39:18 -0700267 std::string filename(StringPrintf(OS_SHARED_LIB_FORMAT_STR, library_name.c_str()));
268
269#if defined(__APPLE__)
270 // On Linux, dex2oat will have been built with an RPATH of $ORIGIN/../lib, so dlopen(3) will find
271 // the .so by itself. On Mac OS, there isn't really an equivalent, so we have to manually do the
272 // same work.
273 std::vector<char> executable_path(1);
274 uint32_t executable_path_length = 0;
275 _NSGetExecutablePath(&executable_path[0], &executable_path_length);
276 while (_NSGetExecutablePath(&executable_path[0], &executable_path_length) == -1) {
277 executable_path.resize(executable_path_length);
278 }
279
280 executable_path.resize(executable_path.size() - 1); // Strip trailing NUL.
281 std::string path(&executable_path[0]);
282
283 // Strip the "/dex2oat".
284 size_t last_slash = path.find_last_of('/');
285 CHECK_NE(last_slash, std::string::npos) << path;
286 path.resize(last_slash);
287
288 // Strip the "/bin".
289 last_slash = path.find_last_of('/');
290 path.resize(last_slash);
291
292 filename = path + "/lib/" + filename;
293#endif
294 return filename;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800295}
296
Elliott Hughes46f060a2012-03-09 17:36:50 -0800297template<typename Fn>
298static Fn FindFunction(const std::string& compiler_so_name, void* library, const char* name) {
299 Fn fn = reinterpret_cast<Fn>(dlsym(library, name));
300 if (fn == NULL) {
301 LOG(FATAL) << "Couldn't find \"" << name << "\" in compiler library " << compiler_so_name << ": " << dlerror();
302 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700303 VLOG(compiler) << "Found \"" << name << "\" at " << reinterpret_cast<void*>(fn);
Elliott Hughes46f060a2012-03-09 17:36:50 -0800304 return fn;
305}
306
Elliott Hughes5523ee02012-02-03 18:18:34 -0800307Compiler::Compiler(InstructionSet instruction_set, bool image, size_t thread_count,
Brian Carlstromba0668e2012-03-26 13:14:07 -0700308 bool support_debugging, const std::set<std::string>* image_classes,
309 bool dump_stats, bool dump_timings)
Brian Carlstromaded5f72011-10-07 17:15:04 -0700310 : instruction_set_(instruction_set),
Elliott Hughesc225caa2012-02-03 15:43:37 -0800311 compiled_classes_lock_("compiled classes lock"),
312 compiled_methods_lock_("compiled method lock"),
313 compiled_invoke_stubs_lock_("compiled invoke stubs lock"),
Brian Carlstromaded5f72011-10-07 17:15:04 -0700314 image_(image),
Elliott Hughes5523ee02012-02-03 18:18:34 -0800315 thread_count_(thread_count),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800316 support_debugging_(support_debugging),
Ian Rogersc8b306f2012-02-17 21:34:44 -0800317 stats_(new AOTCompilationStats),
Brian Carlstromba0668e2012-03-26 13:14:07 -0700318 dump_stats_(dump_stats),
319 dump_timings_(dump_timings),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800320 image_classes_(image_classes),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800321 compiler_library_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800322 compiler_(NULL),
Elliott Hughes6f4976c2012-03-13 21:19:01 -0700323 compiler_context_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800324 jni_compiler_(NULL),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700325 create_invoke_stub_(NULL) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800326 std::string compiler_so_name(MakeCompilerSoName(instruction_set_));
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800327 compiler_library_ = dlopen(compiler_so_name.c_str(), RTLD_LAZY);
328 if (compiler_library_ == NULL) {
329 LOG(FATAL) << "Couldn't find compiler library " << compiler_so_name << ": " << dlerror();
330 }
331 VLOG(compiler) << "dlopen(\"" << compiler_so_name << "\", RTLD_LAZY) returned " << compiler_library_;
332
Logan Chien106b2a02012-03-18 04:41:38 +0800333#if defined(ART_USE_LLVM_COMPILER)
334 // Initialize compiler_context_
335 typedef void (*InitCompilerContextFn)(Compiler&);
336
337 InitCompilerContextFn init_compiler_context =
338 FindFunction<void (*)(Compiler&)>(compiler_so_name,
339 compiler_library_,
340 "ArtInitCompilerContext");
341
342 init_compiler_context(*this);
343#endif
344
Elliott Hughes3fa1b7e2012-03-13 17:06:22 -0700345 compiler_ = FindFunction<CompilerFn>(compiler_so_name, compiler_library_, "ArtCompileMethod");
Elliott Hughes46f060a2012-03-09 17:36:50 -0800346 jni_compiler_ = FindFunction<JniCompilerFn>(compiler_so_name, compiler_library_, "ArtJniCompileMethod");
347 create_invoke_stub_ = FindFunction<CreateInvokeStubFn>(compiler_so_name, compiler_library_, "ArtCreateInvokeStub");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800348
Brian Carlstrom25c33252011-09-18 15:58:35 -0700349 CHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800350 if (!image_) {
351 CHECK(image_classes_ == NULL);
352 }
Shih-wei Liaoc486c112011-09-13 16:43:52 -0700353}
354
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700355Compiler::~Compiler() {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800356 {
357 MutexLock mu(compiled_classes_lock_);
358 STLDeleteValues(&compiled_classes_);
359 }
360 {
361 MutexLock mu(compiled_methods_lock_);
362 STLDeleteValues(&compiled_methods_);
363 }
364 {
365 MutexLock mu(compiled_invoke_stubs_lock_);
366 STLDeleteValues(&compiled_invoke_stubs_);
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800367 }
Brian Carlstromf5822582012-03-19 22:34:31 -0700368 {
369 MutexLock mu(compiled_methods_lock_);
370 STLDeleteElements(&code_to_patch_);
371 }
372 {
373 MutexLock mu(compiled_methods_lock_);
374 STLDeleteElements(&methods_to_patch_);
375 }
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800376#if defined(ART_USE_LLVM_COMPILER)
377 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
378 compiler_library_,
379 "compilerLLVMDispose");
380 (*f)(*this);
381#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800382 if (compiler_library_ != NULL) {
383 VLOG(compiler) << "dlclose(" << compiler_library_ << ")";
384 dlclose(compiler_library_);
385 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700386}
387
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700388ByteArray* Compiler::CreateResolutionStub(InstructionSet instruction_set,
389 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700390 if (instruction_set == kX86) {
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700391 return x86::X86CreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700392 } else {
393 CHECK(instruction_set == kArm || instruction_set == kThumb2);
394 // Generates resolution stub using ARM instruction set
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700395 return arm::ArmCreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700396 }
397}
398
Elliott Hughes8add92d2012-01-18 18:18:43 -0800399ByteArray* Compiler::CreateJniDlsymLookupStub(InstructionSet instruction_set) {
Ian Rogers169c9a72011-11-13 20:13:17 -0800400 switch (instruction_set) {
401 case kArm:
402 case kThumb2:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800403 return arm::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800404 case kX86:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800405 return x86::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800406 default:
Ian Rogers49c48942012-03-11 15:15:37 -0700407 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
Ian Rogers169c9a72011-11-13 20:13:17 -0800408 return NULL;
409 }
410}
411
Ian Rogersad25ac52011-10-04 19:13:33 -0700412ByteArray* Compiler::CreateAbstractMethodErrorStub(InstructionSet instruction_set) {
413 if (instruction_set == kX86) {
414 return x86::CreateAbstractMethodErrorStub();
415 } else {
416 CHECK(instruction_set == kArm || instruction_set == kThumb2);
417 // Generates resolution stub using ARM instruction set
418 return arm::CreateAbstractMethodErrorStub();
419 }
420}
421
Jesse Wilson254db0f2011-11-16 16:44:11 -0500422void Compiler::CompileAll(const ClassLoader* class_loader,
Brian Carlstromae826982011-11-09 01:33:42 -0800423 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700424 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800425
Elliott Hughes601a1232012-02-02 17:47:38 -0800426 TimingLogger timings("compiler");
427
428 PreCompile(class_loader, dex_files, timings);
429
Brian Carlstromae826982011-11-09 01:33:42 -0800430 Compile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800431 timings.AddSplit("Compile");
432
Brian Carlstromae826982011-11-09 01:33:42 -0800433 PostCompile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800434 timings.AddSplit("PostCompile");
435
Brian Carlstromba0668e2012-03-26 13:14:07 -0700436 if (dump_timings_ && timings.GetTotalNs() > MsToNs(1000)) {
Elliott Hughes601a1232012-02-02 17:47:38 -0800437 timings.Dump();
438 }
Ian Rogers996cc582012-02-14 22:23:29 -0800439
Brian Carlstromba0668e2012-03-26 13:14:07 -0700440 if (dump_stats_) {
441 stats_->Dump();
442 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700443}
444
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700445void Compiler::CompileOne(const Method* method) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700446 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800447
Brian Carlstrom8a487412011-08-29 20:08:52 -0700448 const ClassLoader* class_loader = method->GetDeclaringClass()->GetClassLoader();
Brian Carlstromae826982011-11-09 01:33:42 -0800449
Ian Rogers0571d352011-11-03 19:51:38 -0700450 // Find the dex_file
451 const DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
452 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
Brian Carlstromae826982011-11-09 01:33:42 -0800453 std::vector<const DexFile*> dex_files;
454 dex_files.push_back(&dex_file);
455
Elliott Hughes601a1232012-02-02 17:47:38 -0800456 TimingLogger timings("CompileOne");
457 PreCompile(class_loader, dex_files, timings);
Brian Carlstromae826982011-11-09 01:33:42 -0800458
Ian Rogers0571d352011-11-03 19:51:38 -0700459 uint32_t method_idx = method->GetDexMethodIndex();
Ian Rogersa3760aa2011-11-14 14:32:37 -0800460 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
461 CompileMethod(code_item, method->GetAccessFlags(), method_idx, class_loader, dex_file);
Brian Carlstromae826982011-11-09 01:33:42 -0800462
463 PostCompile(class_loader, dex_files);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700464}
465
Brian Carlstromae826982011-11-09 01:33:42 -0800466void Compiler::Resolve(const ClassLoader* class_loader,
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800467 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -0800468 for (size_t i = 0; i != dex_files.size(); ++i) {
469 const DexFile* dex_file = dex_files[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700470 CHECK(dex_file != NULL);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800471 ResolveDexFile(class_loader, *dex_file, timings);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700472 }
473}
474
Brian Carlstromae826982011-11-09 01:33:42 -0800475void Compiler::PreCompile(const ClassLoader* class_loader,
Elliott Hughes601a1232012-02-02 17:47:38 -0800476 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800477 Resolve(class_loader, dex_files, timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800478
Brian Carlstromae826982011-11-09 01:33:42 -0800479 Verify(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800480 timings.AddSplit("PreCompile.Verify");
481
Brian Carlstromae826982011-11-09 01:33:42 -0800482 InitializeClassesWithoutClinit(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800483 timings.AddSplit("PreCompile.InitializeClassesWithoutClinit");
Brian Carlstromae826982011-11-09 01:33:42 -0800484}
485
486void Compiler::PostCompile(const ClassLoader* class_loader,
487 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800488 SetGcMaps(class_loader, dex_files);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800489#if defined(ART_USE_LLVM_COMPILER)
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800490 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
491 compiler_library_,
492 "compilerLLVMMaterializeRemainder");
493 (*f)(*this);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800494#endif
Brian Carlstromae826982011-11-09 01:33:42 -0800495}
496
497bool Compiler::IsImageClass(const std::string& descriptor) const {
498 if (image_classes_ == NULL) {
499 return true;
500 }
501 return image_classes_->find(descriptor) != image_classes_->end();
502}
503
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800504bool Compiler::CanAssumeTypeIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800505 uint32_t type_idx) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800506 if (!IsImage()) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800507 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800508 return false;
509 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800510 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800511 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800512 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800513 return false;
514 }
Ian Rogers996cc582012-02-14 22:23:29 -0800515 bool result = IsImageClass(ClassHelper(resolved_class).GetDescriptor());
516 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800517 stats_->TypeInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800518 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800519 stats_->TypeNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800520 }
521 return result;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800522}
523
Ian Rogers1bddec32012-02-04 12:27:34 -0800524bool Compiler::CanAssumeStringIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800525 uint32_t string_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800526 // TODO: Add support for loading strings referenced by image_classes_
527 // See also Compiler::ResolveDexFile
528
529 // The following is a test saying that if we're building the image without a restricted set of
530 // 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 -0800531 bool result = IsImage() && image_classes_ == NULL && dex_cache->GetResolvedString(string_idx) != NULL;
532 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800533 stats_->StringInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800534 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800535 stats_->StringNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800536 }
537 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800538}
539
540bool Compiler::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800541 const DexFile& dex_file, uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800542 // Get type from dex cache assuming it was populated by the verifier
543 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
544 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800545 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800546 return false; // Unknown class needs access checks.
547 }
548 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
549 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
550 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800551 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800552 return false; // Incomplete referrer knowledge needs access check.
553 }
554 // Perform access check, will return true if access is ok or false if we're going to have to
555 // check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800556 bool result = referrer_class->CanAccess(resolved_class);
557 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800558 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800559 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800560 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800561 }
562 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800563}
564
565bool Compiler::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
566 const DexCache* dex_cache,
567 const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800568 uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800569 // Get type from dex cache assuming it was populated by the verifier.
570 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
571 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800572 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800573 return false; // Unknown class needs access checks.
574 }
575 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
576 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
577 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800578 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800579 return false; // Incomplete referrer knowledge needs access check.
580 }
581 // Perform access and instantiable checks, will return true if access is ok or false if we're
582 // going to have to check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800583 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
584 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800585 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800586 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800587 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800588 }
589 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800590}
591
Logan Chien4dd96f52012-02-29 01:26:58 +0800592static Class* ComputeReferrerClass(OatCompilationUnit* mUnit) {
593 const DexFile::MethodId& referrer_method_id =
594 mUnit->dex_file_->GetMethodId(mUnit->method_idx_);
595
596 return mUnit->class_linker_->ResolveType(
597 *mUnit->dex_file_, referrer_method_id.class_idx_,
598 mUnit->dex_cache_, mUnit->class_loader_);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800599}
600
Logan Chien4dd96f52012-02-29 01:26:58 +0800601static Field* ComputeReferrerField(OatCompilationUnit* mUnit, uint32_t field_idx) {
602 return mUnit->class_linker_->ResolveField(
603 *mUnit->dex_file_, field_idx, mUnit->dex_cache_,
604 mUnit->class_loader_, false);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800605}
606
Logan Chien4dd96f52012-02-29 01:26:58 +0800607static Method* ComputeReferrerMethod(OatCompilationUnit* mUnit, uint32_t method_idx) {
608 return mUnit->class_linker_->ResolveMethod(
609 *mUnit->dex_file_, method_idx, mUnit->dex_cache_,
610 mUnit->class_loader_, true);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800611}
612
Logan Chien4dd96f52012-02-29 01:26:58 +0800613bool Compiler::ComputeInstanceFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
jeffhao8cd6dda2012-02-22 10:15:34 -0800614 int& field_offset, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800615 // Conservative defaults
616 field_offset = -1;
617 is_volatile = true;
618 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800619 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800620 if (resolved_field != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800621 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800622 // Try to resolve referring class then access check, failure to pass the
623 Class* fields_class = resolved_field->GetDeclaringClass();
jeffhao8cd6dda2012-02-22 10:15:34 -0800624 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal() &&
625 fields_class != referrer_class;
626 if (referrer_class != NULL && referrer_class->CanAccess(fields_class) &&
627 referrer_class->CanAccessMember(fields_class, resolved_field->GetAccessFlags()) &&
628 !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800629 field_offset = resolved_field->GetOffset().Int32Value();
630 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800631 stats_->ResolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800632 return true; // Fast path.
633 }
634 }
635 // Clean up any exception left by field/type resolution
636 Thread* thread = Thread::Current();
637 if (thread->IsExceptionPending()) {
638 thread->ClearException();
639 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800640 stats_->UnresolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800641 return false; // Incomplete knowledge needs slow path.
642}
643
Logan Chien4dd96f52012-02-29 01:26:58 +0800644bool Compiler::ComputeStaticFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
Ian Rogers1bddec32012-02-04 12:27:34 -0800645 int& field_offset, int& ssb_index,
jeffhao8cd6dda2012-02-22 10:15:34 -0800646 bool& is_referrers_class, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800647 // Conservative defaults
648 field_offset = -1;
649 ssb_index = -1;
650 is_referrers_class = false;
651 is_volatile = true;
652 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800653 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800654 if (resolved_field != NULL) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800655 DCHECK(resolved_field->IsStatic());
Logan Chien4dd96f52012-02-29 01:26:58 +0800656 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800657 if (referrer_class != NULL) {
jeffhao8cd6dda2012-02-22 10:15:34 -0800658 Class* fields_class = resolved_field->GetDeclaringClass();
659 if (fields_class == referrer_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800660 is_referrers_class = true; // implies no worrying about class initialization
661 field_offset = resolved_field->GetOffset().Int32Value();
662 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800663 stats_->ResolvedLocalStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800664 return true; // fast path
665 } else {
jeffhao8cd6dda2012-02-22 10:15:34 -0800666 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal();
Ian Rogers1bddec32012-02-04 12:27:34 -0800667 if (referrer_class->CanAccess(fields_class) &&
jeffhao8cd6dda2012-02-22 10:15:34 -0800668 referrer_class->CanAccessMember(fields_class, resolved_field->GetAccessFlags()) &&
669 !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800670 // We have the resolved field, we must make it into a ssbIndex for the referrer
671 // in its static storage base (which may fail if it doesn't have a slot for it)
Ian Rogers4103ad22012-02-06 09:18:25 -0800672 // TODO: for images we can elide the static storage base null check
673 // if we know there's a non-null entry in the image
Logan Chien4dd96f52012-02-29 01:26:58 +0800674 if (fields_class->GetDexCache() == mUnit->dex_cache_) {
Ian Rogers4103ad22012-02-06 09:18:25 -0800675 // common case where the dex cache of both the referrer and the field are the same,
676 // no need to search the dex file
677 ssb_index = fields_class->GetDexTypeIndex();
678 field_offset = resolved_field->GetOffset().Int32Value();
679 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800680 stats_->ResolvedStaticField();
Ian Rogers4103ad22012-02-06 09:18:25 -0800681 return true;
682 }
683 // Search dex file for localized ssb index
Ian Rogers1bddec32012-02-04 12:27:34 -0800684 std::string descriptor(FieldHelper(resolved_field).GetDeclaringClassDescriptor());
685 const DexFile::StringId* string_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800686 mUnit->dex_file_->FindStringId(descriptor);
Ian Rogers1bddec32012-02-04 12:27:34 -0800687 if (string_id != NULL) {
688 const DexFile::TypeId* type_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800689 mUnit->dex_file_->FindTypeId(mUnit->dex_file_->GetIndexForStringId(*string_id));
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700690 if (type_id != NULL) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800691 // medium path, needs check of static storage base being initialized
Logan Chien4dd96f52012-02-29 01:26:58 +0800692 ssb_index = mUnit->dex_file_->GetIndexForTypeId(*type_id);
Ian Rogers1bddec32012-02-04 12:27:34 -0800693 field_offset = resolved_field->GetOffset().Int32Value();
694 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800695 stats_->ResolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800696 return true;
697 }
698 }
699 }
700 }
701 }
702 }
703 // Clean up any exception left by field/type resolution
704 Thread* thread = Thread::Current();
705 if (thread->IsExceptionPending()) {
706 thread->ClearException();
707 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800708 stats_->UnresolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800709 return false; // Incomplete knowledge needs slow path.
710}
711
Ian Rogers2ed3b952012-03-17 11:49:39 -0700712void Compiler::GetCodeAndMethodForDirectCall(InvokeType type, InvokeType sharp_type, Method* method,
713 uintptr_t& direct_code, uintptr_t& direct_method) {
714 direct_code = 0;
715 direct_method = 0;
716 if (sharp_type != kStatic && sharp_type != kDirect) {
717 return;
718 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700719 bool method_code_in_boot = method->GetDeclaringClass()->GetClassLoader() == NULL;
720 if (!method_code_in_boot) {
721 return;
722 }
723 bool has_clinit_trampoline = method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
724 if (has_clinit_trampoline) {
725 return;
726 }
727 stats_->DirectCallsToBoot(type);
728 stats_->DirectMethodsToBoot(type);
Ian Rogers3fa13792012-03-18 15:53:45 -0700729 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
730 if (compiling_boot) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700731 const bool kSupportBootImageFixup = true;
Ian Rogers3fa13792012-03-18 15:53:45 -0700732 if (kSupportBootImageFixup) {
733 MethodHelper mh(method);
734 if (IsImageClass(mh.GetDeclaringClassDescriptor())) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700735 // We can only branch directly to Methods that are resolved in the DexCache.
736 // Otherwise we won't invoke the resolution trampoline.
Ian Rogers3fa13792012-03-18 15:53:45 -0700737 direct_method = -1;
Brian Carlstrom0637e272012-03-20 01:07:52 -0700738 direct_code = -1;
Ian Rogers3fa13792012-03-18 15:53:45 -0700739 }
Ian Rogers3fa13792012-03-18 15:53:45 -0700740 }
741 } else {
742 if (Runtime::Current()->GetHeap()->GetImageSpace()->Contains(method)) {
743 direct_method = reinterpret_cast<uintptr_t>(method);
744 }
745 direct_code = reinterpret_cast<uintptr_t>(method->GetCode());
Ian Rogers2ed3b952012-03-17 11:49:39 -0700746 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700747}
748
Ian Rogersfb6adba2012-03-04 21:51:51 -0800749bool Compiler::ComputeInvokeInfo(uint32_t method_idx, OatCompilationUnit* mUnit, InvokeType& type,
Ian Rogers2ed3b952012-03-17 11:49:39 -0700750 int& vtable_idx, uintptr_t& direct_code,
751 uintptr_t& direct_method) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800752 vtable_idx = -1;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700753 direct_code = 0;
754 direct_method = 0;
Logan Chien4dd96f52012-02-29 01:26:58 +0800755 Method* resolved_method = ComputeReferrerMethod(mUnit, method_idx);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800756 if (resolved_method != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800757 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800758 if (referrer_class != NULL) {
759 Class* methods_class = resolved_method->GetDeclaringClass();
760 if (!referrer_class->CanAccess(methods_class) ||
761 !referrer_class->CanAccessMember(methods_class,
Ian Rogers996cc582012-02-14 22:23:29 -0800762 resolved_method->GetAccessFlags())) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800763 // The referring class can't access the resolved method, this may occur as a result of a
764 // protected method being made public by implementing an interface that re-declares the
765 // method public. Resort to the dex file to determine the correct class for the access check
Logan Chien4dd96f52012-02-29 01:26:58 +0800766 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800767 methods_class =
Logan Chien4dd96f52012-02-29 01:26:58 +0800768 mUnit->class_linker_->ResolveType(dex_file,
769 dex_file.GetMethodId(method_idx).class_idx_,
770 referrer_class);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800771 }
772 if (referrer_class->CanAccess(methods_class) &&
773 referrer_class->CanAccessMember(methods_class,
774 resolved_method->GetAccessFlags())) {
775 vtable_idx = resolved_method->GetMethodIndex();
Ian Rogersf320b632012-03-13 18:47:47 -0700776 const bool kEnableSharpening = true;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700777 // Sharpen a virtual call into a direct call when the target is known.
778 bool can_sharpen = type == kVirtual && (resolved_method->IsFinal() ||
779 methods_class->IsFinal());
780 // ensure the vtable index will be correct to dispatch in the vtable of the super class
jeffhao4155fcd2012-03-21 11:42:12 -0700781 can_sharpen = can_sharpen || (type == kSuper && referrer_class != methods_class &&
Ian Rogers2ed3b952012-03-17 11:49:39 -0700782 referrer_class->IsSubClass(methods_class) &&
jeffhao4155fcd2012-03-21 11:42:12 -0700783 vtable_idx < methods_class->GetVTable()->GetLength() &&
784 methods_class->GetVTable()->Get(vtable_idx) == resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700785 if (kEnableSharpening && can_sharpen) {
786 stats_->ResolvedMethod(type);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800787 // Sharpen a virtual call into a direct call. The method_idx is into referrer's
788 // dex cache, check that this resolved method is where we expect it.
789 CHECK(referrer_class->GetDexCache()->GetResolvedMethod(method_idx) == resolved_method)
790 << PrettyMethod(resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700791 stats_->VirtualMadeDirect(type);
792 GetCodeAndMethodForDirectCall(type, kDirect, resolved_method, direct_code, direct_method);
793 type = kDirect;
794 return true;
795 } else if (type == kSuper) {
796 // Unsharpened super calls are suspicious so go slowpath.
797 } else {
798 stats_->ResolvedMethod(type);
799 GetCodeAndMethodForDirectCall(type, type, resolved_method, direct_code, direct_method);
800 return true;
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800801 }
802 }
803 }
804 }
805 // Clean up any exception left by method/type resolution
806 Thread* thread = Thread::Current();
807 if (thread->IsExceptionPending()) {
808 thread->ClearException();
809 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800810 stats_->UnresolvedMethod(type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800811 return false; // Incomplete knowledge needs slow path.
812}
813
Brian Carlstromf5822582012-03-19 22:34:31 -0700814void Compiler::AddCodePatch(DexCache* dex_cache,
815 const DexFile* dex_file,
816 uint32_t referrer_method_idx,
817 uint32_t referrer_access_flags,
818 uint32_t target_method_idx,
819 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700820 size_t literal_offset) {
821 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700822 code_to_patch_.push_back(new PatchInformation(dex_cache,
823 dex_file,
824 referrer_method_idx,
825 referrer_access_flags,
826 target_method_idx,
827 target_is_direct,
828 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700829}
Brian Carlstromf5822582012-03-19 22:34:31 -0700830void Compiler::AddMethodPatch(DexCache* dex_cache,
831 const DexFile* dex_file,
832 uint32_t referrer_method_idx,
833 uint32_t referrer_access_flags,
834 uint32_t target_method_idx,
835 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700836 size_t literal_offset) {
837 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700838 methods_to_patch_.push_back(new PatchInformation(dex_cache,
839 dex_file,
840 referrer_method_idx,
841 referrer_access_flags,
842 target_method_idx,
843 target_is_direct,
844 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700845}
846
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800847// Return true if the class should be skipped during compilation. We
848// never skip classes in the boot class loader. However, if we have a
849// non-boot class loader and we can resolve the class in the boot
850// class loader, we do skip the class. This happens if an app bundles
851// classes found in the boot classpath. Since at runtime we will
852// select the class from the boot classpath, do not attempt to resolve
853// or compile it now.
854static bool SkipClass(const ClassLoader* class_loader,
855 const DexFile& dex_file,
856 const DexFile::ClassDef& class_def) {
857 if (class_loader == NULL) {
858 return false;
859 }
860 const char* descriptor = dex_file.GetClassDescriptor(class_def);
861 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
862 Class* klass = class_linker->FindClass(descriptor, NULL);
863 if (klass == NULL) {
864 Thread* self = Thread::Current();
865 CHECK(self->IsExceptionPending());
866 self->ClearException();
867 return false;
868 }
869 return true;
870}
871
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800872class Context {
873 public:
874 Context(ClassLinker* class_linker,
875 const ClassLoader* class_loader,
876 Compiler* compiler,
877 DexCache* dex_cache,
878 const DexFile* dex_file)
879 : class_linker_(class_linker),
880 class_loader_(class_loader),
881 compiler_(compiler),
882 dex_cache_(dex_cache),
883 dex_file_(dex_file) {}
884
885 ClassLinker* GetClassLinker() {
886 CHECK(class_linker_ != NULL);
887 return class_linker_;
888 }
889 const ClassLoader* GetClassLoader() {
890 return class_loader_;
891 }
892 Compiler* GetCompiler() {
893 CHECK(compiler_ != NULL);
894 return compiler_;
895 }
896 DexCache* GetDexCache() {
897 CHECK(dex_cache_ != NULL);
898 return dex_cache_;
899 }
900 const DexFile* GetDexFile() {
901 CHECK(dex_file_ != NULL);
902 return dex_file_;
903 }
904
905 private:
906 ClassLinker* class_linker_;
907 const ClassLoader* class_loader_;
908 Compiler* compiler_;
909 DexCache* dex_cache_;
910 const DexFile* dex_file_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800911};
912
913typedef void Callback(Context* context, size_t index);
914
915class WorkerThread {
916 public:
Elliott Hughes1e409252012-02-06 11:21:27 -0800917 WorkerThread(Context* context, size_t begin, size_t end, Callback callback, size_t stripe, bool spawn)
918 : spawn_(spawn), context_(context), begin_(begin), end_(end), callback_(callback), stripe_(stripe) {
919 if (spawn_) {
920 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, NULL, &Go, this), "compiler worker thread");
921 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800922 }
923
924 ~WorkerThread() {
Elliott Hughes1e409252012-02-06 11:21:27 -0800925 if (spawn_) {
926 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
927 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800928 }
929
930 private:
Elliott Hughes1e409252012-02-06 11:21:27 -0800931 static void* Go(void* arg) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800932 WorkerThread* worker = reinterpret_cast<WorkerThread*>(arg);
933 Runtime* runtime = Runtime::Current();
Elliott Hughes1e409252012-02-06 11:21:27 -0800934 if (worker->spawn_) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700935 runtime->AttachCurrentThread("Compiler Worker", true, NULL);
Elliott Hughes1e409252012-02-06 11:21:27 -0800936 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800937 Thread::Current()->SetState(Thread::kRunnable);
938 worker->Run();
Elliott Hughes1e409252012-02-06 11:21:27 -0800939 if (worker->spawn_) {
940 Thread::Current()->SetState(Thread::kNative);
941 runtime->DetachCurrentThread();
942 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800943 return NULL;
944 }
945
Elliott Hughes1e409252012-02-06 11:21:27 -0800946 void Go() {
947 Go(this);
948 }
949
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800950 void Run() {
951 for (size_t i = begin_; i < end_; i += stripe_) {
952 callback_(context_, i);
953 }
954 }
955
956 pthread_t pthread_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800957 bool spawn_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800958
959 Context* context_;
960 size_t begin_;
961 size_t end_;
962 Callback* callback_;
963 size_t stripe_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800964
965 friend void ForAll(Context*, size_t, size_t, Callback, size_t);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800966};
967
Elliott Hughes5523ee02012-02-03 18:18:34 -0800968void ForAll(Context* context, size_t begin, size_t end, Callback callback, size_t thread_count) {
Elliott Hughes1e409252012-02-06 11:21:27 -0800969 CHECK_GT(thread_count, 0U);
Elliott Hughes81d91512012-02-03 16:38:43 -0800970
Elliott Hughes1e409252012-02-06 11:21:27 -0800971 std::vector<WorkerThread*> threads;
Elliott Hughes81d91512012-02-03 16:38:43 -0800972 for (size_t i = 0; i < thread_count; ++i) {
Elliott Hughes1e409252012-02-06 11:21:27 -0800973 threads.push_back(new WorkerThread(context, begin + i, end, callback, thread_count, (i != 0)));
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800974 }
Elliott Hughes1e409252012-02-06 11:21:27 -0800975 threads[0]->Go();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800976
Elliott Hughes81d91512012-02-03 16:38:43 -0800977 // Switch to kVmWait while we're blocked waiting for the other threads to finish.
978 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
979 STLDeleteElements(&threads);
980}
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800981
982static void ResolveClassFieldsAndMethods(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800983 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800984
985 // Method and Field are the worst. We can't resolve without either
986 // context from the code use (to disambiguate virtual vs direct
987 // method and instance vs static field) or from class
988 // definitions. While the compiler will resolve what it can as it
989 // needs it, here we try to resolve fields and methods used in class
990 // definitions, since many of them many never be referenced by
991 // generated code.
992 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800993 if (SkipClass(context->GetClassLoader(), dex_file, class_def)) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800994 return;
995 }
996
997 // Note the class_data pointer advances through the headers,
998 // static fields, instance fields, direct methods, and virtual
999 // methods.
1000 const byte* class_data = dex_file.GetClassData(class_def);
1001 if (class_data == NULL) {
1002 // empty class such as a marker interface
1003 return;
1004 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001005 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001006 ClassLinker* class_linker = context->GetClassLinker();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001007 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1008 ClassDataItemIterator it(dex_file, class_data);
1009 while (it.HasNextStaticField()) {
1010 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001011 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001012 if (field == NULL) {
1013 CHECK(self->IsExceptionPending());
1014 self->ClearException();
1015 }
1016 it.Next();
1017 }
1018 while (it.HasNextInstanceField()) {
1019 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001020 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001021 if (field == NULL) {
1022 CHECK(self->IsExceptionPending());
1023 self->ClearException();
1024 }
1025 it.Next();
1026 }
1027 while (it.HasNextDirectMethod()) {
1028 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001029 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001030 if (method == NULL) {
1031 CHECK(self->IsExceptionPending());
1032 self->ClearException();
1033 }
1034 it.Next();
1035 }
1036 while (it.HasNextVirtualMethod()) {
1037 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001038 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001039 if (method == NULL) {
1040 CHECK(self->IsExceptionPending());
1041 self->ClearException();
1042 }
1043 it.Next();
1044 }
1045 DCHECK(!it.HasNext());
1046}
1047
1048static void ResolveType(Context* context, size_t type_idx) {
1049 // Class derived values are more complicated, they require the linker and loader.
1050 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001051 Class* klass = context->GetClassLinker()->ResolveType(*context->GetDexFile(),
1052 type_idx,
1053 context->GetDexCache(),
1054 context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001055 if (klass == NULL) {
1056 CHECK(self->IsExceptionPending());
1057 Thread::Current()->ClearException();
1058 }
1059}
1060
1061void Compiler::ResolveDexFile(const ClassLoader* class_loader, const DexFile& dex_file, TimingLogger& timings) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001062 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001063 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001064
Brian Carlstromae826982011-11-09 01:33:42 -08001065 // Strings are easy in that they always are simply resolved to literals in the same file
1066 if (image_ && image_classes_ == NULL) {
1067 // TODO: Add support for loading strings referenced by image_classes_
1068 // See also Compiler::CanAssumeTypeIsPresentInDexCache.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001069 for (size_t string_idx = 0; string_idx < dex_cache->NumStrings(); string_idx++) {
1070 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1071 }
Elliott Hughesff738062012-02-03 15:00:42 -08001072 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Strings");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001073 }
1074
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001075 Context context(class_linker, class_loader, this, dex_cache, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001076 ForAll(&context, 0, dex_cache->NumResolvedTypes(), ResolveType, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001077 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Types");
Brian Carlstrom845490b2011-09-19 15:56:53 -07001078
Elliott Hughes5523ee02012-02-03 18:18:34 -08001079 ForAll(&context, 0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001080 timings.AddSplit("Resolve " + dex_file.GetLocation() + " MethodsAndFields");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001081}
1082
Brian Carlstromae826982011-11-09 01:33:42 -08001083void Compiler::Verify(const ClassLoader* class_loader,
1084 const std::vector<const DexFile*>& dex_files) {
1085 for (size_t i = 0; i != dex_files.size(); ++i) {
1086 const DexFile* dex_file = dex_files[i];
jeffhao98eacac2011-09-14 16:11:53 -07001087 CHECK(dex_file != NULL);
1088 VerifyDexFile(class_loader, *dex_file);
1089 }
1090}
1091
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001092static void VerifyClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001093 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
1094 const char* descriptor = context->GetDexFile()->GetClassDescriptor(class_def);
1095 Class* klass = context->GetClassLinker()->FindClass(descriptor, context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001096 if (klass == NULL) {
1097 Thread* self = Thread::Current();
1098 CHECK(self->IsExceptionPending());
1099 self->ClearException();
jeffhaof56197c2012-03-05 18:01:54 -08001100
1101 /*
1102 * At compile time, we can still structurally verify the class even if FindClass fails.
1103 * This is to ensure the class is structurally sound for compilation. An unsound class
1104 * will be rejected by the verifier and later skipped during compilation in the compiler.
1105 */
1106 std::string error_msg;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001107 if (!verifier::DexVerifier::VerifyClass(context->GetDexFile(), context->GetDexCache(),
1108 context->GetClassLoader(), class_def_index, error_msg)) {
1109 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
jeffhaof56197c2012-03-05 18:01:54 -08001110 LOG(ERROR) << "Verification failed on class "
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001111 << PrettyDescriptor(context->GetDexFile()->GetClassDescriptor(class_def))
jeffhaof56197c2012-03-05 18:01:54 -08001112 << " because: " << error_msg;
1113 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001114 return;
1115 }
1116 CHECK(klass->IsResolved()) << PrettyClass(klass);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001117 context->GetClassLinker()->VerifyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001118
1119 if (klass->IsErroneous()) {
1120 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1121 CHECK(Thread::Current()->IsExceptionPending());
1122 Thread::Current()->ClearException();
jeffhao1ac29442012-03-26 11:37:32 -07001123 art::Compiler::ClassReference ref(context->GetDexFile(), class_def_index);
1124 if (!verifier::DexVerifier::IsClassRejected(ref)) {
1125 // If the erroneous class wasn't rejected by the verifier, it was a soft error. We want
1126 // to try verification again at run-time, so move back into the resolved state.
1127 klass->SetStatus(Class::kStatusResolved);
1128 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001129 }
1130
jeffhao1ac29442012-03-26 11:37:32 -07001131 CHECK(klass->IsVerified() || klass->IsResolved() || klass->IsErroneous()) << PrettyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001132 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1133}
1134
jeffhao98eacac2011-09-14 16:11:53 -07001135void Compiler::VerifyDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
jeffhaob4df5142011-09-19 20:25:32 -07001136 dex_file.ChangePermissions(PROT_READ | PROT_WRITE);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001137
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001138 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1139 Context context(class_linker, class_loader, this, class_linker->FindDexCache(dex_file), &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001140 ForAll(&context, 0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001141
jeffhaob4df5142011-09-19 20:25:32 -07001142 dex_file.ChangePermissions(PROT_READ);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001143}
1144
Brian Carlstromae826982011-11-09 01:33:42 -08001145void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader,
1146 const std::vector<const DexFile*>& dex_files) {
1147 for (size_t i = 0; i != dex_files.size(); ++i) {
1148 const DexFile* dex_file = dex_files[i];
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001149 CHECK(dex_file != NULL);
1150 InitializeClassesWithoutClinit(class_loader, *dex_file);
1151 }
1152}
1153
1154void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader, const DexFile& dex_file) {
1155 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001156 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1157 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001158 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1159 Class* klass = class_linker->FindClass(descriptor, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001160 if (klass != NULL) {
jeffhao1ac29442012-03-26 11:37:32 -07001161 if (klass->IsVerified()) {
1162 // Only try to initialize classes that were successfully verified.
1163 class_linker->EnsureInitialized(klass, false);
1164 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001165 // record the final class status if necessary
1166 Class::Status status = klass->GetStatus();
1167 ClassReference ref(&dex_file, class_def_index);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001168 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001169 CompiledClass* compiled_class = GetCompiledClass(ref);
1170 if (compiled_class == NULL) {
1171 compiled_class = new CompiledClass(status);
1172 compiled_classes_[ref] = compiled_class;
1173 } else {
1174 DCHECK_EQ(status, compiled_class->GetStatus());
1175 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001176 }
1177 // clear any class not found or verification exceptions
1178 Thread::Current()->ClearException();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001179 }
1180
1181 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1182 for (size_t type_idx = 0; type_idx < dex_cache->NumResolvedTypes(); type_idx++) {
1183 Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001184 if (klass == NULL) {
1185 Thread::Current()->ClearException();
1186 } else if (klass->IsInitialized()) {
Brian Carlstromffca45d2011-09-16 12:10:49 -07001187 dex_cache->GetInitializedStaticStorage()->Set(type_idx, klass);
1188 }
jeffhao98eacac2011-09-14 16:11:53 -07001189 }
1190}
1191
Brian Carlstromae826982011-11-09 01:33:42 -08001192void Compiler::Compile(const ClassLoader* class_loader,
1193 const std::vector<const DexFile*>& dex_files) {
1194 for (size_t i = 0; i != dex_files.size(); ++i) {
1195 const DexFile* dex_file = dex_files[i];
Brian Carlstrom83db7722011-08-26 17:32:56 -07001196 CHECK(dex_file != NULL);
1197 CompileDexFile(class_loader, *dex_file);
1198 }
1199}
1200
Elliott Hughesc225caa2012-02-03 15:43:37 -08001201void Compiler::CompileClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001202 const ClassLoader* class_loader = context->GetClassLoader();
1203 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesc225caa2012-02-03 15:43:37 -08001204 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Logan Chien7f767612012-03-01 18:54:49 +08001205#if defined(ART_USE_LLVM_COMPILER)
Logan Chien7f767612012-03-01 18:54:49 +08001206 // TODO: Remove this. We should not lock the compiler_lock_ in CompileClass()
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001207 // However, without this mutex lock, we will get segmentation fault before
1208 // LLVM becomes multithreaded.
1209 Compiler* cmplr = context->GetCompiler();
1210 CompilerMutexLockFn f =
1211 FindFunction<CompilerMutexLockFn>(MakeCompilerSoName(cmplr->GetInstructionSet()),
1212 cmplr->compiler_library_,
1213 "compilerLLVMMutexLock");
1214 UniquePtr<MutexLock> GUARD((*f)(*cmplr));
Logan Chien7f767612012-03-01 18:54:49 +08001215#endif
1216
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001217 if (SkipClass(class_loader, dex_file, class_def)) {
1218 return;
1219 }
jeffhaod1224c72012-02-29 13:43:08 -08001220 ClassReference ref(&dex_file, class_def_index);
1221 // Skip compiling classes with generic verifier failures since they will still fail at runtime
1222 if (verifier::DexVerifier::IsClassRejected(ref)) {
1223 return;
1224 }
Ian Rogers0571d352011-11-03 19:51:38 -07001225 const byte* class_data = dex_file.GetClassData(class_def);
1226 if (class_data == NULL) {
1227 // empty class, probably a marker interface
1228 return;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001229 }
Ian Rogers0571d352011-11-03 19:51:38 -07001230 ClassDataItemIterator it(dex_file, class_data);
1231 // Skip fields
1232 while (it.HasNextStaticField()) {
1233 it.Next();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001234 }
Ian Rogers0571d352011-11-03 19:51:38 -07001235 while (it.HasNextInstanceField()) {
1236 it.Next();
1237 }
1238 // Compile direct methods
1239 while (it.HasNextDirectMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001240 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1241 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001242 it.Next();
1243 }
1244 // Compile virtual methods
1245 while (it.HasNextVirtualMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001246 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1247 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001248 it.Next();
1249 }
1250 DCHECK(!it.HasNext());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001251}
1252
Elliott Hughesc225caa2012-02-03 15:43:37 -08001253void Compiler::CompileDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001254 Context context(NULL, class_loader, this, NULL, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001255 ForAll(&context, 0, dex_file.NumClassDefs(), Compiler::CompileClass, thread_count_);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001256}
1257
Ian Rogersa3760aa2011-11-14 14:32:37 -08001258void Compiler::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
1259 uint32_t method_idx, const ClassLoader* class_loader,
1260 const DexFile& dex_file) {
Elliott Hughesf09afe82011-10-16 14:24:21 -07001261 CompiledMethod* compiled_method = NULL;
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001262 uint64_t start_ns = NanoTime();
Logan Chien4dd96f52012-02-29 01:26:58 +08001263
Ian Rogers169c9a72011-11-13 20:13:17 -08001264 if ((access_flags & kAccNative) != 0) {
Elliott Hughes46f060a2012-03-09 17:36:50 -08001265 compiled_method = (*jni_compiler_)(*this, access_flags, method_idx, class_loader, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001266 CHECK(compiled_method != NULL);
Ian Rogers169c9a72011-11-13 20:13:17 -08001267 } else if ((access_flags & kAccAbstract) != 0) {
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001268 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001269 compiled_method = (*compiler_)(*this, code_item, access_flags, method_idx, class_loader,
1270 dex_file);
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001271 CHECK(compiled_method != NULL) << PrettyMethod(method_idx, dex_file);
1272 }
Ian Rogers3bb17a62012-01-27 23:56:44 -08001273 uint64_t duration_ns = NanoTime() - start_ns;
buzbee5abfa3e2012-01-31 17:01:43 -08001274 if (duration_ns > MsToNs(100)) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001275 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
Ian Rogers3bb17a62012-01-27 23:56:44 -08001276 << " took " << PrettyDuration(duration_ns);
Elliott Hughesf09afe82011-10-16 14:24:21 -07001277 }
1278
1279 if (compiled_method != NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07001280 MethodReference ref(&dex_file, method_idx);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001281 CHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001282 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001283 compiled_methods_[ref] = compiled_method;
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001284 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001285 }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -07001286
Ian Rogers45619fc2012-02-29 11:15:25 -08001287 uint32_t shorty_len;
1288 const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx), &shorty_len);
Ian Rogers169c9a72011-11-13 20:13:17 -08001289 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001290 const CompiledInvokeStub* compiled_invoke_stub = FindInvokeStub(is_static, shorty);
1291 if (compiled_invoke_stub == NULL) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001292 compiled_invoke_stub = (*create_invoke_stub_)(*this, is_static, shorty, shorty_len);
Ian Rogers0571d352011-11-03 19:51:38 -07001293 CHECK(compiled_invoke_stub != NULL);
1294 InsertInvokeStub(is_static, shorty, compiled_invoke_stub);
Ian Rogers2c8f6532011-09-02 17:16:34 -07001295 }
Ian Rogers0571d352011-11-03 19:51:38 -07001296 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001297}
1298
Ian Rogers0571d352011-11-03 19:51:38 -07001299static std::string MakeInvokeStubKey(bool is_static, const char* shorty) {
1300 std::string key(shorty);
1301 if (is_static) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001302 key += "$"; // Must not be a shorty type character.
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001303 }
Ian Rogers0571d352011-11-03 19:51:38 -07001304 return key;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001305}
1306
Ian Rogers0571d352011-11-03 19:51:38 -07001307const CompiledInvokeStub* Compiler::FindInvokeStub(bool is_static, const char* shorty) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001308 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001309 const std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001310 InvokeStubTable::const_iterator it = compiled_invoke_stubs_.find(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001311 if (it == compiled_invoke_stubs_.end()) {
1312 return NULL;
Ian Rogers0571d352011-11-03 19:51:38 -07001313 } else {
1314 DCHECK(it->second != NULL);
1315 return it->second;
1316 }
1317}
1318
1319void Compiler::InsertInvokeStub(bool is_static, const char* shorty,
1320 const CompiledInvokeStub* compiled_invoke_stub) {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001321 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001322 std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001323 compiled_invoke_stubs_[key] = compiled_invoke_stub;
1324}
1325
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001326CompiledClass* Compiler::GetCompiledClass(ClassReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001327 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001328 ClassTable::const_iterator it = compiled_classes_.find(ref);
1329 if (it == compiled_classes_.end()) {
1330 return NULL;
1331 }
1332 CHECK(it->second != NULL);
1333 return it->second;
1334}
1335
Ian Rogers0571d352011-11-03 19:51:38 -07001336CompiledMethod* Compiler::GetCompiledMethod(MethodReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001337 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001338 MethodTable::const_iterator it = compiled_methods_.find(ref);
1339 if (it == compiled_methods_.end()) {
1340 return NULL;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001341 }
1342 CHECK(it->second != NULL);
1343 return it->second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001344}
1345
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001346void Compiler::SetGcMaps(const ClassLoader* class_loader, const std::vector<const DexFile*>& dex_files) {
1347 for (size_t i = 0; i != dex_files.size(); ++i) {
1348 const DexFile* dex_file = dex_files[i];
1349 CHECK(dex_file != NULL);
1350 SetGcMapsDexFile(class_loader, *dex_file);
1351 }
1352}
1353
1354void Compiler::SetGcMapsDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
1355 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1356 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1357 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1358 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1359 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1360 Class* klass = class_linker->FindClass(descriptor, class_loader);
1361 if (klass == NULL || !klass->IsVerified()) {
1362 Thread::Current()->ClearException();
1363 continue;
1364 }
1365 const byte* class_data = dex_file.GetClassData(class_def);
1366 if (class_data == NULL) {
1367 // empty class such as a marker interface
1368 continue;
1369 }
1370 ClassDataItemIterator it(dex_file, class_data);
1371 while (it.HasNextStaticField()) {
1372 it.Next();
1373 }
1374 while (it.HasNextInstanceField()) {
1375 it.Next();
1376 }
1377 while (it.HasNextDirectMethod()) {
1378 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1379 class_loader, true);
1380 SetGcMapsMethod(dex_file, method);
1381 it.Next();
1382 }
1383 while (it.HasNextVirtualMethod()) {
1384 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1385 class_loader, false);
1386 SetGcMapsMethod(dex_file, method);
1387 it.Next();
1388 }
1389 }
1390}
1391
1392void Compiler::SetGcMapsMethod(const DexFile& dex_file, Method* method) {
1393 if (method == NULL) {
1394 Thread::Current()->ClearException();
1395 return;
1396 }
1397 uint16_t method_idx = method->GetDexMethodIndex();
1398 MethodReference ref(&dex_file, method_idx);
1399 CompiledMethod* compiled_method = GetCompiledMethod(ref);
1400 if (compiled_method == NULL) {
1401 return;
1402 }
1403 const std::vector<uint8_t>* gc_map = verifier::DexVerifier::GetGcMap(ref);
1404 if (gc_map == NULL) {
1405 return;
1406 }
1407 compiled_method->SetGcMap(*gc_map);
1408}
1409
Logan Chien8b977d32012-02-21 19:14:55 +08001410#if defined(ART_USE_LLVM_COMPILER)
1411void Compiler::SetElfFileName(std::string const& filename) {
Logan Chien106b2a02012-03-18 04:41:38 +08001412 typedef void (*SetElfFileNameFn)(Compiler&, std::string const&);
1413
1414 SetElfFileNameFn set_elf_file_name =
1415 FindFunction<SetElfFileNameFn>(MakeCompilerSoName(instruction_set_),
1416 compiler_library_,
1417 "compilerLLVMSetElfFileName");
1418
1419 set_elf_file_name(*this, filename);
Logan Chien8b977d32012-02-21 19:14:55 +08001420}
1421
1422void Compiler::SetBitcodeFileName(std::string const& filename) {
Logan Chien106b2a02012-03-18 04:41:38 +08001423 typedef void (*SetBitcodeFileNameFn)(Compiler&, std::string const&);
1424
1425 SetBitcodeFileNameFn set_bitcode_file_name =
1426 FindFunction<SetBitcodeFileNameFn>(MakeCompilerSoName(instruction_set_),
1427 compiler_library_,
1428 "compilerLLVMSetBitcodeFileName");
1429
1430 set_bitcode_file_name(*this, filename);
Logan Chien8b977d32012-02-21 19:14:55 +08001431}
1432#endif
1433
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001434} // namespace art