blob: fdf09a50a641fce9f2da62a9107b6b058670875d [file] [log] [blame]
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -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 */
16
17#ifndef ART_COMPILER_COMMON_COMPILER_TEST_H_
18#define ART_COMPILER_COMMON_COMPILER_TEST_H_
19
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000020#include "compiler.h"
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -080021#include "compiler_callbacks.h"
22#include "common_runtime_test.h"
23#include "dex/quick/dex_file_to_method_inliner_map.h"
24#include "dex/verification_results.h"
25#include "driver/compiler_callbacks_impl.h"
26#include "driver/compiler_driver.h"
27#include "driver/compiler_options.h"
28
29namespace art {
30
31#if defined(__arm__)
32
33#include <sys/ucontext.h>
34
35// A signal handler called when have an illegal instruction. We record the fact in
36// a global boolean and then increment the PC in the signal context to return to
37// the next instruction. We know the instruction is an sdiv (4 bytes long).
Ian Rogers719d1a32014-03-06 12:13:39 -080038static inline void baddivideinst(int signo, siginfo *si, void *data) {
39 UNUSED(signo);
40 UNUSED(si);
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -080041 struct ucontext *uc = (struct ucontext *)data;
42 struct sigcontext *sc = &uc->uc_mcontext;
43 sc->arm_r0 = 0; // set R0 to #0 to signal error
44 sc->arm_pc += 4; // skip offending instruction
45}
46
47// This is in arch/arm/arm_sdiv.S. It does the following:
48// mov r1,#1
49// sdiv r0,r1,r1
50// bx lr
51//
52// the result will be the value 1 if sdiv is supported. If it is not supported
53// a SIGILL signal will be raised and the signal handler (baddivideinst) called.
54// The signal handler sets r0 to #0 and then increments pc beyond the failed instruction.
55// Thus if the instruction is not supported, the result of this function will be #0
56
57extern "C" bool CheckForARMSDIVInstruction();
58
Ian Rogers719d1a32014-03-06 12:13:39 -080059static inline InstructionSetFeatures GuessInstructionFeatures() {
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -080060 InstructionSetFeatures f;
61
62 // Uncomment this for processing of /proc/cpuinfo.
63 if (false) {
64 // Look in /proc/cpuinfo for features we need. Only use this when we can guarantee that
65 // the kernel puts the appropriate feature flags in here. Sometimes it doesn't.
66 std::ifstream in("/proc/cpuinfo");
67 if (in) {
68 while (!in.eof()) {
69 std::string line;
70 std::getline(in, line);
71 if (!in.eof()) {
72 if (line.find("Features") != std::string::npos) {
73 if (line.find("idivt") != std::string::npos) {
74 f.SetHasDivideInstruction(true);
75 }
76 }
77 }
78 in.close();
79 }
80 } else {
81 LOG(INFO) << "Failed to open /proc/cpuinfo";
82 }
83 }
84
85 // See if have a sdiv instruction. Register a signal handler and try to execute
86 // an sdiv instruction. If we get a SIGILL then it's not supported. We can't use
87 // the /proc/cpuinfo method for this because Krait devices don't always put the idivt
88 // feature in the list.
89 struct sigaction sa, osa;
90 sa.sa_flags = SA_ONSTACK | SA_RESTART | SA_SIGINFO;
91 sa.sa_sigaction = baddivideinst;
92 sigaction(SIGILL, &sa, &osa);
93
94 if (CheckForARMSDIVInstruction()) {
95 f.SetHasDivideInstruction(true);
96 }
97
98 // Restore the signal handler.
99 sigaction(SIGILL, &osa, nullptr);
100
101 // Other feature guesses in here.
102 return f;
103}
104
105#endif
106
107// Given a set of instruction features from the build, parse it. The
108// input 'str' is a comma separated list of feature names. Parse it and
109// return the InstructionSetFeatures object.
Ian Rogers719d1a32014-03-06 12:13:39 -0800110static inline InstructionSetFeatures ParseFeatureList(std::string str) {
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800111 InstructionSetFeatures result;
112 typedef std::vector<std::string> FeatureList;
113 FeatureList features;
114 Split(str, ',', features);
115 for (FeatureList::iterator i = features.begin(); i != features.end(); i++) {
116 std::string feature = Trim(*i);
117 if (feature == "default") {
118 // Nothing to do.
119 } else if (feature == "div") {
120 // Supports divide instruction.
121 result.SetHasDivideInstruction(true);
122 } else if (feature == "nodiv") {
123 // Turn off support for divide instruction.
124 result.SetHasDivideInstruction(false);
125 } else {
126 LOG(FATAL) << "Unknown instruction set feature: '" << feature << "'";
127 }
128 }
129 // Others...
130 return result;
131}
132
133class CommonCompilerTest : public CommonRuntimeTest {
134 public:
135 static void MakeExecutable(const std::vector<uint8_t>& code) {
136 CHECK_NE(code.size(), 0U);
137 MakeExecutable(&code[0], code.size());
138 }
139
140 // Create an OatMethod based on pointers (for unit tests).
141 OatFile::OatMethod CreateOatMethod(const void* code,
142 const size_t frame_size_in_bytes,
143 const uint32_t core_spill_mask,
144 const uint32_t fp_spill_mask,
145 const uint8_t* mapping_table,
146 const uint8_t* vmap_table,
147 const uint8_t* gc_map) {
148 const byte* base;
149 uint32_t code_offset, mapping_table_offset, vmap_table_offset, gc_map_offset;
150 if (mapping_table == nullptr && vmap_table == nullptr && gc_map == nullptr) {
151 base = reinterpret_cast<const byte*>(code); // Base of data points at code.
152 base -= kPointerSize; // Move backward so that code_offset != 0.
153 code_offset = kPointerSize;
154 mapping_table_offset = 0;
155 vmap_table_offset = 0;
156 gc_map_offset = 0;
157 } else {
158 // TODO: 64bit support.
159 base = nullptr; // Base of data in oat file, ie 0.
160 code_offset = PointerToLowMemUInt32(code);
161 mapping_table_offset = PointerToLowMemUInt32(mapping_table);
162 vmap_table_offset = PointerToLowMemUInt32(vmap_table);
163 gc_map_offset = PointerToLowMemUInt32(gc_map);
164 }
165 return OatFile::OatMethod(base,
166 code_offset,
167 frame_size_in_bytes,
168 core_spill_mask,
169 fp_spill_mask,
170 mapping_table_offset,
171 vmap_table_offset,
172 gc_map_offset);
173 }
174
175 void MakeExecutable(mirror::ArtMethod* method) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
176 CHECK(method != nullptr);
177
178 const CompiledMethod* compiled_method = nullptr;
179 if (!method->IsAbstract()) {
180 mirror::DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
181 const DexFile& dex_file = *dex_cache->GetDexFile();
182 compiled_method =
183 compiler_driver_->GetCompiledMethod(MethodReference(&dex_file,
184 method->GetDexMethodIndex()));
185 }
186 if (compiled_method != nullptr) {
187 const std::vector<uint8_t>* code = compiled_method->GetQuickCode();
188 if (code == nullptr) {
189 code = compiled_method->GetPortableCode();
190 }
191 MakeExecutable(*code);
192 const void* method_code = CompiledMethod::CodePointer(&(*code)[0],
193 compiled_method->GetInstructionSet());
194 LOG(INFO) << "MakeExecutable " << PrettyMethod(method) << " code=" << method_code;
195 OatFile::OatMethod oat_method = CreateOatMethod(method_code,
196 compiled_method->GetFrameSizeInBytes(),
197 compiled_method->GetCoreSpillMask(),
198 compiled_method->GetFpSpillMask(),
199 &compiled_method->GetMappingTable()[0],
200 &compiled_method->GetVmapTable()[0],
201 nullptr);
202 oat_method.LinkMethod(method);
203 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
204 } else {
205 // No code? You must mean to go into the interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -0800206 // Or the generic JNI...
Andreas Gampebf6b92a2014-03-05 16:11:04 -0800207 if (!method->IsNative()) {
208 const void* method_code = kUsePortableCompiler ? GetPortableToInterpreterBridge()
209 : GetQuickToInterpreterBridge();
210 OatFile::OatMethod oat_method = CreateOatMethod(method_code,
211 kStackAlignment,
212 0,
213 0,
214 nullptr,
215 nullptr,
216 nullptr);
217 oat_method.LinkMethod(method);
218 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
219 } else {
220 const void* method_code = GetQuickGenericJniTrampoline();
221 mirror::ArtMethod* callee_save_method = runtime_->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Andreas Gampe36fea8d2014-03-10 13:37:40 -0700222
223 // Compute Sirt size, as Sirt goes into frame
224 MethodHelper mh(method);
225 uint32_t sirt_refs = mh.GetNumberOfReferenceArgsWithoutReceiver() + 1;
226 uint32_t sirt_size = StackIndirectReferenceTable::SizeOf(sirt_refs);
227
Andreas Gampebf6b92a2014-03-05 16:11:04 -0800228 OatFile::OatMethod oat_method = CreateOatMethod(method_code,
Andreas Gampe36fea8d2014-03-10 13:37:40 -0700229 callee_save_method->GetFrameSizeInBytes() +
230 sirt_size,
Andreas Gampebf6b92a2014-03-05 16:11:04 -0800231 callee_save_method->GetCoreSpillMask(),
232 callee_save_method->GetFpSpillMask(),
233 nullptr,
234 nullptr,
235 nullptr);
236 oat_method.LinkMethod(method);
237 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
238 }
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800239 }
240 // Create bridges to transition between different kinds of compiled bridge.
241 if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
242 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
243 } else {
244 CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
245 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
246 method->SetIsPortableCompiled();
247 }
248 }
249
250 static void MakeExecutable(const void* code_start, size_t code_length) {
251 CHECK(code_start != nullptr);
252 CHECK_NE(code_length, 0U);
253 uintptr_t data = reinterpret_cast<uintptr_t>(code_start);
254 uintptr_t base = RoundDown(data, kPageSize);
255 uintptr_t limit = RoundUp(data + code_length, kPageSize);
256 uintptr_t len = limit - base;
257 int result = mprotect(reinterpret_cast<void*>(base), len, PROT_READ | PROT_WRITE | PROT_EXEC);
258 CHECK_EQ(result, 0);
259
260 // Flush instruction cache
261 // Only uses __builtin___clear_cache if GCC >= 4.3.3
262#if GCC_VERSION >= 40303
263 __builtin___clear_cache(reinterpret_cast<void*>(base), reinterpret_cast<void*>(base + len));
264#else
Ian Rogersb48b9eb2014-02-28 16:20:21 -0800265 LOG(WARNING) << "UNIMPLEMENTED: cache flush";
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800266#endif
267 }
268
269 void MakeExecutable(mirror::ClassLoader* class_loader, const char* class_name)
270 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
271 std::string class_descriptor(DotToDescriptor(class_name));
272 Thread* self = Thread::Current();
273 SirtRef<mirror::ClassLoader> loader(self, class_loader);
274 mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
275 CHECK(klass != nullptr) << "Class not found " << class_name;
276 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
277 MakeExecutable(klass->GetDirectMethod(i));
278 }
279 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
280 MakeExecutable(klass->GetVirtualMethod(i));
281 }
282 }
283
284 protected:
285 virtual void SetUp() {
286 CommonRuntimeTest::SetUp();
287 {
288 ScopedObjectAccess soa(Thread::Current());
289
290 InstructionSet instruction_set = kNone;
291
292 // Take the default set of instruction features from the build.
293 InstructionSetFeatures instruction_set_features =
Ian Rogers8afeb852014-04-02 14:55:49 -0700294 ParseFeatureList(Runtime::GetDefaultInstructionSetFeatures());
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800295
296#if defined(__arm__)
297 instruction_set = kThumb2;
298 InstructionSetFeatures runtime_features = GuessInstructionFeatures();
299
300 // for ARM, do a runtime check to make sure that the features we are passed from
301 // the build match the features we actually determine at runtime.
Serban Constantinescu75b91132014-04-09 18:39:10 +0100302 ASSERT_LE(instruction_set_features, runtime_features);
Stuart Monteithb95a5342014-03-12 13:32:32 +0000303#elif defined(__aarch64__)
304 instruction_set = kArm64;
305 // TODO: arm64 compilation support.
306 compiler_options_->SetCompilerFilter(CompilerOptions::kInterpretOnly);
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800307#elif defined(__mips__)
308 instruction_set = kMips;
309#elif defined(__i386__)
310 instruction_set = kX86;
311#elif defined(__x86_64__)
312 instruction_set = kX86_64;
313 // TODO: x86_64 compilation support.
Dmitry Petrochenko659d87d2014-02-27 14:23:11 +0700314 compiler_options_->SetCompilerFilter(CompilerOptions::kInterpretOnly);
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800315#endif
316
317 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
318 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
319 if (!runtime_->HasCalleeSaveMethod(type)) {
320 runtime_->SetCalleeSaveMethod(
321 runtime_->CreateCalleeSaveMethod(instruction_set, type), type);
322 }
323 }
324
325 // TODO: make selectable
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000326 Compiler::Kind compiler_kind
327 = (kUsePortableCompiler) ? Compiler::kPortable : Compiler::kQuick;
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800328 timer_.reset(new CumulativeLogger("Compilation times"));
329 compiler_driver_.reset(new CompilerDriver(compiler_options_.get(),
330 verification_results_.get(),
331 method_inliner_map_.get(),
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000332 compiler_kind, instruction_set,
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800333 instruction_set_features,
334 true, new CompilerDriver::DescriptorSet,
335 2, true, true, timer_.get()));
336 }
337 // We typically don't generate an image in unit tests, disable this optimization by default.
338 compiler_driver_->SetSupportBootImageFixup(false);
339 }
340
341 virtual void SetUpRuntimeOptions(Runtime::Options *options) {
342 CommonRuntimeTest::SetUpRuntimeOptions(options);
343
344 compiler_options_.reset(new CompilerOptions);
345 verification_results_.reset(new VerificationResults(compiler_options_.get()));
346 method_inliner_map_.reset(new DexFileToMethodInlinerMap);
347 callbacks_.reset(new CompilerCallbacksImpl(verification_results_.get(),
348 method_inliner_map_.get()));
349 options->push_back(std::make_pair("compilercallbacks", callbacks_.get()));
350 }
351
352 virtual void TearDown() {
353 timer_.reset();
354 compiler_driver_.reset();
355 callbacks_.reset();
356 method_inliner_map_.reset();
357 verification_results_.reset();
358 compiler_options_.reset();
359
360 CommonRuntimeTest::TearDown();
361 }
362
363 void CompileClass(mirror::ClassLoader* class_loader, const char* class_name)
364 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
365 std::string class_descriptor(DotToDescriptor(class_name));
366 Thread* self = Thread::Current();
367 SirtRef<mirror::ClassLoader> loader(self, class_loader);
368 mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
369 CHECK(klass != nullptr) << "Class not found " << class_name;
370 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
371 CompileMethod(klass->GetDirectMethod(i));
372 }
373 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
374 CompileMethod(klass->GetVirtualMethod(i));
375 }
376 }
377
378 void CompileMethod(mirror::ArtMethod* method) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
379 CHECK(method != nullptr);
380 TimingLogger timings("CommonTest::CompileMethod", false, false);
381 timings.StartSplit("CompileOne");
Ian Rogers3d504072014-03-01 09:16:49 -0800382 compiler_driver_->CompileOne(method, &timings);
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800383 MakeExecutable(method);
384 timings.EndSplit();
385 }
386
387 void CompileDirectMethod(SirtRef<mirror::ClassLoader>& class_loader, const char* class_name,
388 const char* method_name, const char* signature)
389 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
390 std::string class_descriptor(DotToDescriptor(class_name));
391 Thread* self = Thread::Current();
392 mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
393 CHECK(klass != nullptr) << "Class not found " << class_name;
394 mirror::ArtMethod* method = klass->FindDirectMethod(method_name, signature);
395 CHECK(method != nullptr) << "Direct method not found: "
396 << class_name << "." << method_name << signature;
397 CompileMethod(method);
398 }
399
400 void CompileVirtualMethod(SirtRef<mirror::ClassLoader>& class_loader, const char* class_name,
401 const char* method_name, const char* signature)
402 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
403 std::string class_descriptor(DotToDescriptor(class_name));
404 Thread* self = Thread::Current();
405 mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
406 CHECK(klass != nullptr) << "Class not found " << class_name;
407 mirror::ArtMethod* method = klass->FindVirtualMethod(method_name, signature);
408 CHECK(method != NULL) << "Virtual method not found: "
409 << class_name << "." << method_name << signature;
410 CompileMethod(method);
411 }
412
413 void ReserveImageSpace() {
414 // Reserve where the image will be loaded up front so that other parts of test set up don't
415 // accidentally end up colliding with the fixed memory address when we need to load the image.
416 std::string error_msg;
417 image_reservation_.reset(MemMap::MapAnonymous("image reservation",
418 reinterpret_cast<byte*>(ART_BASE_ADDRESS),
419 (size_t)100 * 1024 * 1024, // 100MB
420 PROT_NONE,
421 false /* no need for 4gb flag with fixed mmap*/,
422 &error_msg));
423 CHECK(image_reservation_.get() != nullptr) << error_msg;
424 }
425
426 void UnreserveImageSpace() {
427 image_reservation_.reset();
428 }
429
430 UniquePtr<CompilerOptions> compiler_options_;
431 UniquePtr<VerificationResults> verification_results_;
432 UniquePtr<DexFileToMethodInlinerMap> method_inliner_map_;
433 UniquePtr<CompilerCallbacksImpl> callbacks_;
434 UniquePtr<CompilerDriver> compiler_driver_;
435 UniquePtr<CumulativeLogger> timer_;
436
437 private:
438 UniquePtr<MemMap> image_reservation_;
439};
440
441} // namespace art
442
443#endif // ART_COMPILER_COMMON_COMPILER_TEST_H_