common_compiler_test.cc revision a5ca888d715cd0c6c421313211caa1928be3e399
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#include "arch/instruction_set_features.h"
20#include "class_linker.h"
21#include "compiled_method.h"
22#include "dex/pass_manager.h"
23#include "dex/quick_compiler_callbacks.h"
24#include "dex/quick/dex_file_to_method_inliner_map.h"
25#include "dex/verification_results.h"
26#include "driver/compiler_driver.h"
27#include "interpreter/interpreter.h"
28#include "mirror/art_method.h"
29#include "mirror/dex_cache.h"
30#include "mirror/object-inl.h"
31#include "scoped_thread_state_change.h"
32#include "thread-inl.h"
33#include "utils.h"
34
35namespace art {
36
37CommonCompilerTest::CommonCompilerTest() {}
38CommonCompilerTest::~CommonCompilerTest() {}
39
40void CommonCompilerTest::MakeExecutable(mirror::ArtMethod* method) {
41  CHECK(method != nullptr);
42
43  const CompiledMethod* compiled_method = nullptr;
44  if (!method->IsAbstract()) {
45    mirror::DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
46    const DexFile& dex_file = *dex_cache->GetDexFile();
47    compiled_method =
48        compiler_driver_->GetCompiledMethod(MethodReference(&dex_file,
49                                                            method->GetDexMethodIndex()));
50  }
51  if (compiled_method != nullptr) {
52    const SwapVector<uint8_t>* code = compiled_method->GetQuickCode();
53    uint32_t code_size = code->size();
54    CHECK_NE(0u, code_size);
55    const SwapVector<uint8_t>& vmap_table = compiled_method->GetVmapTable();
56    uint32_t vmap_table_offset = vmap_table.empty() ? 0u
57        : sizeof(OatQuickMethodHeader) + vmap_table.size();
58    const SwapVector<uint8_t>* mapping_table = compiled_method->GetMappingTable();
59    bool mapping_table_used = mapping_table != nullptr && !mapping_table->empty();
60    size_t mapping_table_size = mapping_table_used ? mapping_table->size() : 0U;
61    uint32_t mapping_table_offset = !mapping_table_used ? 0u
62        : sizeof(OatQuickMethodHeader) + vmap_table.size() + mapping_table_size;
63    const SwapVector<uint8_t>* gc_map = compiled_method->GetGcMap();
64    bool gc_map_used = gc_map != nullptr && !gc_map->empty();
65    size_t gc_map_size = gc_map_used ? gc_map->size() : 0U;
66    uint32_t gc_map_offset = !gc_map_used ? 0u
67        : sizeof(OatQuickMethodHeader) + vmap_table.size() + mapping_table_size + gc_map_size;
68    OatQuickMethodHeader method_header(mapping_table_offset, vmap_table_offset, gc_map_offset,
69                                       compiled_method->GetFrameSizeInBytes(),
70                                       compiled_method->GetCoreSpillMask(),
71                                       compiled_method->GetFpSpillMask(), code_size);
72
73    header_code_and_maps_chunks_.push_back(std::vector<uint8_t>());
74    std::vector<uint8_t>* chunk = &header_code_and_maps_chunks_.back();
75    size_t size = sizeof(method_header) + code_size + vmap_table.size() + mapping_table_size +
76        gc_map_size;
77    size_t code_offset = compiled_method->AlignCode(size - code_size);
78    size_t padding = code_offset - (size - code_size);
79    chunk->reserve(padding + size);
80    chunk->resize(sizeof(method_header));
81    memcpy(&(*chunk)[0], &method_header, sizeof(method_header));
82    chunk->insert(chunk->begin(), vmap_table.begin(), vmap_table.end());
83    if (mapping_table_used) {
84      chunk->insert(chunk->begin(), mapping_table->begin(), mapping_table->end());
85    }
86    if (gc_map_used) {
87      chunk->insert(chunk->begin(), gc_map->begin(), gc_map->end());
88    }
89    chunk->insert(chunk->begin(), padding, 0);
90    chunk->insert(chunk->end(), code->begin(), code->end());
91    CHECK_EQ(padding + size, chunk->size());
92    const void* code_ptr = &(*chunk)[code_offset];
93    MakeExecutable(code_ptr, code->size());
94    const void* method_code = CompiledMethod::CodePointer(code_ptr,
95                                                          compiled_method->GetInstructionSet());
96    LOG(INFO) << "MakeExecutable " << PrettyMethod(method) << " code=" << method_code;
97    class_linker_->SetEntryPointsToCompiledCode(method, method_code);
98  } else {
99    // No code? You must mean to go into the interpreter.
100    // Or the generic JNI...
101    class_linker_->SetEntryPointsToInterpreter(method);
102  }
103}
104
105void CommonCompilerTest::MakeExecutable(const void* code_start, size_t code_length) {
106  CHECK(code_start != nullptr);
107  CHECK_NE(code_length, 0U);
108  uintptr_t data = reinterpret_cast<uintptr_t>(code_start);
109  uintptr_t base = RoundDown(data, kPageSize);
110  uintptr_t limit = RoundUp(data + code_length, kPageSize);
111  uintptr_t len = limit - base;
112  int result = mprotect(reinterpret_cast<void*>(base), len, PROT_READ | PROT_WRITE | PROT_EXEC);
113  CHECK_EQ(result, 0);
114
115  // Flush instruction cache
116  // Only uses __builtin___clear_cache if GCC >= 4.3.3
117#if GCC_VERSION >= 40303
118  __builtin___clear_cache(reinterpret_cast<void*>(base), reinterpret_cast<void*>(base + len));
119#else
120  // Only warn if not Intel as Intel doesn't have cache flush instructions.
121#if !defined(__i386__) && !defined(__x86_64__)
122  UNIMPLEMENTED(WARNING) << "cache flush";
123#endif
124#endif
125}
126
127void CommonCompilerTest::MakeExecutable(mirror::ClassLoader* class_loader, const char* class_name) {
128  std::string class_descriptor(DotToDescriptor(class_name));
129  Thread* self = Thread::Current();
130  StackHandleScope<1> hs(self);
131  Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
132  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
133  CHECK(klass != nullptr) << "Class not found " << class_name;
134  for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
135    MakeExecutable(klass->GetDirectMethod(i));
136  }
137  for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
138    MakeExecutable(klass->GetVirtualMethod(i));
139  }
140}
141
142void CommonCompilerTest::SetUp() {
143  CommonRuntimeTest::SetUp();
144  {
145    ScopedObjectAccess soa(Thread::Current());
146
147    const InstructionSet instruction_set = kRuntimeISA;
148    // Take the default set of instruction features from the build.
149    instruction_set_features_.reset(InstructionSetFeatures::FromCppDefines());
150
151    runtime_->SetInstructionSet(instruction_set);
152    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
153      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
154      if (!runtime_->HasCalleeSaveMethod(type)) {
155        runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
156      }
157    }
158
159    // TODO: make selectable
160    Compiler::Kind compiler_kind = Compiler::kQuick;
161    timer_.reset(new CumulativeLogger("Compilation times"));
162    compiler_driver_.reset(new CompilerDriver(compiler_options_.get(),
163                                              verification_results_.get(),
164                                              method_inliner_map_.get(),
165                                              compiler_kind, instruction_set,
166                                              instruction_set_features_.get(),
167                                              true, new std::set<std::string>, nullptr,
168                                              2, true, true, "", timer_.get(), -1, ""));
169  }
170  // We typically don't generate an image in unit tests, disable this optimization by default.
171  compiler_driver_->SetSupportBootImageFixup(false);
172}
173
174void CommonCompilerTest::SetUpRuntimeOptions(RuntimeOptions* options) {
175  CommonRuntimeTest::SetUpRuntimeOptions(options);
176
177  compiler_options_.reset(new CompilerOptions);
178  verification_results_.reset(new VerificationResults(compiler_options_.get()));
179  method_inliner_map_.reset(new DexFileToMethodInlinerMap);
180  callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(),
181                                              method_inliner_map_.get()));
182  options->push_back(std::make_pair("compilercallbacks", callbacks_.get()));
183}
184
185void CommonCompilerTest::TearDown() {
186  timer_.reset();
187  compiler_driver_.reset();
188  callbacks_.reset();
189  method_inliner_map_.reset();
190  verification_results_.reset();
191  compiler_options_.reset();
192
193  CommonRuntimeTest::TearDown();
194}
195
196void CommonCompilerTest::CompileClass(mirror::ClassLoader* class_loader, const char* class_name) {
197  std::string class_descriptor(DotToDescriptor(class_name));
198  Thread* self = Thread::Current();
199  StackHandleScope<1> hs(self);
200  Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
201  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
202  CHECK(klass != nullptr) << "Class not found " << class_name;
203  for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
204    CompileMethod(klass->GetDirectMethod(i));
205  }
206  for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
207    CompileMethod(klass->GetVirtualMethod(i));
208  }
209}
210
211void CommonCompilerTest::CompileMethod(mirror::ArtMethod* method) {
212  CHECK(method != nullptr);
213  TimingLogger timings("CommonTest::CompileMethod", false, false);
214  TimingLogger::ScopedTiming t(__FUNCTION__, &timings);
215  compiler_driver_->CompileOne(method, &timings);
216  TimingLogger::ScopedTiming t2("MakeExecutable", &timings);
217  MakeExecutable(method);
218}
219
220void CommonCompilerTest::CompileDirectMethod(Handle<mirror::ClassLoader> class_loader,
221                                             const char* class_name, const char* method_name,
222                                             const char* signature) {
223  std::string class_descriptor(DotToDescriptor(class_name));
224  Thread* self = Thread::Current();
225  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
226  CHECK(klass != nullptr) << "Class not found " << class_name;
227  mirror::ArtMethod* method = klass->FindDirectMethod(method_name, signature);
228  CHECK(method != nullptr) << "Direct method not found: "
229      << class_name << "." << method_name << signature;
230  CompileMethod(method);
231}
232
233void CommonCompilerTest::CompileVirtualMethod(Handle<mirror::ClassLoader> class_loader,
234                                              const char* class_name, const char* method_name,
235                                              const char* signature) {
236  std::string class_descriptor(DotToDescriptor(class_name));
237  Thread* self = Thread::Current();
238  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
239  CHECK(klass != nullptr) << "Class not found " << class_name;
240  mirror::ArtMethod* method = klass->FindVirtualMethod(method_name, signature);
241  CHECK(method != NULL) << "Virtual method not found: "
242      << class_name << "." << method_name << signature;
243  CompileMethod(method);
244}
245
246void CommonCompilerTest::ReserveImageSpace() {
247  // Reserve where the image will be loaded up front so that other parts of test set up don't
248  // accidentally end up colliding with the fixed memory address when we need to load the image.
249  std::string error_msg;
250  MemMap::Init();
251  image_reservation_.reset(MemMap::MapAnonymous("image reservation",
252                                                reinterpret_cast<uint8_t*>(ART_BASE_ADDRESS),
253                                                (size_t)100 * 1024 * 1024,  // 100MB
254                                                PROT_NONE,
255                                                false /* no need for 4gb flag with fixed mmap*/,
256                                                &error_msg));
257  CHECK(image_reservation_.get() != nullptr) << error_msg;
258}
259
260void CommonCompilerTest::UnreserveImageSpace() {
261  image_reservation_.reset();
262}
263
264}  // namespace art
265