blob: e3eb9e9915763c62134076f48dc0c8d129c1b5d2 [file] [log] [blame]
Ian Rogerse63db272014-07-15 15:36:11 -07001/*
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 */
16
17#include "common_compiler_test.h"
18
19#if defined(__arm__)
20#include <sys/ucontext.h>
21#endif
22#include <fstream>
23
24#include "class_linker.h"
25#include "compiled_method.h"
26#include "dex/quick_compiler_callbacks.h"
27#include "dex/verification_results.h"
28#include "dex/quick/dex_file_to_method_inliner_map.h"
29#include "driver/compiler_driver.h"
30#include "entrypoints/entrypoint_utils.h"
31#include "interpreter/interpreter.h"
32#include "mirror/art_method.h"
33#include "mirror/dex_cache.h"
34#include "mirror/object-inl.h"
35#include "scoped_thread_state_change.h"
36#include "thread-inl.h"
37#include "utils.h"
38
39namespace art {
40
41// Normally the ClassLinker supplies this.
42extern "C" void art_quick_generic_jni_trampoline(mirror::ArtMethod*);
43
44#if defined(__arm__)
45// A signal handler called when have an illegal instruction. We record the fact in
46// a global boolean and then increment the PC in the signal context to return to
47// the next instruction. We know the instruction is an sdiv (4 bytes long).
48static void baddivideinst(int signo, siginfo *si, void *data) {
49 UNUSED(signo);
50 UNUSED(si);
51 struct ucontext *uc = (struct ucontext *)data;
52 struct sigcontext *sc = &uc->uc_mcontext;
53 sc->arm_r0 = 0; // set R0 to #0 to signal error
54 sc->arm_pc += 4; // skip offending instruction
55}
56
57// This is in arch/arm/arm_sdiv.S. It does the following:
58// mov r1,#1
59// sdiv r0,r1,r1
60// bx lr
61//
62// the result will be the value 1 if sdiv is supported. If it is not supported
63// a SIGILL signal will be raised and the signal handler (baddivideinst) called.
64// The signal handler sets r0 to #0 and then increments pc beyond the failed instruction.
65// Thus if the instruction is not supported, the result of this function will be #0
66
67extern "C" bool CheckForARMSDIVInstruction();
68
69static InstructionSetFeatures GuessInstructionFeatures() {
70 InstructionSetFeatures f;
71
72 // Uncomment this for processing of /proc/cpuinfo.
73 if (false) {
74 // Look in /proc/cpuinfo for features we need. Only use this when we can guarantee that
75 // the kernel puts the appropriate feature flags in here. Sometimes it doesn't.
76 std::ifstream in("/proc/cpuinfo");
77 if (in) {
78 while (!in.eof()) {
79 std::string line;
80 std::getline(in, line);
81 if (!in.eof()) {
82 if (line.find("Features") != std::string::npos) {
83 if (line.find("idivt") != std::string::npos) {
84 f.SetHasDivideInstruction(true);
85 }
86 }
87 }
88 in.close();
89 }
90 } else {
91 LOG(INFO) << "Failed to open /proc/cpuinfo";
92 }
93 }
94
95 // See if have a sdiv instruction. Register a signal handler and try to execute
96 // an sdiv instruction. If we get a SIGILL then it's not supported. We can't use
97 // the /proc/cpuinfo method for this because Krait devices don't always put the idivt
98 // feature in the list.
99 struct sigaction sa, osa;
100 sa.sa_flags = SA_ONSTACK | SA_RESTART | SA_SIGINFO;
101 sa.sa_sigaction = baddivideinst;
102 sigaction(SIGILL, &sa, &osa);
103
104 if (CheckForARMSDIVInstruction()) {
105 f.SetHasDivideInstruction(true);
106 }
107
108 // Restore the signal handler.
109 sigaction(SIGILL, &osa, nullptr);
110
111 // Other feature guesses in here.
112 return f;
113}
114#endif
115
116// Given a set of instruction features from the build, parse it. The
117// input 'str' is a comma separated list of feature names. Parse it and
118// return the InstructionSetFeatures object.
119static InstructionSetFeatures ParseFeatureList(std::string str) {
120 InstructionSetFeatures result;
121 typedef std::vector<std::string> FeatureList;
122 FeatureList features;
123 Split(str, ',', features);
124 for (FeatureList::iterator i = features.begin(); i != features.end(); i++) {
125 std::string feature = Trim(*i);
126 if (feature == "default") {
127 // Nothing to do.
128 } else if (feature == "div") {
129 // Supports divide instruction.
130 result.SetHasDivideInstruction(true);
131 } else if (feature == "nodiv") {
132 // Turn off support for divide instruction.
133 result.SetHasDivideInstruction(false);
134 } else {
135 LOG(FATAL) << "Unknown instruction set feature: '" << feature << "'";
136 }
137 }
138 // Others...
139 return result;
140}
141
142CommonCompilerTest::CommonCompilerTest() {}
143CommonCompilerTest::~CommonCompilerTest() {}
144
145OatFile::OatMethod CommonCompilerTest::CreateOatMethod(const void* code, const uint8_t* gc_map) {
146 CHECK(code != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700147 const uint8_t* base;
Ian Rogerse63db272014-07-15 15:36:11 -0700148 uint32_t code_offset, gc_map_offset;
149 if (gc_map == nullptr) {
Ian Rogers13735952014-10-08 12:43:28 -0700150 base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
151 base -= sizeof(void*); // Move backward so that code_offset != 0.
152 code_offset = sizeof(void*);
Ian Rogerse63db272014-07-15 15:36:11 -0700153 gc_map_offset = 0;
154 } else {
155 // TODO: 64bit support.
156 base = nullptr; // Base of data in oat file, ie 0.
157 code_offset = PointerToLowMemUInt32(code);
158 gc_map_offset = PointerToLowMemUInt32(gc_map);
159 }
160 return OatFile::OatMethod(base, code_offset, gc_map_offset);
161}
162
163void CommonCompilerTest::MakeExecutable(mirror::ArtMethod* method) {
164 CHECK(method != nullptr);
165
166 const CompiledMethod* compiled_method = nullptr;
167 if (!method->IsAbstract()) {
168 mirror::DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
169 const DexFile& dex_file = *dex_cache->GetDexFile();
170 compiled_method =
171 compiler_driver_->GetCompiledMethod(MethodReference(&dex_file,
172 method->GetDexMethodIndex()));
173 }
174 if (compiled_method != nullptr) {
175 const std::vector<uint8_t>* code = compiled_method->GetQuickCode();
176 const void* code_ptr;
177 if (code != nullptr) {
178 uint32_t code_size = code->size();
179 CHECK_NE(0u, code_size);
180 const std::vector<uint8_t>& vmap_table = compiled_method->GetVmapTable();
181 uint32_t vmap_table_offset = vmap_table.empty() ? 0u
182 : sizeof(OatQuickMethodHeader) + vmap_table.size();
183 const std::vector<uint8_t>& mapping_table = compiled_method->GetMappingTable();
184 uint32_t mapping_table_offset = mapping_table.empty() ? 0u
185 : sizeof(OatQuickMethodHeader) + vmap_table.size() + mapping_table.size();
186 OatQuickMethodHeader method_header(mapping_table_offset, vmap_table_offset,
187 compiled_method->GetFrameSizeInBytes(),
188 compiled_method->GetCoreSpillMask(),
189 compiled_method->GetFpSpillMask(), code_size);
190
191 header_code_and_maps_chunks_.push_back(std::vector<uint8_t>());
192 std::vector<uint8_t>* chunk = &header_code_and_maps_chunks_.back();
193 size_t size = sizeof(method_header) + code_size + vmap_table.size() + mapping_table.size();
194 size_t code_offset = compiled_method->AlignCode(size - code_size);
195 size_t padding = code_offset - (size - code_size);
196 chunk->reserve(padding + size);
197 chunk->resize(sizeof(method_header));
198 memcpy(&(*chunk)[0], &method_header, sizeof(method_header));
199 chunk->insert(chunk->begin(), vmap_table.begin(), vmap_table.end());
200 chunk->insert(chunk->begin(), mapping_table.begin(), mapping_table.end());
201 chunk->insert(chunk->begin(), padding, 0);
202 chunk->insert(chunk->end(), code->begin(), code->end());
203 CHECK_EQ(padding + size, chunk->size());
204 code_ptr = &(*chunk)[code_offset];
205 } else {
206 code = compiled_method->GetPortableCode();
207 code_ptr = &(*code)[0];
208 }
209 MakeExecutable(code_ptr, code->size());
210 const void* method_code = CompiledMethod::CodePointer(code_ptr,
211 compiled_method->GetInstructionSet());
212 LOG(INFO) << "MakeExecutable " << PrettyMethod(method) << " code=" << method_code;
213 OatFile::OatMethod oat_method = CreateOatMethod(method_code, nullptr);
214 oat_method.LinkMethod(method);
215 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
216 } else {
217 // No code? You must mean to go into the interpreter.
218 // Or the generic JNI...
219 if (!method->IsNative()) {
220 const void* method_code = kUsePortableCompiler ? GetPortableToInterpreterBridge()
221 : GetQuickToInterpreterBridge();
222 OatFile::OatMethod oat_method = CreateOatMethod(method_code, nullptr);
223 oat_method.LinkMethod(method);
224 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
225 } else {
226 const void* method_code = reinterpret_cast<void*>(art_quick_generic_jni_trampoline);
227
228 OatFile::OatMethod oat_method = CreateOatMethod(method_code, nullptr);
229 oat_method.LinkMethod(method);
230 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
231 }
232 }
233 // Create bridges to transition between different kinds of compiled bridge.
234 if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
235 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
236 } else {
237 CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
238 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
239 method->SetIsPortableCompiled();
240 }
241}
242
243void CommonCompilerTest::MakeExecutable(const void* code_start, size_t code_length) {
244 CHECK(code_start != nullptr);
245 CHECK_NE(code_length, 0U);
246 uintptr_t data = reinterpret_cast<uintptr_t>(code_start);
247 uintptr_t base = RoundDown(data, kPageSize);
248 uintptr_t limit = RoundUp(data + code_length, kPageSize);
249 uintptr_t len = limit - base;
250 int result = mprotect(reinterpret_cast<void*>(base), len, PROT_READ | PROT_WRITE | PROT_EXEC);
251 CHECK_EQ(result, 0);
252
253 // Flush instruction cache
254 // Only uses __builtin___clear_cache if GCC >= 4.3.3
255#if GCC_VERSION >= 40303
256 __builtin___clear_cache(reinterpret_cast<void*>(base), reinterpret_cast<void*>(base + len));
257#else
258 // Only warn if not Intel as Intel doesn't have cache flush instructions.
259#if !defined(__i386__) && !defined(__x86_64__)
260 LOG(WARNING) << "UNIMPLEMENTED: cache flush";
261#endif
262#endif
263}
264
265void CommonCompilerTest::MakeExecutable(mirror::ClassLoader* class_loader, const char* class_name) {
266 std::string class_descriptor(DotToDescriptor(class_name));
267 Thread* self = Thread::Current();
268 StackHandleScope<1> hs(self);
269 Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
270 mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
271 CHECK(klass != nullptr) << "Class not found " << class_name;
272 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
273 MakeExecutable(klass->GetDirectMethod(i));
274 }
275 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
276 MakeExecutable(klass->GetVirtualMethod(i));
277 }
278}
279
280void CommonCompilerTest::SetUp() {
281 CommonRuntimeTest::SetUp();
282 {
283 ScopedObjectAccess soa(Thread::Current());
284
285 InstructionSet instruction_set = kRuntimeISA;
286
287 // Take the default set of instruction features from the build.
288 InstructionSetFeatures instruction_set_features =
289 ParseFeatureList(Runtime::GetDefaultInstructionSetFeatures());
290
291#if defined(__arm__)
292 InstructionSetFeatures runtime_features = GuessInstructionFeatures();
293
294 // for ARM, do a runtime check to make sure that the features we are passed from
295 // the build match the features we actually determine at runtime.
296 ASSERT_LE(instruction_set_features, runtime_features);
297#endif
298
299 runtime_->SetInstructionSet(instruction_set);
300 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
301 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
302 if (!runtime_->HasCalleeSaveMethod(type)) {
303 runtime_->SetCalleeSaveMethod(
304 runtime_->CreateCalleeSaveMethod(type), type);
305 }
306 }
307
308 // TODO: make selectable
309 Compiler::Kind compiler_kind
310 = (kUsePortableCompiler) ? Compiler::kPortable : Compiler::kQuick;
311 timer_.reset(new CumulativeLogger("Compilation times"));
312 compiler_driver_.reset(new CompilerDriver(compiler_options_.get(),
313 verification_results_.get(),
314 method_inliner_map_.get(),
315 compiler_kind, instruction_set,
316 instruction_set_features,
Ian Rogers1ff3c982014-08-12 02:30:58 -0700317 true, new std::set<std::string>,
Ian Rogerse63db272014-07-15 15:36:11 -0700318 2, true, true, timer_.get()));
319 }
320 // We typically don't generate an image in unit tests, disable this optimization by default.
321 compiler_driver_->SetSupportBootImageFixup(false);
322}
323
324void CommonCompilerTest::SetUpRuntimeOptions(RuntimeOptions* options) {
325 CommonRuntimeTest::SetUpRuntimeOptions(options);
326
327 compiler_options_.reset(new CompilerOptions);
328 verification_results_.reset(new VerificationResults(compiler_options_.get()));
329 method_inliner_map_.reset(new DexFileToMethodInlinerMap);
330 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(),
331 method_inliner_map_.get()));
332 options->push_back(std::make_pair("compilercallbacks", callbacks_.get()));
333}
334
335void CommonCompilerTest::TearDown() {
336 timer_.reset();
337 compiler_driver_.reset();
338 callbacks_.reset();
339 method_inliner_map_.reset();
340 verification_results_.reset();
341 compiler_options_.reset();
342
343 CommonRuntimeTest::TearDown();
344}
345
346void CommonCompilerTest::CompileClass(mirror::ClassLoader* class_loader, const char* class_name) {
347 std::string class_descriptor(DotToDescriptor(class_name));
348 Thread* self = Thread::Current();
349 StackHandleScope<1> hs(self);
350 Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
351 mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
352 CHECK(klass != nullptr) << "Class not found " << class_name;
353 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
354 CompileMethod(klass->GetDirectMethod(i));
355 }
356 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
357 CompileMethod(klass->GetVirtualMethod(i));
358 }
359}
360
361void CommonCompilerTest::CompileMethod(mirror::ArtMethod* method) {
362 CHECK(method != nullptr);
363 TimingLogger timings("CommonTest::CompileMethod", false, false);
364 TimingLogger::ScopedTiming t(__FUNCTION__, &timings);
365 compiler_driver_->CompileOne(method, &timings);
366 TimingLogger::ScopedTiming t2("MakeExecutable", &timings);
367 MakeExecutable(method);
368}
369
Andreas Gampe5a4b8a22014-09-11 08:30:08 -0700370void CommonCompilerTest::CompileDirectMethod(Handle<mirror::ClassLoader> class_loader,
Ian Rogerse63db272014-07-15 15:36:11 -0700371 const char* class_name, const char* method_name,
372 const char* signature) {
373 std::string class_descriptor(DotToDescriptor(class_name));
374 Thread* self = Thread::Current();
375 mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
376 CHECK(klass != nullptr) << "Class not found " << class_name;
377 mirror::ArtMethod* method = klass->FindDirectMethod(method_name, signature);
378 CHECK(method != nullptr) << "Direct method not found: "
379 << class_name << "." << method_name << signature;
380 CompileMethod(method);
381}
382
Andreas Gampe5a4b8a22014-09-11 08:30:08 -0700383void CommonCompilerTest::CompileVirtualMethod(Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierbf99f772014-08-23 16:37:27 -0700384 const char* class_name, const char* method_name,
385 const char* signature) {
Ian Rogerse63db272014-07-15 15:36:11 -0700386 std::string class_descriptor(DotToDescriptor(class_name));
387 Thread* self = Thread::Current();
388 mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
389 CHECK(klass != nullptr) << "Class not found " << class_name;
390 mirror::ArtMethod* method = klass->FindVirtualMethod(method_name, signature);
391 CHECK(method != NULL) << "Virtual method not found: "
392 << class_name << "." << method_name << signature;
393 CompileMethod(method);
394}
395
396void CommonCompilerTest::ReserveImageSpace() {
397 // Reserve where the image will be loaded up front so that other parts of test set up don't
398 // accidentally end up colliding with the fixed memory address when we need to load the image.
399 std::string error_msg;
400 image_reservation_.reset(MemMap::MapAnonymous("image reservation",
Ian Rogers13735952014-10-08 12:43:28 -0700401 reinterpret_cast<uint8_t*>(ART_BASE_ADDRESS),
Ian Rogerse63db272014-07-15 15:36:11 -0700402 (size_t)100 * 1024 * 1024, // 100MB
403 PROT_NONE,
404 false /* no need for 4gb flag with fixed mmap*/,
405 &error_msg));
406 CHECK(image_reservation_.get() != nullptr) << error_msg;
407}
408
409void CommonCompilerTest::UnreserveImageSpace() {
410 image_reservation_.reset();
411}
412
413} // namespace art