blob: 903b70a4ad8f8c85031229f514f3ed5cb978df9a [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>
Elliott Hughesd9c67be2012-02-02 19:54:06 -080022#include <unistd.h>
Brian Carlstrom27ec9612011-09-19 20:20:38 -070023
Elliott Hughes1aa246d2012-12-13 09:29:36 -080024#include "base/stl_util.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070025#include "class_linker.h"
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -070026#include "jni_internal.h"
Logan Chien4dd96f52012-02-29 01:26:58 +080027#include "oat_compilation_unit.h"
Brian Carlstrom3320cf42011-10-04 14:58:28 -070028#include "oat_file.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070029#include "oat/runtime/stub.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080030#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070031#include "runtime.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "gc/card_table-inl.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070033#include "gc/space.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080034#include "mirror/class_loader.h"
35#include "mirror/class-inl.h"
36#include "mirror/dex_cache.h"
37#include "mirror/field-inl.h"
38#include "mirror/abstract_method-inl.h"
39#include "mirror/object-inl.h"
40#include "mirror/object_array-inl.h"
41#include "mirror/throwable.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070042#include "scoped_thread_state_change.h"
43#include "ScopedLocalRef.h"
Ian Rogers50b35e22012-10-04 10:09:15 -070044#include "thread.h"
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070045#include "thread_pool.h"
Elliott Hughes601a1232012-02-02 17:47:38 -080046#include "timing_logger.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070047#include "verifier/method_verifier.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070048
Elliott Hughes059d5c12012-03-12 17:39:18 -070049#if defined(__APPLE__)
50#include <mach-o/dyld.h>
51#endif
52
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070053namespace art {
54
Ian Rogers996cc582012-02-14 22:23:29 -080055static double Percentage(size_t x, size_t y) {
Elliott Hughes398f64b2012-03-26 18:05:48 -070056 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
Ian Rogers996cc582012-02-14 22:23:29 -080057}
58
59static void DumpStat(size_t x, size_t y, const char* str) {
60 if (x == 0 && y == 0) {
61 return;
62 }
63 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
64}
65
Ian Rogersc8b306f2012-02-17 21:34:44 -080066class AOTCompilationStats {
67 public:
Ian Rogersca190662012-06-26 15:45:57 -070068 AOTCompilationStats()
69 : 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),
74 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0) {
Ian Rogers2ed3b952012-03-17 11:49:39 -070075 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
Ian Rogers50b35e22012-10-04 10:09:15 -0700122// Allow lossy statistics in non-debug builds.
Ian Rogers996cc582012-02-14 22:23:29 -0800123#ifndef NDEBUG
Ian Rogers50b35e22012-10-04 10:09:15 -0700124#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
Ian Rogers996cc582012-02-14 22:23:29 -0800125#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
buzbee8c4bbb52012-11-26 14:00:58 -0800242static std::string MakeCompilerSoName(CompilerBackend compiler_backend) {
Elliott Hughes059d5c12012-03-12 17:39:18 -0700243
244 // Bad things happen if we pull in the libartd-compiler to a libart dex2oat or vice versa,
245 // because we end up with both libart and libartd in the same address space!
Elliott Hughes67d92002012-03-26 15:08:51 -0700246 const char* suffix = (kIsDebugBuild ? "d" : "");
Elliott Hughes059d5c12012-03-12 17:39:18 -0700247
248 // Work out the filename for the compiler library.
buzbeec531cef2012-10-18 07:09:20 -0700249 std::string library_name;
250 if ((compiler_backend == kPortable) || (compiler_backend == kIceland)) {
251 library_name = StringPrintf("art%s-compiler-llvm", suffix);
252 } else {
buzbee8c4bbb52012-11-26 14:00:58 -0800253 library_name = StringPrintf("art%s-compiler", suffix);
buzbeec531cef2012-10-18 07:09:20 -0700254 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700255 std::string filename(StringPrintf(OS_SHARED_LIB_FORMAT_STR, library_name.c_str()));
256
257#if defined(__APPLE__)
258 // On Linux, dex2oat will have been built with an RPATH of $ORIGIN/../lib, so dlopen(3) will find
259 // the .so by itself. On Mac OS, there isn't really an equivalent, so we have to manually do the
260 // same work.
Elliott Hughes059d5c12012-03-12 17:39:18 -0700261 uint32_t executable_path_length = 0;
Elliott Hughes448e93c2012-03-28 22:30:06 -0700262 _NSGetExecutablePath(NULL, &executable_path_length);
263 std::string path(executable_path_length, static_cast<char>(0));
264 CHECK_EQ(_NSGetExecutablePath(&path[0], &executable_path_length), 0);
Elliott Hughes059d5c12012-03-12 17:39:18 -0700265
266 // Strip the "/dex2oat".
267 size_t last_slash = path.find_last_of('/');
268 CHECK_NE(last_slash, std::string::npos) << path;
269 path.resize(last_slash);
270
271 // Strip the "/bin".
272 last_slash = path.find_last_of('/');
273 path.resize(last_slash);
274
275 filename = path + "/lib/" + filename;
276#endif
277 return filename;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800278}
279
Elliott Hughes46f060a2012-03-09 17:36:50 -0800280template<typename Fn>
281static Fn FindFunction(const std::string& compiler_so_name, void* library, const char* name) {
282 Fn fn = reinterpret_cast<Fn>(dlsym(library, name));
283 if (fn == NULL) {
284 LOG(FATAL) << "Couldn't find \"" << name << "\" in compiler library " << compiler_so_name << ": " << dlerror();
285 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700286 VLOG(compiler) << "Found \"" << name << "\" at " << reinterpret_cast<void*>(fn);
Elliott Hughes46f060a2012-03-09 17:36:50 -0800287 return fn;
288}
289
buzbeec531cef2012-10-18 07:09:20 -0700290Compiler::Compiler(CompilerBackend compiler_backend, InstructionSet instruction_set, bool image,
291 size_t thread_count, bool support_debugging, const std::set<std::string>* image_classes,
Brian Carlstromba0668e2012-03-26 13:14:07 -0700292 bool dump_stats, bool dump_timings)
buzbeec531cef2012-10-18 07:09:20 -0700293 : compiler_backend_(compiler_backend),
294 instruction_set_(instruction_set),
Ian Rogersfffdb022013-01-04 15:14:08 -0800295 freezing_constructor_lock_("freezing constructor lock"),
Elliott Hughesc225caa2012-02-03 15:43:37 -0800296 compiled_classes_lock_("compiled classes lock"),
297 compiled_methods_lock_("compiled method lock"),
298 compiled_invoke_stubs_lock_("compiled invoke stubs lock"),
Logan Chien7a2a23a2012-06-06 11:01:00 +0800299 compiled_proxy_stubs_lock_("compiled proxy stubs lock"),
Brian Carlstromaded5f72011-10-07 17:15:04 -0700300 image_(image),
Elliott Hughes5523ee02012-02-03 18:18:34 -0800301 thread_count_(thread_count),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800302 support_debugging_(support_debugging),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700303 start_ns_(0),
Ian Rogersc8b306f2012-02-17 21:34:44 -0800304 stats_(new AOTCompilationStats),
Brian Carlstromba0668e2012-03-26 13:14:07 -0700305 dump_stats_(dump_stats),
306 dump_timings_(dump_timings),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800307 image_classes_(image_classes),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800308 compiler_library_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800309 compiler_(NULL),
Elliott Hughes6f4976c2012-03-13 21:19:01 -0700310 compiler_context_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800311 jni_compiler_(NULL),
Brian Carlstrom2f663822012-11-07 22:49:06 -0800312 create_invoke_stub_(NULL)
Logan Chien971bf3f2012-05-01 15:47:55 +0800313{
buzbee8c4bbb52012-11-26 14:00:58 -0800314 std::string compiler_so_name(MakeCompilerSoName(compiler_backend_));
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800315 compiler_library_ = dlopen(compiler_so_name.c_str(), RTLD_LAZY);
316 if (compiler_library_ == NULL) {
317 LOG(FATAL) << "Couldn't find compiler library " << compiler_so_name << ": " << dlerror();
318 }
319 VLOG(compiler) << "dlopen(\"" << compiler_so_name << "\", RTLD_LAZY) returned " << compiler_library_;
320
buzbee4df2bbd2012-10-11 14:46:06 -0700321 CHECK_PTHREAD_CALL(pthread_key_create, (&tls_key_, NULL), "compiler tls key");
322
buzbeec531cef2012-10-18 07:09:20 -0700323 // TODO: more work needed to combine initializations and allow per-method backend selection
Logan Chien106b2a02012-03-18 04:41:38 +0800324 typedef void (*InitCompilerContextFn)(Compiler&);
buzbeec531cef2012-10-18 07:09:20 -0700325 InitCompilerContextFn init_compiler_context;
326 if ((compiler_backend_ == kPortable) || (compiler_backend_ == kIceland)){
327 // Initialize compiler_context_
328 init_compiler_context = FindFunction<void (*)(Compiler&)>(compiler_so_name,
329 compiler_library_, "ArtInitCompilerContext");
330 compiler_ = FindFunction<CompilerFn>(compiler_so_name, compiler_library_, "ArtCompileMethod");
331 } else {
332 init_compiler_context = FindFunction<void (*)(Compiler&)>(compiler_so_name,
333 compiler_library_, "ArtInitQuickCompilerContext");
334 compiler_ = FindFunction<CompilerFn>(compiler_so_name, compiler_library_, "ArtQuickCompileMethod");
335 }
Logan Chien106b2a02012-03-18 04:41:38 +0800336
337 init_compiler_context(*this);
buzbee692be802012-08-29 15:52:59 -0700338
Elliott Hughes46f060a2012-03-09 17:36:50 -0800339 jni_compiler_ = FindFunction<JniCompilerFn>(compiler_so_name, compiler_library_, "ArtJniCompileMethod");
buzbee02031b12012-11-23 09:41:35 -0800340 if ((compiler_backend_ == kPortable) || (compiler_backend_ == kIceland)){
341 create_invoke_stub_ =
342 FindFunction<CreateInvokeStubFn>(compiler_so_name, compiler_library_, "ArtCreateLLVMInvokeStub");
343 } else {
344 switch (instruction_set) {
345 case kArm:
346 case kThumb2:
347 create_invoke_stub_ =
348 FindFunction<CreateInvokeStubFn>(compiler_so_name, compiler_library_, "ArtCreateArmInvokeStub");
349 break;
350 case kMips:
351 create_invoke_stub_ =
352 FindFunction<CreateInvokeStubFn>(compiler_so_name, compiler_library_, "ArtCreateMipsInvokeStub");
353 break;
354 case kX86:
355 create_invoke_stub_ =
356 FindFunction<CreateInvokeStubFn>(compiler_so_name, compiler_library_, "ArtCreateX86InvokeStub");
357 break;
358 default:
359 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
360 }
361 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800362
buzbeec531cef2012-10-18 07:09:20 -0700363 if ((compiler_backend_ == kPortable) || (compiler_backend_ == kIceland)) {
364 create_proxy_stub_ = FindFunction<CreateProxyStubFn>(
365 compiler_so_name, compiler_library_, "ArtCreateProxyStub");
366 }
Logan Chienf7015fd2012-03-18 01:19:37 +0800367
Brian Carlstrom25c33252011-09-18 15:58:35 -0700368 CHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800369 if (!image_) {
370 CHECK(image_classes_ == NULL);
371 }
Shih-wei Liaoc486c112011-09-13 16:43:52 -0700372}
373
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700374Compiler::~Compiler() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700375 Thread* self = Thread::Current();
Elliott Hughesc225caa2012-02-03 15:43:37 -0800376 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700377 MutexLock mu(self, compiled_classes_lock_);
Elliott Hughesc225caa2012-02-03 15:43:37 -0800378 STLDeleteValues(&compiled_classes_);
379 }
380 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700381 MutexLock mu(self, compiled_methods_lock_);
Elliott Hughesc225caa2012-02-03 15:43:37 -0800382 STLDeleteValues(&compiled_methods_);
383 }
384 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700385 MutexLock mu(self, compiled_invoke_stubs_lock_);
Elliott Hughesc225caa2012-02-03 15:43:37 -0800386 STLDeleteValues(&compiled_invoke_stubs_);
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800387 }
Brian Carlstromf5822582012-03-19 22:34:31 -0700388 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700389 MutexLock mu(self, compiled_proxy_stubs_lock_);
Logan Chien7a2a23a2012-06-06 11:01:00 +0800390 STLDeleteValues(&compiled_proxy_stubs_);
391 }
392 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700393 MutexLock mu(self, compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700394 STLDeleteElements(&code_to_patch_);
395 }
396 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700397 MutexLock mu(self, compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700398 STLDeleteElements(&methods_to_patch_);
399 }
Mathieu Chartiered6d5ed2012-10-12 14:51:46 -0700400 CHECK_PTHREAD_CALL(pthread_key_delete, (tls_key_), "delete tls key");
Logan Chien971bf3f2012-05-01 15:47:55 +0800401 typedef void (*UninitCompilerContextFn)(Compiler&);
buzbee8c4bbb52012-11-26 14:00:58 -0800402 std::string compiler_so_name(MakeCompilerSoName(compiler_backend_));
buzbeec531cef2012-10-18 07:09:20 -0700403 UninitCompilerContextFn uninit_compiler_context;
buzbee692be802012-08-29 15:52:59 -0700404 // Uninitialize compiler_context_
buzbeec531cef2012-10-18 07:09:20 -0700405 // TODO: rework to combine initialization/uninitialization
406 if ((compiler_backend_ == kPortable) || (compiler_backend_ == kIceland)) {
407 uninit_compiler_context = FindFunction<void (*)(Compiler&)>(compiler_so_name,
408 compiler_library_, "ArtUnInitCompilerContext");
409 } else {
410 uninit_compiler_context = FindFunction<void (*)(Compiler&)>(compiler_so_name,
411 compiler_library_, "ArtUnInitQuickCompilerContext");
412 }
buzbee692be802012-08-29 15:52:59 -0700413 uninit_compiler_context(*this);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800414 if (compiler_library_ != NULL) {
415 VLOG(compiler) << "dlclose(" << compiler_library_ << ")";
buzbeeca7a5e42012-08-20 11:12:18 -0700416 /*
417 * FIXME: Temporary workaround
418 * Apparently, llvm is adding dctors to atexit, but if we unload
419 * the library here the code will no longer be around at exit time
420 * and we die a flaming death in __cxa_finalize(). Apparently, some
421 * dlclose() implementations will scan the atexit list on unload and
422 * handle any associated with the soon-to-be-unloaded library.
423 * However, this is not required by POSIX and we don't do it.
424 * See: http://b/issue?id=4998315
425 * What's the right thing to do here?
426 */
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800427 dlclose(compiler_library_);
428 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700429}
430
buzbee4df2bbd2012-10-11 14:46:06 -0700431CompilerTls* Compiler::GetTls() {
432 // Lazily create thread-local storage
433 CompilerTls* res = static_cast<CompilerTls*>(pthread_getspecific(tls_key_));
434 if (res == NULL) {
435 res = new CompilerTls();
436 CHECK_PTHREAD_CALL(pthread_setspecific, (tls_key_, res), "compiler tls");
437 }
438 return res;
439}
440
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800441mirror::ByteArray* Compiler::CreateResolutionStub(InstructionSet instruction_set,
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700442 Runtime::TrampolineType type) {
jeffhao7fbee072012-08-24 17:56:54 -0700443 switch (instruction_set) {
444 case kArm:
445 case kThumb2:
446 return arm::ArmCreateResolutionTrampoline(type);
447 case kMips:
448 return mips::MipsCreateResolutionTrampoline(type);
449 case kX86:
450 return x86::X86CreateResolutionTrampoline(type);
451 default:
452 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
453 return NULL;
Ian Rogersad25ac52011-10-04 19:13:33 -0700454 }
455}
456
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800457mirror::ByteArray* Compiler::CreateJniDlsymLookupStub(InstructionSet instruction_set) {
Ian Rogers169c9a72011-11-13 20:13:17 -0800458 switch (instruction_set) {
459 case kArm:
460 case kThumb2:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800461 return arm::CreateJniDlsymLookupStub();
jeffhao7fbee072012-08-24 17:56:54 -0700462 case kMips:
463 return mips::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800464 case kX86:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800465 return x86::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800466 default:
Ian Rogers49c48942012-03-11 15:15:37 -0700467 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
Ian Rogers169c9a72011-11-13 20:13:17 -0800468 return NULL;
469 }
470}
471
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800472mirror::ByteArray* Compiler::CreateAbstractMethodErrorStub(InstructionSet instruction_set) {
jeffhao7fbee072012-08-24 17:56:54 -0700473 switch (instruction_set) {
474 case kArm:
475 case kThumb2:
476 return arm::CreateAbstractMethodErrorStub();
477 case kMips:
478 return mips::CreateAbstractMethodErrorStub();
479 case kX86:
480 return x86::CreateAbstractMethodErrorStub();
481 default:
482 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
483 return NULL;
Ian Rogersad25ac52011-10-04 19:13:33 -0700484 }
485}
486
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700487void Compiler::CompileAll(jobject class_loader,
Brian Carlstromae826982011-11-09 01:33:42 -0800488 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700489 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800490
Ian Rogers56edc432013-01-18 16:51:51 -0800491 UniquePtr<ThreadPool> thread_pool(new ThreadPool(thread_count_));
Elliott Hughes601a1232012-02-02 17:47:38 -0800492 TimingLogger timings("compiler");
493
Ian Rogers56edc432013-01-18 16:51:51 -0800494 PreCompile(class_loader, dex_files, *thread_pool.get(), timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800495
Ian Rogers56edc432013-01-18 16:51:51 -0800496 Compile(class_loader, dex_files, *thread_pool.get(), timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800497
Brian Carlstromba0668e2012-03-26 13:14:07 -0700498 if (dump_timings_ && timings.GetTotalNs() > MsToNs(1000)) {
Elliott Hughes601a1232012-02-02 17:47:38 -0800499 timings.Dump();
500 }
Ian Rogers996cc582012-02-14 22:23:29 -0800501
Brian Carlstromba0668e2012-03-26 13:14:07 -0700502 if (dump_stats_) {
503 stats_->Dump();
504 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700505}
506
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800507void Compiler::CompileOne(const mirror::AbstractMethod* method) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700508 DCHECK(!Runtime::Current()->IsStarted());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700509 Thread* self = Thread::Current();
510 jobject class_loader;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700511 const DexFile* dex_file;
Ian Rogersfffdb022013-01-04 15:14:08 -0800512 uint32_t class_def_idx;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700513 {
514 ScopedObjectAccessUnchecked soa(self);
515 ScopedLocalRef<jobject>
516 local_class_loader(soa.Env(),
517 soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
518 class_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
519 // Find the dex_file
Ian Rogersfffdb022013-01-04 15:14:08 -0800520 MethodHelper mh(method);
521 dex_file = &mh.GetDexFile();
522 class_def_idx = mh.GetClassDefIndex();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700523 }
524 self->TransitionFromRunnableToSuspended(kNative);
Brian Carlstromae826982011-11-09 01:33:42 -0800525
Brian Carlstromae826982011-11-09 01:33:42 -0800526 std::vector<const DexFile*> dex_files;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700527 dex_files.push_back(dex_file);
Brian Carlstromae826982011-11-09 01:33:42 -0800528
Ian Rogers56edc432013-01-18 16:51:51 -0800529 UniquePtr<ThreadPool> thread_pool(new ThreadPool(1U));
Elliott Hughes601a1232012-02-02 17:47:38 -0800530 TimingLogger timings("CompileOne");
Ian Rogers56edc432013-01-18 16:51:51 -0800531 PreCompile(class_loader, dex_files, *thread_pool.get(), timings);
Brian Carlstromae826982011-11-09 01:33:42 -0800532
Ian Rogers0571d352011-11-03 19:51:38 -0700533 uint32_t method_idx = method->GetDexMethodIndex();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700534 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Ian Rogers08f753d2012-08-24 14:35:25 -0700535 CompileMethod(code_item, method->GetAccessFlags(), method->GetInvokeType(),
Ian Rogersfffdb022013-01-04 15:14:08 -0800536 class_def_idx, method_idx, class_loader, *dex_file);
Brian Carlstromae826982011-11-09 01:33:42 -0800537
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700538 self->GetJniEnv()->DeleteGlobalRef(class_loader);
539
540 self->TransitionFromSuspendedToRunnable();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700541}
542
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700543void Compiler::Resolve(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Brian Carlstrom2f663822012-11-07 22:49:06 -0800544 ThreadPool& thread_pool, TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -0800545 for (size_t i = 0; i != dex_files.size(); ++i) {
546 const DexFile* dex_file = dex_files[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700547 CHECK(dex_file != NULL);
Brian Carlstrom2f663822012-11-07 22:49:06 -0800548 ResolveDexFile(class_loader, *dex_file, thread_pool, timings);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700549 }
550}
551
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700552void Compiler::PreCompile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Brian Carlstrom2f663822012-11-07 22:49:06 -0800553 ThreadPool& thread_pool, TimingLogger& timings) {
554 Resolve(class_loader, dex_files, thread_pool, timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800555
Brian Carlstrom2f663822012-11-07 22:49:06 -0800556 Verify(class_loader, dex_files, thread_pool, timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800557
Brian Carlstrom2f663822012-11-07 22:49:06 -0800558 InitializeClasses(class_loader, dex_files, thread_pool, timings);
Brian Carlstromae826982011-11-09 01:33:42 -0800559}
560
561bool Compiler::IsImageClass(const std::string& descriptor) const {
562 if (image_classes_ == NULL) {
563 return true;
564 }
565 return image_classes_->find(descriptor) != image_classes_->end();
566}
567
Ian Rogers3d1548d2012-09-24 14:08:03 -0700568void Compiler::RecordClassStatus(ClassReference ref, CompiledClass* compiled_class) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700569 MutexLock mu(Thread::Current(), Compiler::compiled_classes_lock_);
Ian Rogers3d1548d2012-09-24 14:08:03 -0700570 compiled_classes_.Put(ref, compiled_class);
571}
572
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700573bool Compiler::CanAssumeTypeIsPresentInDexCache(const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800574 uint32_t type_idx) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700575 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800576 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800577 if (!IsImage()) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800578 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800579 return false;
580 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800581 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800582 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800583 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800584 return false;
585 }
Ian Rogers996cc582012-02-14 22:23:29 -0800586 bool result = IsImageClass(ClassHelper(resolved_class).GetDescriptor());
587 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800588 stats_->TypeInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800589 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800590 stats_->TypeNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800591 }
592 return result;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800593}
594
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700595bool Compiler::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800596 uint32_t string_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800597 // See also Compiler::ResolveDexFile
598
Ian Rogers5f7fa552012-11-02 11:45:53 -0700599 bool result = false;
600 if (IsImage()) {
601 // We resolve all const-string strings when building for the image.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700602 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800603 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
Ian Rogers5f7fa552012-11-02 11:45:53 -0700604 Runtime::Current()->GetClassLinker()->ResolveString(dex_file, string_idx, dex_cache);
605 result = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700606 }
Ian Rogers996cc582012-02-14 22:23:29 -0800607 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800608 stats_->StringInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800609 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800610 stats_->StringNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800611 }
612 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800613}
614
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700615bool Compiler::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
616 uint32_t type_idx) {
617 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800618 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
Ian Rogers1bddec32012-02-04 12:27:34 -0800619 // Get type from dex cache assuming it was populated by the verifier
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800620 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800621 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800622 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800623 return false; // Unknown class needs access checks.
624 }
625 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800626 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
Ian Rogers1bddec32012-02-04 12:27:34 -0800627 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800628 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800629 return false; // Incomplete referrer knowledge needs access check.
630 }
631 // Perform access check, will return true if access is ok or false if we're going to have to
632 // check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800633 bool result = referrer_class->CanAccess(resolved_class);
634 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800635 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800636 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800637 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800638 }
639 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800640}
641
642bool Compiler::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
Ian Rogers1bddec32012-02-04 12:27:34 -0800643 const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800644 uint32_t type_idx) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700645 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800646 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
Ian Rogers1bddec32012-02-04 12:27:34 -0800647 // Get type from dex cache assuming it was populated by the verifier.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800648 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800649 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800650 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800651 return false; // Unknown class needs access checks.
652 }
653 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800654 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
Ian Rogers1bddec32012-02-04 12:27:34 -0800655 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800656 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800657 return false; // Incomplete referrer knowledge needs access check.
658 }
659 // Perform access and instantiable checks, will return true if access is ok or false if we're
660 // going to have to check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800661 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
662 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800663 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800664 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800665 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800666 }
667 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800668}
669
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800670static mirror::Class* ComputeCompilingMethodsClass(ScopedObjectAccess& soa,
671 OatCompilationUnit* mUnit)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700672 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800673 mirror::DexCache* dex_cache = mUnit->class_linker_->FindDexCache(*mUnit->dex_file_);
674 mirror::ClassLoader* class_loader = soa.Decode<mirror::ClassLoader*>(mUnit->class_loader_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700675 const DexFile::MethodId& referrer_method_id = mUnit->dex_file_->GetMethodId(mUnit->method_idx_);
676 return mUnit->class_linker_->ResolveType(*mUnit->dex_file_, referrer_method_id.class_idx_,
677 dex_cache, class_loader);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800678}
679
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800680static mirror::Field* ComputeFieldReferencedFromCompilingMethod(ScopedObjectAccess& soa,
681 OatCompilationUnit* mUnit,
682 uint32_t field_idx)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700683 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800684 mirror::DexCache* dex_cache = mUnit->class_linker_->FindDexCache(*mUnit->dex_file_);
685 mirror::ClassLoader* class_loader = soa.Decode<mirror::ClassLoader*>(mUnit->class_loader_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700686 return mUnit->class_linker_->ResolveField(*mUnit->dex_file_, field_idx, dex_cache,
687 class_loader, false);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800688}
689
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800690static mirror::AbstractMethod* ComputeMethodReferencedFromCompilingMethod(ScopedObjectAccess& soa,
691 OatCompilationUnit* mUnit,
692 uint32_t method_idx,
693 InvokeType type)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700694 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800695 mirror::DexCache* dex_cache = mUnit->class_linker_->FindDexCache(*mUnit->dex_file_);
696 mirror::ClassLoader* class_loader = soa.Decode<mirror::ClassLoader*>(mUnit->class_loader_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700697 return mUnit->class_linker_->ResolveMethod(*mUnit->dex_file_, method_idx, dex_cache,
jeffhaoc0228b82012-08-29 18:15:05 -0700698 class_loader, NULL, type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800699}
700
Logan Chien4dd96f52012-02-29 01:26:58 +0800701bool Compiler::ComputeInstanceFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
jeffhao8cd6dda2012-02-22 10:15:34 -0800702 int& field_offset, bool& is_volatile, bool is_put) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700703 ScopedObjectAccess soa(Thread::Current());
Ian Rogers08f753d2012-08-24 14:35:25 -0700704 // Conservative defaults.
Ian Rogers1bddec32012-02-04 12:27:34 -0800705 field_offset = -1;
706 is_volatile = true;
Ian Rogers08f753d2012-08-24 14:35:25 -0700707 // Try to resolve field and ignore if an Incompatible Class Change Error (ie is static).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800708 mirror::Field* resolved_field = ComputeFieldReferencedFromCompilingMethod(soa, mUnit, field_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -0700709 if (resolved_field != NULL && !resolved_field->IsStatic()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800710 mirror::Class* referrer_class = ComputeCompilingMethodsClass(soa, mUnit);
Ian Rogerse2645d32012-04-11 14:42:42 -0700711 if (referrer_class != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800712 mirror::Class* fields_class = resolved_field->GetDeclaringClass();
Ian Rogerse2645d32012-04-11 14:42:42 -0700713 bool access_ok = referrer_class->CanAccess(fields_class) &&
714 referrer_class->CanAccessMember(fields_class,
715 resolved_field->GetAccessFlags());
716 if (!access_ok) {
717 // The referring class can't access the resolved field, this may occur as a result of a
718 // protected field being made public by a sub-class. Resort to the dex file to determine
719 // the correct class for the access check.
Ian Rogers4445a7e2012-10-05 17:19:13 -0700720 const DexFile& dex_file = *referrer_class->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800721 mirror::Class* dex_fields_class = mUnit->class_linker_->ResolveType(dex_file,
Ian Rogerse2645d32012-04-11 14:42:42 -0700722 dex_file.GetFieldId(field_idx).class_idx_,
723 referrer_class);
724 access_ok = referrer_class->CanAccess(dex_fields_class) &&
725 referrer_class->CanAccessMember(dex_fields_class,
726 resolved_field->GetAccessFlags());
727 }
728 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal() &&
729 fields_class != referrer_class;
730 if (access_ok && !is_write_to_final_from_wrong_class) {
731 field_offset = resolved_field->GetOffset().Int32Value();
732 is_volatile = resolved_field->IsVolatile();
733 stats_->ResolvedInstanceField();
734 return true; // Fast path.
735 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800736 }
737 }
738 // Clean up any exception left by field/type resolution
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700739 if (soa.Self()->IsExceptionPending()) {
740 soa.Self()->ClearException();
Ian Rogers1bddec32012-02-04 12:27:34 -0800741 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800742 stats_->UnresolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800743 return false; // Incomplete knowledge needs slow path.
744}
745
Logan Chien4dd96f52012-02-29 01:26:58 +0800746bool Compiler::ComputeStaticFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
Ian Rogers1bddec32012-02-04 12:27:34 -0800747 int& field_offset, int& ssb_index,
jeffhao8cd6dda2012-02-22 10:15:34 -0800748 bool& is_referrers_class, bool& is_volatile, bool is_put) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700749 ScopedObjectAccess soa(Thread::Current());
Ian Rogers08f753d2012-08-24 14:35:25 -0700750 // Conservative defaults.
Ian Rogers1bddec32012-02-04 12:27:34 -0800751 field_offset = -1;
752 ssb_index = -1;
753 is_referrers_class = false;
754 is_volatile = true;
Ian Rogers08f753d2012-08-24 14:35:25 -0700755 // Try to resolve field and ignore if an Incompatible Class Change Error (ie isn't static).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800756 mirror::Field* resolved_field = ComputeFieldReferencedFromCompilingMethod(soa, mUnit, field_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -0700757 if (resolved_field != NULL && resolved_field->IsStatic()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800758 mirror::Class* referrer_class = ComputeCompilingMethodsClass(soa, mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800759 if (referrer_class != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800760 mirror::Class* fields_class = resolved_field->GetDeclaringClass();
jeffhao8cd6dda2012-02-22 10:15:34 -0800761 if (fields_class == referrer_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800762 is_referrers_class = true; // implies no worrying about class initialization
763 field_offset = resolved_field->GetOffset().Int32Value();
764 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800765 stats_->ResolvedLocalStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800766 return true; // fast path
767 } else {
Ian Rogerse2645d32012-04-11 14:42:42 -0700768 bool access_ok = referrer_class->CanAccess(fields_class) &&
769 referrer_class->CanAccessMember(fields_class,
770 resolved_field->GetAccessFlags());
771 if (!access_ok) {
772 // The referring class can't access the resolved field, this may occur as a result of a
773 // protected field being made public by a sub-class. Resort to the dex file to determine
774 // the correct class for the access check. Don't change the field's class as that is
775 // used to identify the SSB.
Ian Rogers4445a7e2012-10-05 17:19:13 -0700776 const DexFile& dex_file = *referrer_class->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800777 mirror::Class* dex_fields_class =
Ian Rogerse2645d32012-04-11 14:42:42 -0700778 mUnit->class_linker_->ResolveType(dex_file,
779 dex_file.GetFieldId(field_idx).class_idx_,
780 referrer_class);
781 access_ok = referrer_class->CanAccess(dex_fields_class) &&
782 referrer_class->CanAccessMember(dex_fields_class,
783 resolved_field->GetAccessFlags());
784 }
jeffhao8cd6dda2012-02-22 10:15:34 -0800785 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal();
Ian Rogerse2645d32012-04-11 14:42:42 -0700786 if (access_ok && !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800787 // We have the resolved field, we must make it into a ssbIndex for the referrer
788 // in its static storage base (which may fail if it doesn't have a slot for it)
Ian Rogers4103ad22012-02-06 09:18:25 -0800789 // TODO: for images we can elide the static storage base null check
790 // if we know there's a non-null entry in the image
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800791 mirror::DexCache* dex_cache = mUnit->class_linker_->FindDexCache(*mUnit->dex_file_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700792 if (fields_class->GetDexCache() == dex_cache) {
Ian Rogers4103ad22012-02-06 09:18:25 -0800793 // common case where the dex cache of both the referrer and the field are the same,
794 // no need to search the dex file
795 ssb_index = fields_class->GetDexTypeIndex();
796 field_offset = resolved_field->GetOffset().Int32Value();
797 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800798 stats_->ResolvedStaticField();
Ian Rogers4103ad22012-02-06 09:18:25 -0800799 return true;
800 }
Ian Rogerse2645d32012-04-11 14:42:42 -0700801 // Search dex file for localized ssb index, may fail if field's class is a parent
802 // of the class mentioned in the dex file and there is no dex cache entry.
Ian Rogers1bddec32012-02-04 12:27:34 -0800803 std::string descriptor(FieldHelper(resolved_field).GetDeclaringClassDescriptor());
804 const DexFile::StringId* string_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800805 mUnit->dex_file_->FindStringId(descriptor);
Ian Rogers1bddec32012-02-04 12:27:34 -0800806 if (string_id != NULL) {
807 const DexFile::TypeId* type_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800808 mUnit->dex_file_->FindTypeId(mUnit->dex_file_->GetIndexForStringId(*string_id));
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700809 if (type_id != NULL) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800810 // medium path, needs check of static storage base being initialized
Logan Chien4dd96f52012-02-29 01:26:58 +0800811 ssb_index = mUnit->dex_file_->GetIndexForTypeId(*type_id);
Ian Rogers1bddec32012-02-04 12:27:34 -0800812 field_offset = resolved_field->GetOffset().Int32Value();
813 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800814 stats_->ResolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800815 return true;
816 }
817 }
818 }
819 }
820 }
821 }
822 // Clean up any exception left by field/type resolution
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700823 if (soa.Self()->IsExceptionPending()) {
824 soa.Self()->ClearException();
Ian Rogers1bddec32012-02-04 12:27:34 -0800825 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800826 stats_->UnresolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800827 return false; // Incomplete knowledge needs slow path.
828}
829
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800830void Compiler::GetCodeAndMethodForDirectCall(InvokeType type, InvokeType sharp_type,
831 mirror::AbstractMethod* method,
Ian Rogers2ed3b952012-03-17 11:49:39 -0700832 uintptr_t& direct_code, uintptr_t& direct_method) {
Ian Rogers137e88f2012-10-08 17:46:47 -0700833 // For direct and static methods compute possible direct_code and direct_method values, ie
834 // an address for the Method* being invoked and an address of the code for that Method*.
835 // For interface calls compute a value for direct_method that is the interface method being
836 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers2ed3b952012-03-17 11:49:39 -0700837 direct_code = 0;
838 direct_method = 0;
buzbeec531cef2012-10-18 07:09:20 -0700839 if ((compiler_backend_ == kPortable) || (compiler_backend_ == kIceland)) {
840 if (sharp_type != kStatic && sharp_type != kDirect) {
841 return;
842 }
843 } else {
844 if (sharp_type != kStatic && sharp_type != kDirect && sharp_type != kInterface) {
845 return;
846 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700847 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700848 bool method_code_in_boot = method->GetDeclaringClass()->GetClassLoader() == NULL;
849 if (!method_code_in_boot) {
850 return;
851 }
852 bool has_clinit_trampoline = method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
853 if (has_clinit_trampoline) {
854 return;
855 }
Ian Rogersc468e922012-10-10 18:11:33 -0700856 if (sharp_type != kInterface) { // Interfaces always go via a trampoline.
857 stats_->DirectCallsToBoot(type);
858 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700859 stats_->DirectMethodsToBoot(type);
Ian Rogers3fa13792012-03-18 15:53:45 -0700860 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
861 if (compiling_boot) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700862 const bool kSupportBootImageFixup = true;
Ian Rogers3fa13792012-03-18 15:53:45 -0700863 if (kSupportBootImageFixup) {
864 MethodHelper mh(method);
865 if (IsImageClass(mh.GetDeclaringClassDescriptor())) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700866 // We can only branch directly to Methods that are resolved in the DexCache.
867 // Otherwise we won't invoke the resolution trampoline.
Ian Rogers3fa13792012-03-18 15:53:45 -0700868 direct_method = -1;
Brian Carlstrom0637e272012-03-20 01:07:52 -0700869 direct_code = -1;
Ian Rogers3fa13792012-03-18 15:53:45 -0700870 }
Ian Rogers3fa13792012-03-18 15:53:45 -0700871 }
872 } else {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700873 if (Runtime::Current()->GetHeap()->FindSpaceFromObject(method)->IsImageSpace()) {
Ian Rogers3fa13792012-03-18 15:53:45 -0700874 direct_method = reinterpret_cast<uintptr_t>(method);
875 }
876 direct_code = reinterpret_cast<uintptr_t>(method->GetCode());
Ian Rogers2ed3b952012-03-17 11:49:39 -0700877 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700878}
879
Ian Rogersfb6adba2012-03-04 21:51:51 -0800880bool Compiler::ComputeInvokeInfo(uint32_t method_idx, OatCompilationUnit* mUnit, InvokeType& type,
Ian Rogers2ed3b952012-03-17 11:49:39 -0700881 int& vtable_idx, uintptr_t& direct_code,
882 uintptr_t& direct_method) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700883 ScopedObjectAccess soa(Thread::Current());
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800884 vtable_idx = -1;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700885 direct_code = 0;
886 direct_method = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800887 mirror::AbstractMethod* resolved_method =
Ian Rogers08f753d2012-08-24 14:35:25 -0700888 ComputeMethodReferencedFromCompilingMethod(soa, mUnit, method_idx, type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800889 if (resolved_method != NULL) {
Ian Rogers08f753d2012-08-24 14:35:25 -0700890 // Don't try to fast-path if we don't understand the caller's class or this appears to be an
891 // Incompatible Class Change Error.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800892 mirror::Class* referrer_class = ComputeCompilingMethodsClass(soa, mUnit);
Ian Rogers08f753d2012-08-24 14:35:25 -0700893 bool icce = resolved_method->CheckIncompatibleClassChange(type);
894 if (referrer_class != NULL && !icce) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800895 mirror::Class* methods_class = resolved_method->GetDeclaringClass();
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800896 if (!referrer_class->CanAccess(methods_class) ||
897 !referrer_class->CanAccessMember(methods_class,
Ian Rogers996cc582012-02-14 22:23:29 -0800898 resolved_method->GetAccessFlags())) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800899 // The referring class can't access the resolved method, this may occur as a result of a
900 // protected method being made public by implementing an interface that re-declares the
Ian Rogers08f753d2012-08-24 14:35:25 -0700901 // method public. Resort to the dex file to determine the correct class for the access
902 // check.
Ian Rogers4445a7e2012-10-05 17:19:13 -0700903 const DexFile& dex_file = *referrer_class->GetDexCache()->GetDexFile();
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800904 methods_class =
Logan Chien4dd96f52012-02-29 01:26:58 +0800905 mUnit->class_linker_->ResolveType(dex_file,
906 dex_file.GetMethodId(method_idx).class_idx_,
907 referrer_class);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800908 }
909 if (referrer_class->CanAccess(methods_class) &&
Ian Rogers137e88f2012-10-08 17:46:47 -0700910 referrer_class->CanAccessMember(methods_class, resolved_method->GetAccessFlags())) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800911 vtable_idx = resolved_method->GetMethodIndex();
Ian Rogersf320b632012-03-13 18:47:47 -0700912 const bool kEnableSharpening = true;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700913 // Sharpen a virtual call into a direct call when the target is known.
914 bool can_sharpen = type == kVirtual && (resolved_method->IsFinal() ||
Ian Rogers08f753d2012-08-24 14:35:25 -0700915 methods_class->IsFinal());
916 // Ensure the vtable index will be correct to dispatch in the vtable of the super class.
jeffhao4155fcd2012-03-21 11:42:12 -0700917 can_sharpen = can_sharpen || (type == kSuper && referrer_class != methods_class &&
Ian Rogers08f753d2012-08-24 14:35:25 -0700918 referrer_class->IsSubClass(methods_class) &&
919 vtable_idx < methods_class->GetVTable()->GetLength() &&
920 methods_class->GetVTable()->Get(vtable_idx) == resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700921 if (kEnableSharpening && can_sharpen) {
922 stats_->ResolvedMethod(type);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800923 // Sharpen a virtual call into a direct call. The method_idx is into referrer's
924 // dex cache, check that this resolved method is where we expect it.
925 CHECK(referrer_class->GetDexCache()->GetResolvedMethod(method_idx) == resolved_method)
Ian Rogers08f753d2012-08-24 14:35:25 -0700926 << PrettyMethod(resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700927 stats_->VirtualMadeDirect(type);
928 GetCodeAndMethodForDirectCall(type, kDirect, resolved_method, direct_code, direct_method);
929 type = kDirect;
930 return true;
931 } else if (type == kSuper) {
Ian Rogers08f753d2012-08-24 14:35:25 -0700932 // Unsharpened super calls are suspicious so go slow-path.
Ian Rogers2ed3b952012-03-17 11:49:39 -0700933 } else {
934 stats_->ResolvedMethod(type);
935 GetCodeAndMethodForDirectCall(type, type, resolved_method, direct_code, direct_method);
936 return true;
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800937 }
938 }
939 }
940 }
941 // Clean up any exception left by method/type resolution
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700942 if (soa.Self()->IsExceptionPending()) {
943 soa.Self()->ClearException();
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800944 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800945 stats_->UnresolvedMethod(type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800946 return false; // Incomplete knowledge needs slow path.
947}
948
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700949void Compiler::AddCodePatch(const DexFile* dex_file,
Brian Carlstromf5822582012-03-19 22:34:31 -0700950 uint32_t referrer_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700951 InvokeType referrer_invoke_type,
Brian Carlstromf5822582012-03-19 22:34:31 -0700952 uint32_t target_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700953 InvokeType target_invoke_type,
Ian Rogers3fa13792012-03-18 15:53:45 -0700954 size_t literal_offset) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700955 MutexLock mu(Thread::Current(), compiled_methods_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700956 code_to_patch_.push_back(new PatchInformation(dex_file,
Brian Carlstromf5822582012-03-19 22:34:31 -0700957 referrer_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700958 referrer_invoke_type,
Brian Carlstromf5822582012-03-19 22:34:31 -0700959 target_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700960 target_invoke_type,
Brian Carlstromf5822582012-03-19 22:34:31 -0700961 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700962}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700963void Compiler::AddMethodPatch(const DexFile* dex_file,
Brian Carlstromf5822582012-03-19 22:34:31 -0700964 uint32_t referrer_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700965 InvokeType referrer_invoke_type,
Brian Carlstromf5822582012-03-19 22:34:31 -0700966 uint32_t target_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700967 InvokeType target_invoke_type,
Ian Rogers3fa13792012-03-18 15:53:45 -0700968 size_t literal_offset) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700969 MutexLock mu(Thread::Current(), compiled_methods_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700970 methods_to_patch_.push_back(new PatchInformation(dex_file,
Brian Carlstromf5822582012-03-19 22:34:31 -0700971 referrer_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700972 referrer_invoke_type,
Brian Carlstromf5822582012-03-19 22:34:31 -0700973 target_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700974 target_invoke_type,
Brian Carlstromf5822582012-03-19 22:34:31 -0700975 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700976}
977
Ian Rogers0399dde2012-06-06 17:09:28 -0700978class CompilationContext {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800979 public:
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700980 typedef void Callback(const CompilationContext* context, size_t index);
981
Ian Rogers0399dde2012-06-06 17:09:28 -0700982 CompilationContext(ClassLinker* class_linker,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700983 jobject class_loader,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800984 Compiler* compiler,
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700985 const DexFile* dex_file,
Brian Carlstrom2f663822012-11-07 22:49:06 -0800986 ThreadPool& thread_pool)
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800987 : class_linker_(class_linker),
988 class_loader_(class_loader),
989 compiler_(compiler),
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700990 dex_file_(dex_file),
Brian Carlstrom2f663822012-11-07 22:49:06 -0800991 thread_pool_(&thread_pool) {}
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800992
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700993 ClassLinker* GetClassLinker() const {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800994 CHECK(class_linker_ != NULL);
995 return class_linker_;
996 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700997
998 jobject GetClassLoader() const {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800999 return class_loader_;
1000 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001001
1002 Compiler* GetCompiler() const {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001003 CHECK(compiler_ != NULL);
1004 return compiler_;
1005 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001006
1007 const DexFile* GetDexFile() const {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001008 CHECK(dex_file_ != NULL);
1009 return dex_file_;
1010 }
1011
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001012 void ForAll(size_t begin, size_t end, Callback callback, size_t work_units) {
1013 Thread* self = Thread::Current();
1014 self->AssertNoPendingException();
1015 CHECK_GT(work_units, 0U);
1016
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001017 std::vector<ForAllClosure*> closures(work_units);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001018 for (size_t i = 0; i < work_units; ++i) {
1019 closures[i] = new ForAllClosure(this, begin + i, end, callback, work_units);
1020 thread_pool_->AddTask(self, closures[i]);
1021 }
1022 thread_pool_->StartWorkers(self);
1023
1024 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1025 // thread destructor's called below perform join).
1026 CHECK_NE(self->GetState(), kRunnable);
1027
1028 // Wait for all the worker threads to finish.
1029 thread_pool_->Wait(self);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001030 }
1031
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001032 private:
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001033
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001034 class ForAllClosure : public Task {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001035 public:
1036 ForAllClosure(CompilationContext* context, size_t begin, size_t end, Callback* callback,
1037 size_t stripe)
1038 : context_(context),
1039 begin_(begin),
1040 end_(end),
1041 callback_(callback),
1042 stripe_(stripe)
1043 {
1044
1045 }
1046
1047 virtual void Run(Thread* self) {
1048 for (size_t i = begin_; i < end_; i += stripe_) {
1049 callback_(context_, i);
1050 self->AssertNoPendingException();
1051 }
1052 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001053
1054 virtual void Finalize() {
1055 delete this;
1056 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001057 private:
1058 CompilationContext* const context_;
1059 const size_t begin_;
1060 const size_t end_;
1061 const Callback* callback_;
1062 const size_t stripe_;
1063 };
1064
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001065 ClassLinker* const class_linker_;
1066 const jobject class_loader_;
1067 Compiler* const compiler_;
1068 const DexFile* const dex_file_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001069 ThreadPool* thread_pool_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001070};
1071
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001072// Return true if the class should be skipped during compilation. We
1073// never skip classes in the boot class loader. However, if we have a
1074// non-boot class loader and we can resolve the class in the boot
1075// class loader, we do skip the class. This happens if an app bundles
1076// classes found in the boot classpath. Since at runtime we will
1077// select the class from the boot classpath, do not attempt to resolve
1078// or compile it now.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001079static bool SkipClass(mirror::ClassLoader* class_loader,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001080 const DexFile& dex_file,
1081 const DexFile::ClassDef& class_def)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001082 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001083 if (class_loader == NULL) {
1084 return false;
1085 }
1086 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1087 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001088 mirror::Class* klass = class_linker->FindClass(descriptor, NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001089 if (klass == NULL) {
1090 Thread* self = Thread::Current();
1091 CHECK(self->IsExceptionPending());
1092 self->ClearException();
1093 return false;
1094 }
1095 return true;
1096}
1097
1098static void ResolveClassFieldsAndMethods(const CompilationContext* context, size_t class_def_index)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001099 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001100 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001101 mirror::ClassLoader* class_loader = soa.Decode<mirror::ClassLoader*>(context->GetClassLoader());
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001102 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001103
1104 // Method and Field are the worst. We can't resolve without either
1105 // context from the code use (to disambiguate virtual vs direct
1106 // method and instance vs static field) or from class
1107 // definitions. While the compiler will resolve what it can as it
1108 // needs it, here we try to resolve fields and methods used in class
1109 // definitions, since many of them many never be referenced by
1110 // generated code.
1111 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001112 if (SkipClass(class_loader, dex_file, class_def)) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001113 return;
1114 }
1115
1116 // Note the class_data pointer advances through the headers,
1117 // static fields, instance fields, direct methods, and virtual
1118 // methods.
1119 const byte* class_data = dex_file.GetClassData(class_def);
1120 if (class_data == NULL) {
1121 // empty class such as a marker interface
1122 return;
1123 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001124 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001125 ClassLinker* class_linker = context->GetClassLinker();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001126 mirror::DexCache* dex_cache = class_linker->FindDexCache(dex_file);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001127 ClassDataItemIterator it(dex_file, class_data);
1128 while (it.HasNextStaticField()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001129 mirror::Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
1130 class_loader, true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001131 if (field == NULL) {
1132 CHECK(self->IsExceptionPending());
1133 self->ClearException();
1134 }
1135 it.Next();
1136 }
Ian Rogersfffdb022013-01-04 15:14:08 -08001137 // If an instance field is final then we need to have a barrier on the return, static final
1138 // fields are assigned within the lock held for class initialization.
1139 bool requires_constructor_barrier = false;
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001140 while (it.HasNextInstanceField()) {
Ian Rogersfffdb022013-01-04 15:14:08 -08001141 if ((it.GetMemberAccessFlags() & kAccFinal) != 0) {
1142 requires_constructor_barrier = true;
1143 }
1144
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001145 mirror::Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
1146 class_loader, false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001147 if (field == NULL) {
1148 CHECK(self->IsExceptionPending());
1149 self->ClearException();
1150 }
1151 it.Next();
1152 }
Ian Rogersfffdb022013-01-04 15:14:08 -08001153 if (requires_constructor_barrier) {
1154 context->GetCompiler()->AddRequiresConstructorBarrier(soa.Self(), context->GetDexFile(),
1155 class_def_index);
1156 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001157 while (it.HasNextDirectMethod()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001158 mirror::AbstractMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1159 dex_cache, class_loader, NULL,
1160 it.GetMethodInvokeType(class_def));
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001161 if (method == NULL) {
1162 CHECK(self->IsExceptionPending());
1163 self->ClearException();
1164 }
1165 it.Next();
1166 }
1167 while (it.HasNextVirtualMethod()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001168 mirror::AbstractMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1169 dex_cache, class_loader, NULL,
1170 it.GetMethodInvokeType(class_def));
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001171 if (method == NULL) {
1172 CHECK(self->IsExceptionPending());
1173 self->ClearException();
1174 }
1175 it.Next();
1176 }
1177 DCHECK(!it.HasNext());
1178}
1179
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001180static void ResolveType(const CompilationContext* context, size_t type_idx)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001181 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001182 // Class derived values are more complicated, they require the linker and loader.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001183 ScopedObjectAccess soa(Thread::Current());
1184 ClassLinker* class_linker = context->GetClassLinker();
1185 const DexFile& dex_file = *context->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001186 mirror::DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1187 mirror::ClassLoader* class_loader = soa.Decode<mirror::ClassLoader*>(context->GetClassLoader());
1188 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001189
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001190 if (klass == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001191 CHECK(soa.Self()->IsExceptionPending());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001192 Thread::Current()->ClearException();
1193 }
1194}
1195
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001196void Compiler::ResolveDexFile(jobject class_loader, const DexFile& dex_file,
Brian Carlstrom2f663822012-11-07 22:49:06 -08001197 ThreadPool& thread_pool, TimingLogger& timings) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001198 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1199
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001200 // TODO: we could resolve strings here, although the string table is largely filled with class
1201 // and method names.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001202
Brian Carlstrom2f663822012-11-07 22:49:06 -08001203 CompilationContext context(class_linker, class_loader, this, &dex_file, thread_pool);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001204 context.ForAll(0, dex_file.NumTypeIds(), ResolveType, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001205 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Types");
Brian Carlstrom845490b2011-09-19 15:56:53 -07001206
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001207 context.ForAll(0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001208 timings.AddSplit("Resolve " + dex_file.GetLocation() + " MethodsAndFields");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001209}
1210
Ian Rogers3d1548d2012-09-24 14:08:03 -07001211void Compiler::Verify(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Brian Carlstrom2f663822012-11-07 22:49:06 -08001212 ThreadPool& thread_pool, TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -08001213 for (size_t i = 0; i != dex_files.size(); ++i) {
1214 const DexFile* dex_file = dex_files[i];
jeffhao98eacac2011-09-14 16:11:53 -07001215 CHECK(dex_file != NULL);
Brian Carlstrom2f663822012-11-07 22:49:06 -08001216 VerifyDexFile(class_loader, *dex_file, thread_pool, timings);
jeffhao98eacac2011-09-14 16:11:53 -07001217 }
1218}
1219
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001220static void VerifyClass(const CompilationContext* context, size_t class_def_index)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001221 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001222 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001223 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
1224 const char* descriptor = context->GetDexFile()->GetClassDescriptor(class_def);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001225 mirror::Class* klass =
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001226 context->GetClassLinker()->FindClass(descriptor,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001227 soa.Decode<mirror::ClassLoader*>(context->GetClassLoader()));
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001228 if (klass == NULL) {
1229 Thread* self = Thread::Current();
1230 CHECK(self->IsExceptionPending());
1231 self->ClearException();
jeffhaof56197c2012-03-05 18:01:54 -08001232
1233 /*
1234 * At compile time, we can still structurally verify the class even if FindClass fails.
1235 * This is to ensure the class is structurally sound for compilation. An unsound class
1236 * will be rejected by the verifier and later skipped during compilation in the compiler.
1237 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001238 mirror::DexCache* dex_cache = context->GetClassLinker()->FindDexCache(*context->GetDexFile());
jeffhaof56197c2012-03-05 18:01:54 -08001239 std::string error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001240 if (verifier::MethodVerifier::VerifyClass(context->GetDexFile(),
1241 dex_cache,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001242 soa.Decode<mirror::ClassLoader*>(context->GetClassLoader()),
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001243 class_def_index, error_msg) ==
1244 verifier::MethodVerifier::kHardFailure) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001245 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
jeffhaof56197c2012-03-05 18:01:54 -08001246 LOG(ERROR) << "Verification failed on class "
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001247 << PrettyDescriptor(context->GetDexFile()->GetClassDescriptor(class_def))
jeffhaof56197c2012-03-05 18:01:54 -08001248 << " because: " << error_msg;
1249 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001250 return;
1251 }
1252 CHECK(klass->IsResolved()) << PrettyClass(klass);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001253 context->GetClassLinker()->VerifyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001254
1255 if (klass->IsErroneous()) {
1256 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1257 CHECK(Thread::Current()->IsExceptionPending());
1258 Thread::Current()->ClearException();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001259 }
1260
Ian Rogers9ffb0392012-09-10 11:56:50 -07001261 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
1262 << PrettyDescriptor(klass) << ": state=" << klass->GetStatus();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001263 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1264}
1265
Brian Carlstrom2f663822012-11-07 22:49:06 -08001266void Compiler::VerifyDexFile(jobject class_loader, const DexFile& dex_file,
1267 ThreadPool& thread_pool, TimingLogger& timings) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001268 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom2f663822012-11-07 22:49:06 -08001269 CompilationContext context(class_linker, class_loader, this, &dex_file, thread_pool);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001270 context.ForAll(0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Ian Rogers3d1548d2012-09-24 14:08:03 -07001271 timings.AddSplit("Verify " + dex_file.GetLocation());
1272}
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001273
Ian Rogers64b6d142012-10-29 16:34:15 -07001274static const char* class_initializer_black_list[] = {
1275 "Landroid/app/ActivityThread;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1276 "Landroid/bluetooth/BluetoothAudioGateway;", // Calls android.bluetooth.BluetoothAudioGateway.classInitNative().
1277 "Landroid/bluetooth/HeadsetBase;", // Calls android.bluetooth.HeadsetBase.classInitNative().
1278 "Landroid/content/res/CompatibilityInfo;", // Requires android.util.DisplayMetrics -..-> android.os.SystemProperties.native_get_int.
1279 "Landroid/content/res/CompatibilityInfo$1;", // Requires android.util.DisplayMetrics -..-> android.os.SystemProperties.native_get_int.
1280 "Landroid/content/UriMatcher;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1281 "Landroid/database/CursorWindow;", // Requires android.util.DisplayMetrics -..-> android.os.SystemProperties.native_get_int.
1282 "Landroid/database/sqlite/SQLiteConnection;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1283 "Landroid/database/sqlite/SQLiteConnection$Operation;", // Requires SimpleDateFormat -> java.util.Locale.
1284 "Landroid/database/sqlite/SQLiteDatabaseConfiguration;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1285 "Landroid/database/sqlite/SQLiteDebug;", // Calls android.util.Log.isLoggable.
1286 "Landroid/database/sqlite/SQLiteOpenHelper;", // Calls Class.getSimpleName -> Class.isAnonymousClass -> Class.getDex.
1287 "Landroid/database/sqlite/SQLiteQueryBuilder;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1288 "Landroid/drm/DrmManagerClient;", // Calls System.loadLibrary.
1289 "Landroid/graphics/drawable/AnimatedRotateDrawable;", // Sub-class of Drawable.
1290 "Landroid/graphics/drawable/AnimationDrawable;", // Sub-class of Drawable.
1291 "Landroid/graphics/drawable/BitmapDrawable;", // Sub-class of Drawable.
1292 "Landroid/graphics/drawable/ClipDrawable;", // Sub-class of Drawable.
1293 "Landroid/graphics/drawable/ColorDrawable;", // Sub-class of Drawable.
1294 "Landroid/graphics/drawable/Drawable;", // Requires android.graphics.Rect.
1295 "Landroid/graphics/drawable/DrawableContainer;", // Sub-class of Drawable.
1296 "Landroid/graphics/drawable/GradientDrawable;", // Sub-class of Drawable.
1297 "Landroid/graphics/drawable/LayerDrawable;", // Sub-class of Drawable.
1298 "Landroid/graphics/drawable/NinePatchDrawable;", // Sub-class of Drawable.
1299 "Landroid/graphics/drawable/RotateDrawable;", // Sub-class of Drawable.
1300 "Landroid/graphics/drawable/ScaleDrawable;", // Sub-class of Drawable.
1301 "Landroid/graphics/drawable/ShapeDrawable;", // Sub-class of Drawable.
1302 "Landroid/graphics/drawable/StateListDrawable;", // Sub-class of Drawable.
1303 "Landroid/graphics/drawable/TransitionDrawable;", // Sub-class of Drawable.
1304 "Landroid/graphics/Matrix;", // Calls android.graphics.Matrix.native_create.
1305 "Landroid/graphics/Matrix$1;", // Requires Matrix.
1306 "Landroid/graphics/PixelFormat;", // Calls android.graphics.PixelFormat.nativeClassInit().
1307 "Landroid/graphics/Rect;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1308 "Landroid/graphics/SurfaceTexture;", // Calls android.graphics.SurfaceTexture.nativeClassInit().
1309 "Landroid/graphics/Typeface;", // Calls android.graphics.Typeface.nativeCreate.
1310 "Landroid/inputmethodservice/ExtractEditText;", // Requires android.widget.TextView.
1311 "Landroid/media/CameraProfile;", // Calls System.loadLibrary.
1312 "Landroid/media/DecoderCapabilities;", // Calls System.loadLibrary.
1313 "Landroid/media/MediaFile;", // Requires DecoderCapabilities.
1314 "Landroid/media/MediaPlayer;", // Calls System.loadLibrary.
1315 "Landroid/media/MediaRecorder;", // Calls System.loadLibrary.
1316 "Landroid/media/MediaScanner;", // Calls System.loadLibrary.
1317 "Landroid/net/NetworkInfo;", // Calls java.util.EnumMap.<init> -> java.lang.Enum.getSharedConstants -> System.identityHashCode.
1318 "Landroid/net/Proxy;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1319 "Landroid/net/SSLCertificateSocketFactory;", // Requires javax.net.ssl.HttpsURLConnection.
1320 "Landroid/net/Uri;", // Calls Class.getSimpleName -> Class.isAnonymousClass -> Class.getDex.
1321 "Landroid/net/Uri$AbstractHierarchicalUri;", // Requires Uri.
1322 "Landroid/net/Uri$HierarchicalUri;", // Requires Uri.
1323 "Landroid/net/Uri$OpaqueUri;", // Requires Uri.
1324 "Landroid/net/Uri$StringUri;", // Requires Uri.
1325 "Landroid/net/WebAddress;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1326 "Landroid/nfc/NdefRecord;", // Calls String.getBytes -> java.nio.charset.Charset.
1327 "Landroid/opengl/GLES10;", // Calls android.opengl.GLES10._nativeClassInit.
1328 "Landroid/opengl/GLES10Ext;", // Calls android.opengl.GLES10Ext._nativeClassInit.
1329 "Landroid/opengl/GLES11;", // Requires GLES10.
1330 "Landroid/opengl/GLES11Ext;", // Calls android.opengl.GLES11Ext._nativeClassInit.
1331 "Landroid/opengl/GLES20;", // Calls android.opengl.GLES20._nativeClassInit.
1332 "Landroid/opengl/GLUtils;", // Calls android.opengl.GLUtils.nativeClassInit.
1333 "Landroid/os/Build;", // Calls -..-> android.os.SystemProperties.native_get.
1334 "Landroid/os/Build$VERSION;", // Requires Build.
1335 "Landroid/os/Debug;", // Requires android.os.Environment.
1336 "Landroid/os/Environment;", // Calls System.getenv.
1337 "Landroid/os/FileUtils;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1338 "Landroid/os/StrictMode;", // Calls android.util.Log.isLoggable.
1339 "Landroid/os/StrictMode$VmPolicy;", // Requires StrictMode.
1340 "Landroid/os/Trace;", // Calls android.os.Trace.nativeGetEnabledTags.
1341 "Landroid/os/UEventObserver;", // Calls Class.getSimpleName -> Class.isAnonymousClass -> Class.getDex.
1342 "Landroid/provider/Settings$Secure;", // Requires android.net.Uri.
1343 "Landroid/provider/Settings$System;", // Requires android.net.Uri.
1344 "Landroid/renderscript/RenderScript;", // Calls System.loadLibrary.
1345 "Landroid/server/BluetoothService;", // Calls android.server.BluetoothService.classInitNative.
1346 "Landroid/server/BluetoothEventLoop;", // Calls android.server.BluetoothEventLoop.classInitNative.
1347 "Landroid/telephony/PhoneNumberUtils;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1348 "Landroid/text/AutoText;", // Requires android.util.DisplayMetrics -..-> android.os.SystemProperties.native_get_int.
1349 "Landroid/text/Layout;", // Calls com.android.internal.util.ArrayUtils.emptyArray -> System.identityHashCode.
1350 "Landroid/text/BoringLayout;", // Requires Layout.
1351 "Landroid/text/DynamicLayout;", // Requires Layout.
1352 "Landroid/text/Html$HtmlParser;", // Calls -..-> String.toLowerCase -> java.util.Locale.
1353 "Landroid/text/StaticLayout;", // Requires Layout.
1354 "Landroid/text/TextUtils;", // Requires android.util.DisplayMetrics.
1355 "Landroid/util/DisplayMetrics;", // Calls SystemProperties.native_get_int.
1356 "Landroid/util/Patterns;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1357 "Landroid/view/animation/Animation;", // Calls SystemProperties.native_get_boolean.
1358 "Landroid/view/animation/AlphaAnimation;", // Requires Animation.
1359 "Landroid/view/Choreographer;", // Calls SystemProperties.native_get_boolean.
1360 "Landroid/view/GLES20Canvas;", // Calls android.view.GLES20Canvas.nIsAvailable.
1361 "Landroid/view/GLES20RecordingCanvas;", // Requires android.view.GLES20Canvas.
1362 "Landroid/view/HardwareRenderer$GlRenderer;", // Requires SystemProperties.native_get.
1363 "Landroid/view/HardwareRenderer$Gl20Renderer;", // Requires SystemProperties.native_get.
1364 "Landroid/view/InputEventConsistencyVerifier;", // Requires android.os.Build.
1365 "Landroid/view/Surface;", // Requires SystemProperties.native_get.
1366 "Landroid/webkit/JniUtil;", // Calls System.loadLibrary.
1367 "Landroid/webkit/WebViewCore;", // Calls System.loadLibrary.
1368 "Landroid/widget/AutoCompleteTextView;", // Requires TextView.
1369 "Landroid/widget/Button;", // Requires TextView.
1370 "Landroid/widget/CheckBox;", // Requires TextView.
1371 "Landroid/widget/CheckedTextView;", // Requires TextView.
1372 "Landroid/widget/CompoundButton;", // Requires TextView.
1373 "Landroid/widget/EditText;", // Requires TextView.
1374 "Landroid/widget/NumberPicker;", // Requires java.util.Locale.
1375 "Landroid/widget/ScrollBarDrawable;", // Sub-class of Drawable.
1376 "Landroid/widget/SearchView$SearchAutoComplete;", // Requires TextView.
1377 "Landroid/widget/Switch;", // Requires TextView.
1378 "Landroid/widget/TextView;", // Calls Paint.<init> -> Paint.native_init.
1379 "Lcom/android/i18n/phonenumbers/AsYouTypeFormatter;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1380 "Lcom/android/i18n/phonenumbers/PhoneNumberUtil;", // Requires java.util.logging.LogManager.
1381 "Lcom/android/internal/os/SamplingProfilerIntegration;", // Calls SystemProperties.native_get_int.
1382 "Lcom/android/internal/policy/impl/PhoneWindow;", // Calls android.os.Binder.init.
1383 "Lcom/android/internal/view/menu/ActionMenuItemView;", // Requires TextView.
1384 "Lcom/android/internal/widget/DialogTitle;", // Requires TextView.
1385 "Lcom/android/org/bouncycastle/asn1/StreamUtil;", // Calls Runtime.getRuntime().maxMemory().
1386 "Lcom/android/org/bouncycastle/crypto/digests/OpenSSLDigest$SHA1;", // Requires org.apache.harmony.xnet.provider.jsse.NativeCrypto.
1387 "Lcom/android/org/bouncycastle/crypto/engines/RSABlindedEngine;", // Calls native ... -> java.math.NativeBN.BN_new().
1388 "Lcom/android/org/bouncycastle/jce/provider/CertBlacklist;", // Calls System.getenv -> OsConstants.initConstants.
1389 "Lcom/android/org/bouncycastle/jce/provider/PKIXCertPathValidatorSpi;", // Calls System.getenv -> OsConstants.initConstants.
1390 "Lcom/google/android/gles_jni/EGLContextImpl;", // Calls com.google.android.gles_jni.EGLImpl._nativeClassInit.
1391 "Lcom/google/android/gles_jni/EGLImpl;", // Calls com.google.android.gles_jni.EGLImpl._nativeClassInit.
1392 "Lcom/google/android/gles_jni/GLImpl;", // Calls com.google.android.gles_jni.GLImpl._nativeClassInit.
1393 "Ljava/io/Console;", // Has FileDescriptor(s).
1394 "Ljava/io/File;", // Calls to Random.<init> -> System.currentTimeMillis -> OsConstants.initConstants.
1395 "Ljava/io/FileDescriptor;", // Requires libcore.io.OsConstants.
1396 "Ljava/io/ObjectInputStream;", // Requires java.lang.ClassLoader$SystemClassLoader.
1397 "Ljava/io/ObjectStreamClass;", // Calls to Class.forName -> java.io.FileDescriptor.
1398 "Ljava/io/ObjectStreamConstants;", // Instance of non-image class SerializablePermission.
1399 "Ljava/lang/ClassLoader$SystemClassLoader;", // Calls System.getProperty -> OsConstants.initConstants.
1400 "Ljava/lang/Runtime;", // Calls System.getProperty -> OsConstants.initConstants.
1401 "Ljava/lang/System;", // Calls OsConstants.initConstants.
1402 "Ljava/math/BigDecimal;", // Calls native ... -> java.math.NativeBN.BN_new().
1403 "Ljava/math/BigInteger;", // Calls native ... -> java.math.NativeBN.BN_new().
1404 "Ljava/math/Multiplication;", // Calls native ... -> java.math.NativeBN.BN_new().
1405 "Ljava/net/InetAddress;", // Requires libcore.io.OsConstants.
1406 "Ljava/net/Inet4Address;", // Sub-class of InetAddress.
1407 "Ljava/net/Inet6Address;", // Sub-class of InetAddress.
1408 "Ljava/nio/charset/Charset;", // Calls Charset.getDefaultCharset -> System.getProperty -> OsConstants.initConstants.
1409 "Ljava/nio/charset/CharsetICU;", // Sub-class of Charset.
1410 "Ljava/nio/charset/Charsets;", // Calls Charset.forName.
1411 "Ljava/security/Security;", // Tries to do disk IO for "security.properties".
1412 "Ljava/util/Date;", // Calls Date.<init> -> System.currentTimeMillis -> OsConstants.initConstants.
1413 "Ljava/util/Locale;", // Calls System.getProperty -> OsConstants.initConstants.
1414 "Ljava/util/SimpleTimeZone;", // Sub-class of TimeZone.
1415 "Ljava/util/TimeZone;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1416 "Ljava/util/concurrent/ConcurrentHashMap$Segment;", // Calls Runtime.getRuntime().availableProcessors().
1417 "Ljava/util/logging/LogManager;", // Calls System.getProperty -> OsConstants.initConstants.
1418 "Ljavax/microedition/khronos/egl/EGL10;", // Requires EGLContext.
1419 "Ljavax/microedition/khronos/egl/EGLContext;", // Requires com.google.android.gles_jni.EGLImpl.
1420 "Ljavax/net/ssl/HttpsURLConnection;", // Calls SSLSocketFactory.getDefault -> java.security.Security.getProperty.
1421 "Llibcore/icu/LocaleData;", // Requires java.util.Locale.
1422 "Llibcore/icu/TimeZones;", // Requires java.util.TimeZone.
1423 "Llibcore/io/OsConstants;", // Platform specific.
1424 "Llibcore/net/MimeUtils;", // Calls libcore.net.MimeUtils.getContentTypesPropertiesStream -> System.getProperty.
1425 "Llibcore/util/ZoneInfo;", // Sub-class of TimeZone.
1426 "Llibcore/util/ZoneInfoDB;", // Calls System.getenv -> OsConstants.initConstants.
1427 "Lorg/apache/commons/logging/LogFactory;", // Calls System.getProperty.
1428 "Lorg/apache/harmony/security/fortress/Services;", // Calls ClassLoader.getSystemClassLoader -> System.getProperty.
1429 "Lorg/apache/harmony/security/provider/cert/X509CertFactoryImpl;", // Requires java.nio.charsets.Charsets.
1430 "Lorg/apache/harmony/security/provider/crypto/RandomBitsSupplier;", // Requires java.io.File.
1431 "Lorg/apache/harmony/security/utils/AlgNameMapper;", // Requires java.util.Locale.
1432 "Lorg/apache/harmony/security/x501/AttributeTypeAndValue;", // Calls IntegralToString.convertInt -> Thread.currentThread.
1433 "Lorg/apache/harmony/security/x501/DirectoryString;", // Requires BigInteger.
1434 "Lorg/apache/harmony/security/x501/Name;", // Requires org.apache.harmony.security.x501.AttributeTypeAndValue.
1435 "Lorg/apache/harmony/security/x509/Certificate;", // Requires org.apache.harmony.security.x509.TBSCertificate.
1436 "Lorg/apache/harmony/security/x509/TBSCertificate;", // Requires org.apache.harmony.security.x501.Name.
1437 "Lorg/apache/harmony/security/x509/EDIPartyName;", // Calls native ... -> java.math.NativeBN.BN_new().
1438 "Lorg/apache/harmony/security/x509/GeneralName;", // Requires org.apache.harmony.security.x501.Name.
1439 "Lorg/apache/harmony/security/x509/GeneralNames;", // Requires GeneralName.
1440 "Lorg/apache/harmony/security/x509/Time;", // Calls native ... -> java.math.NativeBN.BN_new().
1441 "Lorg/apache/harmony/security/x509/Validity;", // Requires x509.Time.
1442 "Lorg/apache/harmony/xml/ExpatParser;", // Calls native ExpatParser.staticInitialize.
1443 "Lorg/apache/harmony/xnet/provider/jsse/NativeCrypto;", // Calls native NativeCrypto.clinit().
1444 "Lorg/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigestJDK$MD5;", // Requires org.apache.harmony.xnet.provider.jsse.NativeCrypto.
1445 "Lorg/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigestJDK$SHA1;", // Requires org.apache.harmony.xnet.provider.jsse.NativeCrypto.
1446 "Lorg/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigestJDK$SHA512;", // Requires org.apache.harmony.xnet.provider.jsse.NativeCrypto.
1447 "Lorg/apache/harmony/xnet/provider/jsse/TrustedCertificateStore;", // Calls System.getenv -> OsConstants.initConstants.
1448 "Lorg/apache/http/conn/params/ConnRouteParams;", // Requires java.util.Locale.
1449 "Lorg/apache/http/conn/ssl/SSLSocketFactory;", // Calls java.security.Security.getProperty.
1450 "Lorg/apache/http/conn/util/InetAddressUtils;", // Calls regex.Pattern.compile -..-> regex.Pattern.compileImpl.
1451};
1452
1453static void InitializeClass(const CompilationContext* context, size_t class_def_index)
Ian Rogers3d1548d2012-09-24 14:08:03 -07001454 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1455 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
1456 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001457 mirror::ClassLoader* class_loader = soa.Decode<mirror::ClassLoader*>(context->GetClassLoader());
Ian Rogers3d1548d2012-09-24 14:08:03 -07001458 const char* descriptor = context->GetDexFile()->GetClassDescriptor(class_def);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001459 mirror::Class* klass = context->GetClassLinker()->FindClass(descriptor, class_loader);
Ian Rogers1f539342012-10-03 21:09:42 -07001460 Thread* self = Thread::Current();
Ian Rogers64b6d142012-10-29 16:34:15 -07001461 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
1462 bool can_init_static_fields = compiling_boot &&
1463 context->GetCompiler()->IsImageClass(descriptor);
Ian Rogers3d1548d2012-09-24 14:08:03 -07001464 if (klass != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001465 // We don't want class initialization occurring on multiple threads due to deadlock problems.
1466 // For example, a parent class is initialized (holding its lock) that refers to a sub-class
1467 // in its static/class initializer causing it to try to acquire the sub-class' lock. While
1468 // on a second thread the sub-class is initialized (holding its lock) after first initializing
1469 // its parents, whose locks are acquired. This leads to a parent-to-child and a child-to-parent
1470 // lock ordering and consequent potential deadlock.
1471 static Mutex lock1("Initializer lock", kMonitorLock);
1472 MutexLock mu(self, lock1);
1473 // The lock required to initialize the class.
1474 ObjectLock lock2(self, klass);
1475 // Only try to initialize classes that were successfully verified.
Ian Rogers3d1548d2012-09-24 14:08:03 -07001476 if (klass->IsVerified()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07001477 context->GetClassLinker()->EnsureInitialized(klass, false, can_init_static_fields);
Ian Rogers64b6d142012-10-29 16:34:15 -07001478 if (!klass->IsInitialized()) {
1479 if (can_init_static_fields) {
1480 bool is_black_listed = false;
1481 for (size_t i = 0; i < arraysize(class_initializer_black_list); ++i) {
1482 if (StringPiece(descriptor) == class_initializer_black_list[i]) {
1483 is_black_listed = true;
1484 break;
1485 }
1486 }
1487 if (!is_black_listed) {
1488 LOG(INFO) << "Initializing: " << descriptor;
1489 if (StringPiece(descriptor) == "Ljava/lang/Void;"){
1490 // Hand initialize j.l.Void to avoid Dex file operations in un-started runtime.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001491 mirror::ObjectArray<mirror::Field>* fields = klass->GetSFields();
Ian Rogers64b6d142012-10-29 16:34:15 -07001492 CHECK_EQ(fields->GetLength(), 1);
1493 fields->Get(0)->SetObj(klass, context->GetClassLinker()->FindPrimitiveClass('V'));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001494 klass->SetStatus(mirror::Class::kStatusInitialized);
Ian Rogers64b6d142012-10-29 16:34:15 -07001495 } else {
1496 context->GetClassLinker()->EnsureInitialized(klass, true, can_init_static_fields);
1497 }
1498 CHECK(!self->IsExceptionPending()) << self->GetException()->Dump();
1499 }
1500 }
1501 }
Ian Rogers3d1548d2012-09-24 14:08:03 -07001502 // If successfully initialized place in SSB array.
1503 if (klass->IsInitialized()) {
1504 klass->GetDexCache()->GetInitializedStaticStorage()->Set(klass->GetDexTypeIndex(), klass);
1505 }
1506 }
1507 // Record the final class status if necessary.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001508 mirror::Class::Status status = klass->GetStatus();
Ian Rogers3d1548d2012-09-24 14:08:03 -07001509 Compiler::ClassReference ref(context->GetDexFile(), class_def_index);
1510 CompiledClass* compiled_class = context->GetCompiler()->GetCompiledClass(ref);
1511 if (compiled_class == NULL) {
1512 compiled_class = new CompiledClass(status);
1513 context->GetCompiler()->RecordClassStatus(ref, compiled_class);
1514 } else {
1515 DCHECK_EQ(status, compiled_class->GetStatus());
1516 }
1517 }
Ian Rogers1f539342012-10-03 21:09:42 -07001518 // Clear any class not found or verification exceptions.
1519 self->ClearException();
Ian Rogers3d1548d2012-09-24 14:08:03 -07001520}
1521
Ian Rogers64b6d142012-10-29 16:34:15 -07001522void Compiler::InitializeClasses(jobject jni_class_loader, const DexFile& dex_file,
Brian Carlstrom2f663822012-11-07 22:49:06 -08001523 ThreadPool& thread_pool, TimingLogger& timings) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001524#ifndef NDEBUG
1525 for (size_t i = 0; i < arraysize(class_initializer_black_list); ++i) {
1526 const char* descriptor = class_initializer_black_list[i];
1527 CHECK(IsValidDescriptor(descriptor)) << descriptor;
1528 }
1529#endif
Ian Rogers3d1548d2012-09-24 14:08:03 -07001530 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom2f663822012-11-07 22:49:06 -08001531 CompilationContext context(class_linker, jni_class_loader, this, &dex_file, thread_pool);
Ian Rogers64b6d142012-10-29 16:34:15 -07001532 context.ForAll(0, dex_file.NumClassDefs(), InitializeClass, thread_count_);
Ian Rogers3d1548d2012-09-24 14:08:03 -07001533 timings.AddSplit("InitializeNoClinit " + dex_file.GetLocation());
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001534}
1535
Ian Rogers64b6d142012-10-29 16:34:15 -07001536void Compiler::InitializeClasses(jobject class_loader,
1537 const std::vector<const DexFile*>& dex_files,
Brian Carlstrom2f663822012-11-07 22:49:06 -08001538 ThreadPool& thread_pool, TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -08001539 for (size_t i = 0; i != dex_files.size(); ++i) {
1540 const DexFile* dex_file = dex_files[i];
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001541 CHECK(dex_file != NULL);
Brian Carlstrom2f663822012-11-07 22:49:06 -08001542 InitializeClasses(class_loader, *dex_file, thread_pool, timings);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001543 }
1544}
1545
Ian Rogers3d1548d2012-09-24 14:08:03 -07001546void Compiler::Compile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Brian Carlstrom2f663822012-11-07 22:49:06 -08001547 ThreadPool& thread_pool, TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -08001548 for (size_t i = 0; i != dex_files.size(); ++i) {
1549 const DexFile* dex_file = dex_files[i];
Brian Carlstrom83db7722011-08-26 17:32:56 -07001550 CHECK(dex_file != NULL);
Brian Carlstrom2f663822012-11-07 22:49:06 -08001551 CompileDexFile(class_loader, *dex_file, thread_pool, timings);
Brian Carlstrom83db7722011-08-26 17:32:56 -07001552 }
1553}
1554
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001555void Compiler::CompileClass(const CompilationContext* context, size_t class_def_index) {
1556 jobject class_loader = context->GetClassLoader();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001557 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesc225caa2012-02-03 15:43:37 -08001558 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001559 {
1560 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001561 mirror::ClassLoader* class_loader = soa.Decode<mirror::ClassLoader*>(context->GetClassLoader());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001562 if (SkipClass(class_loader, dex_file, class_def)) {
1563 return;
1564 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001565 }
jeffhaod1224c72012-02-29 13:43:08 -08001566 ClassReference ref(&dex_file, class_def_index);
1567 // Skip compiling classes with generic verifier failures since they will still fail at runtime
Ian Rogers776ac1f2012-04-13 23:36:36 -07001568 if (verifier::MethodVerifier::IsClassRejected(ref)) {
jeffhaod1224c72012-02-29 13:43:08 -08001569 return;
1570 }
Ian Rogers0571d352011-11-03 19:51:38 -07001571 const byte* class_data = dex_file.GetClassData(class_def);
1572 if (class_data == NULL) {
1573 // empty class, probably a marker interface
1574 return;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001575 }
Ian Rogers0571d352011-11-03 19:51:38 -07001576 ClassDataItemIterator it(dex_file, class_data);
1577 // Skip fields
1578 while (it.HasNextStaticField()) {
1579 it.Next();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001580 }
Ian Rogers0571d352011-11-03 19:51:38 -07001581 while (it.HasNextInstanceField()) {
1582 it.Next();
1583 }
1584 // Compile direct methods
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001585 int64_t previous_direct_method_idx = -1;
Ian Rogers0571d352011-11-03 19:51:38 -07001586 while (it.HasNextDirectMethod()) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001587 uint32_t method_idx = it.GetMemberIndex();
1588 if (method_idx == previous_direct_method_idx) {
1589 // smali can create dex files with two encoded_methods sharing the same method_idx
1590 // http://code.google.com/p/smali/issues/detail?id=119
1591 it.Next();
1592 continue;
1593 }
1594 previous_direct_method_idx = method_idx;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001595 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
Ian Rogersfffdb022013-01-04 15:14:08 -08001596 it.GetMethodInvokeType(class_def), class_def_index,
1597 method_idx, class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001598 it.Next();
1599 }
1600 // Compile virtual methods
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001601 int64_t previous_virtual_method_idx = -1;
Ian Rogers0571d352011-11-03 19:51:38 -07001602 while (it.HasNextVirtualMethod()) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001603 uint32_t method_idx = it.GetMemberIndex();
1604 if (method_idx == previous_virtual_method_idx) {
1605 // smali can create dex files with two encoded_methods sharing the same method_idx
1606 // http://code.google.com/p/smali/issues/detail?id=119
1607 it.Next();
1608 continue;
1609 }
1610 previous_virtual_method_idx = method_idx;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001611 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
Ian Rogersfffdb022013-01-04 15:14:08 -08001612 it.GetMethodInvokeType(class_def), class_def_index,
1613 method_idx, class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001614 it.Next();
1615 }
1616 DCHECK(!it.HasNext());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001617}
1618
Ian Rogers3d1548d2012-09-24 14:08:03 -07001619void Compiler::CompileDexFile(jobject class_loader, const DexFile& dex_file,
Brian Carlstrom2f663822012-11-07 22:49:06 -08001620 ThreadPool& thread_pool, TimingLogger& timings) {
1621 CompilationContext context(NULL, class_loader, this, &dex_file, thread_pool);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001622 context.ForAll(0, dex_file.NumClassDefs(), Compiler::CompileClass, thread_count_);
Ian Rogers3d1548d2012-09-24 14:08:03 -07001623 timings.AddSplit("Compile " + dex_file.GetLocation());
Elliott Hughesc225caa2012-02-03 15:43:37 -08001624}
1625
Elliott Hughesa0e18062012-04-13 15:59:59 -07001626static std::string MakeInvokeStubKey(bool is_static, const char* shorty) {
1627 std::string key(shorty);
1628 if (is_static) {
1629 key += "$"; // Must not be a shorty type character.
1630 }
1631 return key;
1632}
1633
Ian Rogersa3760aa2011-11-14 14:32:37 -08001634void Compiler::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogersfffdb022013-01-04 15:14:08 -08001635 InvokeType invoke_type, uint32_t class_def_idx, uint32_t method_idx,
1636 jobject class_loader, const DexFile& dex_file) {
Elliott Hughesf09afe82011-10-16 14:24:21 -07001637 CompiledMethod* compiled_method = NULL;
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001638 uint64_t start_ns = NanoTime();
Logan Chien4dd96f52012-02-29 01:26:58 +08001639
Ian Rogers169c9a72011-11-13 20:13:17 -08001640 if ((access_flags & kAccNative) != 0) {
Ian Rogers57b86d42012-03-27 16:05:41 -07001641 compiled_method = (*jni_compiler_)(*this, access_flags, method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001642 CHECK(compiled_method != NULL);
Ian Rogers169c9a72011-11-13 20:13:17 -08001643 } else if ((access_flags & kAccAbstract) != 0) {
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001644 } else {
Ian Rogersfffdb022013-01-04 15:14:08 -08001645 compiled_method = (*compiler_)(*this, code_item, access_flags, invoke_type, class_def_idx,
1646 method_idx, class_loader, dex_file);
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001647 CHECK(compiled_method != NULL) << PrettyMethod(method_idx, dex_file);
1648 }
Ian Rogers3bb17a62012-01-27 23:56:44 -08001649 uint64_t duration_ns = NanoTime() - start_ns;
Ian Rogers5354ec52013-01-23 14:27:27 -08001650#ifdef ART_USE_LLVM_COMPILER
1651 const uint64_t kWarnMilliSeconds = 1000;
1652#else
1653 const uint64_t kWarnMilliSeconds = 100;
1654#endif
1655 if (duration_ns > MsToNs(kWarnMilliSeconds)) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001656 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
Ian Rogers3bb17a62012-01-27 23:56:44 -08001657 << " took " << PrettyDuration(duration_ns);
Elliott Hughesf09afe82011-10-16 14:24:21 -07001658 }
1659
Ian Rogers50b35e22012-10-04 10:09:15 -07001660 Thread* self = Thread::Current();
Elliott Hughesf09afe82011-10-16 14:24:21 -07001661 if (compiled_method != NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07001662 MethodReference ref(&dex_file, method_idx);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001663 CHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001664 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001665 MutexLock mu(self, compiled_methods_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001666 compiled_methods_.Put(ref, compiled_method);
1667 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001668 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001669 }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -07001670
Ian Rogers45619fc2012-02-29 11:15:25 -08001671 uint32_t shorty_len;
1672 const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx), &shorty_len);
Ian Rogers169c9a72011-11-13 20:13:17 -08001673 bool is_static = (access_flags & kAccStatic) != 0;
Elliott Hughesa0e18062012-04-13 15:59:59 -07001674 std::string key(MakeInvokeStubKey(is_static, shorty));
1675 const CompiledInvokeStub* compiled_invoke_stub = FindInvokeStub(key);
Ian Rogers0571d352011-11-03 19:51:38 -07001676 if (compiled_invoke_stub == NULL) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001677 compiled_invoke_stub = (*create_invoke_stub_)(*this, is_static, shorty, shorty_len);
Ian Rogers0571d352011-11-03 19:51:38 -07001678 CHECK(compiled_invoke_stub != NULL);
Elliott Hughesa0e18062012-04-13 15:59:59 -07001679 InsertInvokeStub(key, compiled_invoke_stub);
Ian Rogers2c8f6532011-09-02 17:16:34 -07001680 }
Logan Chien7a2a23a2012-06-06 11:01:00 +08001681
buzbeec531cef2012-10-18 07:09:20 -07001682 if (((compiler_backend_ == kPortable) || (compiler_backend_ == kIceland)) && !is_static) {
Logan Chien7a2a23a2012-06-06 11:01:00 +08001683 const CompiledInvokeStub* compiled_proxy_stub = FindProxyStub(shorty);
1684 if (compiled_proxy_stub == NULL) {
1685 compiled_proxy_stub = (*create_proxy_stub_)(*this, shorty, shorty_len);
1686 CHECK(compiled_proxy_stub != NULL);
1687 InsertProxyStub(shorty, compiled_proxy_stub);
1688 }
1689 }
Logan Chien7a2a23a2012-06-06 11:01:00 +08001690
Ian Rogers50b35e22012-10-04 10:09:15 -07001691 if (self->IsExceptionPending()) {
1692 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001693 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
Ian Rogers50b35e22012-10-04 10:09:15 -07001694 << self->GetException()->Dump();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001695 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001696}
1697
Elliott Hughesa0e18062012-04-13 15:59:59 -07001698const CompiledInvokeStub* Compiler::FindInvokeStub(bool is_static, const char* shorty) const {
1699 const std::string key(MakeInvokeStubKey(is_static, shorty));
1700 return FindInvokeStub(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001701}
1702
Elliott Hughesa0e18062012-04-13 15:59:59 -07001703const CompiledInvokeStub* Compiler::FindInvokeStub(const std::string& key) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001704 MutexLock mu(Thread::Current(), compiled_invoke_stubs_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001705 InvokeStubTable::const_iterator it = compiled_invoke_stubs_.find(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001706 if (it == compiled_invoke_stubs_.end()) {
1707 return NULL;
Ian Rogers0571d352011-11-03 19:51:38 -07001708 } else {
1709 DCHECK(it->second != NULL);
1710 return it->second;
1711 }
1712}
1713
Elliott Hughesa0e18062012-04-13 15:59:59 -07001714void Compiler::InsertInvokeStub(const std::string& key,
Ian Rogers0571d352011-11-03 19:51:38 -07001715 const CompiledInvokeStub* compiled_invoke_stub) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001716 MutexLock mu(Thread::Current(), compiled_invoke_stubs_lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -07001717 InvokeStubTable::iterator it = compiled_invoke_stubs_.find(key);
1718 if (it != compiled_invoke_stubs_.end()) {
1719 // Someone else won the race.
1720 delete compiled_invoke_stub;
1721 } else {
1722 compiled_invoke_stubs_.Put(key, compiled_invoke_stub);
1723 }
Ian Rogers0571d352011-11-03 19:51:38 -07001724}
1725
Logan Chien7a2a23a2012-06-06 11:01:00 +08001726const CompiledInvokeStub* Compiler::FindProxyStub(const char* shorty) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001727 MutexLock mu(Thread::Current(), compiled_proxy_stubs_lock_);
Logan Chien7a2a23a2012-06-06 11:01:00 +08001728 ProxyStubTable::const_iterator it = compiled_proxy_stubs_.find(shorty);
1729 if (it == compiled_proxy_stubs_.end()) {
1730 return NULL;
1731 } else {
1732 DCHECK(it->second != NULL);
1733 return it->second;
1734 }
1735}
1736
1737void Compiler::InsertProxyStub(const char* shorty,
1738 const CompiledInvokeStub* compiled_proxy_stub) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001739 MutexLock mu(Thread::Current(), compiled_proxy_stubs_lock_);
Logan Chien7a2a23a2012-06-06 11:01:00 +08001740 InvokeStubTable::iterator it = compiled_proxy_stubs_.find(shorty);
1741 if (it != compiled_proxy_stubs_.end()) {
1742 // Someone else won the race.
1743 delete compiled_proxy_stub;
1744 } else {
1745 compiled_proxy_stubs_.Put(shorty, compiled_proxy_stub);
1746 }
1747}
Logan Chien7a2a23a2012-06-06 11:01:00 +08001748
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001749CompiledClass* Compiler::GetCompiledClass(ClassReference ref) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001750 MutexLock mu(Thread::Current(), compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001751 ClassTable::const_iterator it = compiled_classes_.find(ref);
1752 if (it == compiled_classes_.end()) {
1753 return NULL;
1754 }
1755 CHECK(it->second != NULL);
1756 return it->second;
1757}
1758
Ian Rogers0571d352011-11-03 19:51:38 -07001759CompiledMethod* Compiler::GetCompiledMethod(MethodReference ref) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001760 MutexLock mu(Thread::Current(), compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001761 MethodTable::const_iterator it = compiled_methods_.find(ref);
1762 if (it == compiled_methods_.end()) {
1763 return NULL;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001764 }
1765 CHECK(it->second != NULL);
1766 return it->second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001767}
1768
Logan Chien8b977d32012-02-21 19:14:55 +08001769void Compiler::SetBitcodeFileName(std::string const& filename) {
Logan Chien106b2a02012-03-18 04:41:38 +08001770 typedef void (*SetBitcodeFileNameFn)(Compiler&, std::string const&);
1771
1772 SetBitcodeFileNameFn set_bitcode_file_name =
buzbee8c4bbb52012-11-26 14:00:58 -08001773 FindFunction<SetBitcodeFileNameFn>(MakeCompilerSoName(compiler_backend_), compiler_library_,
Logan Chien106b2a02012-03-18 04:41:38 +08001774 "compilerLLVMSetBitcodeFileName");
1775
1776 set_bitcode_file_name(*this, filename);
Logan Chien8b977d32012-02-21 19:14:55 +08001777}
Logan Chienf7015fd2012-03-18 01:19:37 +08001778
Ian Rogersfffdb022013-01-04 15:14:08 -08001779
1780void Compiler::AddRequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
1781 size_t class_def_index) {
1782 MutexLock mu(self, freezing_constructor_lock_);
1783 freezing_constructor_classes_.insert(ClassReference(dex_file, class_def_index));
1784}
1785
1786bool Compiler::RequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
1787 size_t class_def_index) {
1788 MutexLock mu(self, freezing_constructor_lock_);
1789 return freezing_constructor_classes_.count(ClassReference(dex_file, class_def_index)) != 0;
1790}
1791
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001792bool Compiler::WriteElf(std::vector<uint8_t>& oat_contents, File* file) {
1793 typedef bool (*WriteElfFn)(Compiler&, std::vector<uint8_t>&, File*);
1794 WriteElfFn WriteElf =
1795 FindFunction<WriteElfFn>(MakeCompilerSoName(compiler_backend_), compiler_library_, "WriteElf");
1796 return WriteElf(*this, oat_contents, file);
1797}
1798
1799bool Compiler::FixupElf(File* file, uintptr_t oat_data_begin) const {
1800 typedef bool (*FixupElfFn)(File*, uintptr_t oat_data_begin);
1801 FixupElfFn FixupElf =
1802 FindFunction<FixupElfFn>(MakeCompilerSoName(compiler_backend_), compiler_library_, "FixupElf");
1803 return FixupElf(file, oat_data_begin);
1804}
1805
1806void Compiler::GetOatElfInformation(File* file,
1807 size_t& oat_loaded_size,
1808 size_t& oat_data_offset) const {
1809 typedef bool (*GetOatElfInformationFn)(File*, size_t& oat_loaded_size, size_t& oat_data_offset);
1810 GetOatElfInformationFn GetOatElfInformation =
1811 FindFunction<GetOatElfInformationFn>(MakeCompilerSoName(compiler_backend_), compiler_library_,
1812 "GetOatElfInformation");
1813 GetOatElfInformation(file, oat_loaded_size, oat_data_offset);
1814}
1815
1816void Compiler::InstructionSetToLLVMTarget(InstructionSet instruction_set,
1817 std::string& target_triple,
1818 std::string& target_cpu,
1819 std::string& target_attr) {
1820 switch (instruction_set) {
1821 case kThumb2:
1822 target_triple = "thumb-none-linux-gnueabi";
1823 target_cpu = "cortex-a9";
1824 target_attr = "+thumb2,+neon,+neonfp,+vfp3,+db";
1825 break;
1826
1827 case kArm:
1828 target_triple = "armv7-none-linux-gnueabi";
1829 // TODO: Fix for Nexus S.
1830 target_cpu = "cortex-a9";
1831 // TODO: Fix for Xoom.
1832 target_attr = "+v7,+neon,+neonfp,+vfp3,+db";
1833 break;
1834
1835 case kX86:
1836 target_triple = "i386-pc-linux-gnu";
1837 target_attr = "";
1838 break;
1839
1840 case kMips:
1841 target_triple = "mipsel-unknown-linux";
1842 target_attr = "mips32r2";
1843 break;
1844
1845 default:
1846 LOG(FATAL) << "Unknown instruction set: " << instruction_set;
1847 }
1848 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001849} // namespace art