common_compiler_test.cc revision 4cdf4508903d13fd0f9fba5690aeac1b368db81b
1/*
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) {
146  CHECK(code != nullptr);
147  const byte* base = reinterpret_cast<const byte*>(code);  // Base of data points at code.
148  base -= kPointerSize;  // Move backward so that code_offset != 0.
149  uint32_t code_offset = kPointerSize;
150  return OatFile::OatMethod(base, code_offset);
151}
152
153void CommonCompilerTest::MakeExecutable(mirror::ArtMethod* method) {
154  CHECK(method != nullptr);
155
156  const CompiledMethod* compiled_method = nullptr;
157  if (!method->IsAbstract()) {
158    mirror::DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
159    const DexFile& dex_file = *dex_cache->GetDexFile();
160    compiled_method =
161        compiler_driver_->GetCompiledMethod(MethodReference(&dex_file,
162                                                            method->GetDexMethodIndex()));
163  }
164  if (compiled_method != nullptr) {
165    const std::vector<uint8_t>* code = compiled_method->GetQuickCode();
166    const void* code_ptr;
167    if (code != nullptr) {
168      uint32_t code_size = code->size();
169      CHECK_NE(0u, code_size);
170      const std::vector<uint8_t>& vmap_table = compiled_method->GetVmapTable();
171      uint32_t vmap_table_offset = vmap_table.empty() ? 0u
172          : sizeof(OatQuickMethodHeader) + vmap_table.size();
173      const std::vector<uint8_t>& mapping_table = compiled_method->GetMappingTable();
174      uint32_t mapping_table_offset = mapping_table.empty() ? 0u
175          : sizeof(OatQuickMethodHeader) + vmap_table.size() + mapping_table.size();
176      const std::vector<uint8_t>& gc_map = compiled_method->GetGcMap();
177      uint32_t gc_map_offset = gc_map.empty() ? 0u
178          : sizeof(OatQuickMethodHeader) + vmap_table.size() + mapping_table.size() + gc_map.size();
179      OatQuickMethodHeader method_header(mapping_table_offset, vmap_table_offset, gc_map_offset,
180                                         compiled_method->GetFrameSizeInBytes(),
181                                         compiled_method->GetCoreSpillMask(),
182                                         compiled_method->GetFpSpillMask(), code_size);
183
184      header_code_and_maps_chunks_.push_back(std::vector<uint8_t>());
185      std::vector<uint8_t>* chunk = &header_code_and_maps_chunks_.back();
186      size_t size = sizeof(method_header) + code_size + vmap_table.size() + mapping_table.size() +
187          gc_map.size();
188      size_t code_offset = compiled_method->AlignCode(size - code_size);
189      size_t padding = code_offset - (size - code_size);
190      chunk->reserve(padding + size);
191      chunk->resize(sizeof(method_header));
192      memcpy(&(*chunk)[0], &method_header, sizeof(method_header));
193      chunk->insert(chunk->begin(), vmap_table.begin(), vmap_table.end());
194      chunk->insert(chunk->begin(), mapping_table.begin(), mapping_table.end());
195      chunk->insert(chunk->begin(), gc_map.begin(), gc_map.end());
196      chunk->insert(chunk->begin(), padding, 0);
197      chunk->insert(chunk->end(), code->begin(), code->end());
198      CHECK_EQ(padding + size, chunk->size());
199      code_ptr = &(*chunk)[code_offset];
200    } else {
201      code = compiled_method->GetPortableCode();
202      code_ptr = &(*code)[0];
203    }
204    MakeExecutable(code_ptr, code->size());
205    const void* method_code = CompiledMethod::CodePointer(code_ptr,
206                                                          compiled_method->GetInstructionSet());
207    LOG(INFO) << "MakeExecutable " << PrettyMethod(method) << " code=" << method_code;
208    OatFile::OatMethod oat_method = CreateOatMethod(method_code);
209    oat_method.LinkMethod(method);
210    method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
211  } else {
212    // No code? You must mean to go into the interpreter.
213    // Or the generic JNI...
214    if (!method->IsNative()) {
215#if defined(ART_USE_PORTABLE_COMPILER)
216      const void* method_code = GetPortableToInterpreterBridge();
217#else
218      const void* method_code = GetQuickToInterpreterBridge();
219#endif
220      OatFile::OatMethod oat_method = CreateOatMethod(method_code);
221      oat_method.LinkMethod(method);
222      method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
223    } else {
224      const void* method_code = reinterpret_cast<void*>(art_quick_generic_jni_trampoline);
225
226      OatFile::OatMethod oat_method = CreateOatMethod(method_code);
227      oat_method.LinkMethod(method);
228      method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
229    }
230  }
231  // Create bridges to transition between different kinds of compiled bridge.
232#if defined(ART_USE_PORTABLE_COMPILER)
233  if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
234    method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
235  } else {
236    CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
237    method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
238    method->SetIsPortableCompiled();
239  }
240#else
241  CHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
242#endif
243}
244
245void CommonCompilerTest::MakeExecutable(const void* code_start, size_t code_length) {
246  CHECK(code_start != nullptr);
247  CHECK_NE(code_length, 0U);
248  uintptr_t data = reinterpret_cast<uintptr_t>(code_start);
249  uintptr_t base = RoundDown(data, kPageSize);
250  uintptr_t limit = RoundUp(data + code_length, kPageSize);
251  uintptr_t len = limit - base;
252  int result = mprotect(reinterpret_cast<void*>(base), len, PROT_READ | PROT_WRITE | PROT_EXEC);
253  CHECK_EQ(result, 0);
254
255  // Flush instruction cache
256  // Only uses __builtin___clear_cache if GCC >= 4.3.3
257#if GCC_VERSION >= 40303
258  __builtin___clear_cache(reinterpret_cast<void*>(base), reinterpret_cast<void*>(base + len));
259#else
260  // Only warn if not Intel as Intel doesn't have cache flush instructions.
261#if !defined(__i386__) && !defined(__x86_64__)
262  LOG(WARNING) << "UNIMPLEMENTED: cache flush";
263#endif
264#endif
265}
266
267void CommonCompilerTest::MakeExecutable(mirror::ClassLoader* class_loader, const char* class_name) {
268  std::string class_descriptor(DotToDescriptor(class_name));
269  Thread* self = Thread::Current();
270  StackHandleScope<1> hs(self);
271  Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
272  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
273  CHECK(klass != nullptr) << "Class not found " << class_name;
274  for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
275    MakeExecutable(klass->GetDirectMethod(i));
276  }
277  for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
278    MakeExecutable(klass->GetVirtualMethod(i));
279  }
280}
281
282void CommonCompilerTest::SetUp() {
283  CommonRuntimeTest::SetUp();
284  {
285    ScopedObjectAccess soa(Thread::Current());
286
287    InstructionSet instruction_set = kRuntimeISA;
288
289    // Take the default set of instruction features from the build.
290    InstructionSetFeatures instruction_set_features =
291        ParseFeatureList(Runtime::GetDefaultInstructionSetFeatures());
292
293#if defined(__arm__)
294    InstructionSetFeatures runtime_features = GuessInstructionFeatures();
295
296    // for ARM, do a runtime check to make sure that the features we are passed from
297    // the build match the features we actually determine at runtime.
298    ASSERT_LE(instruction_set_features, runtime_features);
299#endif
300
301    runtime_->SetInstructionSet(instruction_set);
302    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
303      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
304      if (!runtime_->HasCalleeSaveMethod(type)) {
305        runtime_->SetCalleeSaveMethod(
306            runtime_->CreateCalleeSaveMethod(type), type);
307      }
308    }
309
310    // TODO: make selectable
311    Compiler::Kind compiler_kind
312    = (kUsePortableCompiler) ? Compiler::kPortable : Compiler::kQuick;
313    timer_.reset(new CumulativeLogger("Compilation times"));
314    compiler_driver_.reset(new CompilerDriver(compiler_options_.get(),
315                                              verification_results_.get(),
316                                              method_inliner_map_.get(),
317                                              compiler_kind, instruction_set,
318                                              instruction_set_features,
319                                              true, new std::set<std::string>, nullptr,
320                                              2, true, true, timer_.get()));
321  }
322  // We typically don't generate an image in unit tests, disable this optimization by default.
323  compiler_driver_->SetSupportBootImageFixup(false);
324}
325
326void CommonCompilerTest::SetUpRuntimeOptions(RuntimeOptions* options) {
327  CommonRuntimeTest::SetUpRuntimeOptions(options);
328
329  compiler_options_.reset(new CompilerOptions);
330  verification_results_.reset(new VerificationResults(compiler_options_.get()));
331  method_inliner_map_.reset(new DexFileToMethodInlinerMap);
332  callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(),
333                                              method_inliner_map_.get()));
334  options->push_back(std::make_pair("compilercallbacks", callbacks_.get()));
335}
336
337void CommonCompilerTest::TearDown() {
338  timer_.reset();
339  compiler_driver_.reset();
340  callbacks_.reset();
341  method_inliner_map_.reset();
342  verification_results_.reset();
343  compiler_options_.reset();
344
345  CommonRuntimeTest::TearDown();
346}
347
348void CommonCompilerTest::CompileClass(mirror::ClassLoader* class_loader, const char* class_name) {
349  std::string class_descriptor(DotToDescriptor(class_name));
350  Thread* self = Thread::Current();
351  StackHandleScope<1> hs(self);
352  Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
353  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
354  CHECK(klass != nullptr) << "Class not found " << class_name;
355  for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
356    CompileMethod(klass->GetDirectMethod(i));
357  }
358  for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
359    CompileMethod(klass->GetVirtualMethod(i));
360  }
361}
362
363void CommonCompilerTest::CompileMethod(mirror::ArtMethod* method) {
364  CHECK(method != nullptr);
365  TimingLogger timings("CommonTest::CompileMethod", false, false);
366  TimingLogger::ScopedTiming t(__FUNCTION__, &timings);
367  compiler_driver_->CompileOne(method, &timings);
368  TimingLogger::ScopedTiming t2("MakeExecutable", &timings);
369  MakeExecutable(method);
370}
371
372void CommonCompilerTest::CompileDirectMethod(Handle<mirror::ClassLoader> class_loader,
373                                             const char* class_name, const char* method_name,
374                                             const char* signature) {
375  std::string class_descriptor(DotToDescriptor(class_name));
376  Thread* self = Thread::Current();
377  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
378  CHECK(klass != nullptr) << "Class not found " << class_name;
379  mirror::ArtMethod* method = klass->FindDirectMethod(method_name, signature);
380  CHECK(method != nullptr) << "Direct method not found: "
381      << class_name << "." << method_name << signature;
382  CompileMethod(method);
383}
384
385void CommonCompilerTest::CompileVirtualMethod(Handle<mirror::ClassLoader> class_loader, const char* class_name,
386                                              const char* method_name, const char* signature)
387SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
388  std::string class_descriptor(DotToDescriptor(class_name));
389  Thread* self = Thread::Current();
390  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
391  CHECK(klass != nullptr) << "Class not found " << class_name;
392  mirror::ArtMethod* method = klass->FindVirtualMethod(method_name, signature);
393  CHECK(method != NULL) << "Virtual method not found: "
394      << class_name << "." << method_name << signature;
395  CompileMethod(method);
396}
397
398void CommonCompilerTest::ReserveImageSpace() {
399  // Reserve where the image will be loaded up front so that other parts of test set up don't
400  // accidentally end up colliding with the fixed memory address when we need to load the image.
401  std::string error_msg;
402  MemMap::Init();
403  image_reservation_.reset(MemMap::MapAnonymous("image reservation",
404                                                reinterpret_cast<byte*>(ART_BASE_ADDRESS),
405                                                (size_t)100 * 1024 * 1024,  // 100MB
406                                                PROT_NONE,
407                                                false /* no need for 4gb flag with fixed mmap*/,
408                                                &error_msg));
409  CHECK(image_reservation_.get() != nullptr) << error_msg;
410}
411
412void CommonCompilerTest::UnreserveImageSpace() {
413  image_reservation_.reset();
414}
415
416}  // namespace art
417