1 /*
2  * Copyright (C) 2012 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 "compiler_llvm.h"
18 
19 #include "backend_options.h"
20 #include "base/stl_util.h"
21 #include "class_linker.h"
22 #include "compiled_method.h"
23 #include "dex/verification_results.h"
24 #include "dex/verified_method.h"
25 #include "driver/compiler_driver.h"
26 #include "driver/dex_compilation_unit.h"
27 #include "globals.h"
28 #include "ir_builder.h"
29 #include "jni/portable/jni_compiler.h"
30 #include "llvm_compilation_unit.h"
31 #include "thread-inl.h"
32 #include "utils_llvm.h"
33 #include "verifier/method_verifier.h"
34 
35 #include <llvm/LinkAllPasses.h>
36 #include <llvm/Support/ManagedStatic.h>
37 #include <llvm/Support/TargetSelect.h>
38 #include <llvm/Support/Threading.h>
39 
40 namespace art {
41 void CompileOneMethod(CompilerDriver& driver,
42                       Compiler* compiler,
43                       const DexFile::CodeItem* code_item,
44                       uint32_t access_flags, InvokeType invoke_type,
45                       uint16_t class_def_idx, uint32_t method_idx, jobject class_loader,
46                       const DexFile& dex_file,
47                       void* llvm_info);
48 }
49 
50 namespace llvm {
51   extern bool TimePassesIsEnabled;
52 }
53 
54 namespace {
55 
56 pthread_once_t llvm_initialized = PTHREAD_ONCE_INIT;
57 
InitializeLLVM()58 void InitializeLLVM() {
59   // Initialize LLVM internal data structure for multithreading
60   llvm::llvm_start_multithreaded();
61 
62   // NOTE: Uncomment following line to show the time consumption of LLVM passes
63   // llvm::TimePassesIsEnabled = true;
64 
65   // Initialize LLVM target-specific options.
66   art::llvm::InitialBackendOptions();
67 
68   // Initialize LLVM target, MC subsystem, asm printer, and asm parser.
69   if (art::kIsTargetBuild) {
70     // Don't initialize all targets on device. Just initialize the device's native target
71     llvm::InitializeNativeTarget();
72     llvm::InitializeNativeTargetAsmPrinter();
73     llvm::InitializeNativeTargetAsmParser();
74   } else {
75     llvm::InitializeAllTargets();
76     llvm::InitializeAllTargetMCs();
77     llvm::InitializeAllAsmPrinters();
78     llvm::InitializeAllAsmParsers();
79   }
80 
81   // Initialize LLVM optimization passes
82   llvm::PassRegistry &registry = *llvm::PassRegistry::getPassRegistry();
83 
84   llvm::initializeCore(registry);
85   llvm::initializeScalarOpts(registry);
86   llvm::initializeIPO(registry);
87   llvm::initializeAnalysis(registry);
88   llvm::initializeIPA(registry);
89   llvm::initializeTransformUtils(registry);
90   llvm::initializeInstCombine(registry);
91   llvm::initializeInstrumentation(registry);
92   llvm::initializeTarget(registry);
93 }
94 
95 // The Guard to Shutdown LLVM
96 // llvm::llvm_shutdown_obj llvm_guard;
97 // TODO: We are commenting out this line because this will cause SEGV from
98 // time to time.
99 // Two reasons: (1) the order of the destruction of static objects, or
100 //              (2) dlopen/dlclose side-effect on static objects.
101 
102 }  // anonymous namespace
103 
104 
105 namespace art {
106 namespace llvm {
107 
108 
109 ::llvm::Module* makeLLVMModuleContents(::llvm::Module* module);
110 
111 
CompilerLLVM(CompilerDriver * driver,InstructionSet insn_set)112 CompilerLLVM::CompilerLLVM(CompilerDriver* driver, InstructionSet insn_set)
113     : compiler_driver_(driver), insn_set_(insn_set),
114       next_cunit_id_lock_("compilation unit id lock"), next_cunit_id_(1) {
115 
116   // Initialize LLVM libraries
117   pthread_once(&llvm_initialized, InitializeLLVM);
118 }
119 
120 
~CompilerLLVM()121 CompilerLLVM::~CompilerLLVM() {
122 }
123 
124 
AllocateCompilationUnit()125 LlvmCompilationUnit* CompilerLLVM::AllocateCompilationUnit() {
126   MutexLock GUARD(Thread::Current(), next_cunit_id_lock_);
127   LlvmCompilationUnit* cunit = new LlvmCompilationUnit(this, next_cunit_id_++);
128   if (!bitcode_filename_.empty()) {
129     cunit->SetBitcodeFileName(StringPrintf("%s-%u",
130                                            bitcode_filename_.c_str(),
131                                            cunit->GetCompilationUnitId()));
132   }
133   return cunit;
134 }
135 
136 
137 CompiledMethod* CompilerLLVM::
CompileDexMethod(DexCompilationUnit * dex_compilation_unit,InvokeType invoke_type)138 CompileDexMethod(DexCompilationUnit* dex_compilation_unit, InvokeType invoke_type) {
139   std::unique_ptr<LlvmCompilationUnit> cunit(AllocateCompilationUnit());
140 
141   cunit->SetDexCompilationUnit(dex_compilation_unit);
142   cunit->SetCompilerDriver(compiler_driver_);
143   // TODO: consolidate ArtCompileMethods
144   CompileOneMethod(*compiler_driver_,
145                    compiler_driver_->GetCompiler(),
146                    dex_compilation_unit->GetCodeItem(),
147                    dex_compilation_unit->GetAccessFlags(),
148                    invoke_type,
149                    dex_compilation_unit->GetClassDefIndex(),
150                    dex_compilation_unit->GetDexMethodIndex(),
151                    dex_compilation_unit->GetClassLoader(),
152                    *dex_compilation_unit->GetDexFile(),
153                    cunit.get());
154 
155   cunit->Materialize();
156 
157   return new CompiledMethod(*compiler_driver_, compiler_driver_->GetInstructionSet(),
158                             cunit->GetElfObject(),
159                             dex_compilation_unit->GetVerifiedMethod()->GetDexGcMap(),
160                             cunit->GetDexCompilationUnit()->GetSymbol());
161 }
162 
163 
164 CompiledMethod* CompilerLLVM::
CompileNativeMethod(DexCompilationUnit * dex_compilation_unit)165 CompileNativeMethod(DexCompilationUnit* dex_compilation_unit) {
166   std::unique_ptr<LlvmCompilationUnit> cunit(AllocateCompilationUnit());
167 
168   std::unique_ptr<JniCompiler> jni_compiler(
169       new JniCompiler(cunit.get(), compiler_driver_, dex_compilation_unit));
170 
171   return jni_compiler->Compile();
172 }
173 
174 
175 }  // namespace llvm
176 }  // namespace art
177 
ContextOf(art::CompilerDriver * driver)178 static art::llvm::CompilerLLVM* ContextOf(art::CompilerDriver* driver) {
179   void *compiler_context = driver->GetCompilerContext();
180   CHECK(compiler_context != NULL);
181   return reinterpret_cast<art::llvm::CompilerLLVM*>(compiler_context);
182 }
183 
ContextOf(const art::CompilerDriver & driver)184 static art::llvm::CompilerLLVM* ContextOf(const art::CompilerDriver& driver) {
185   void *compiler_context = driver.GetCompilerContext();
186   CHECK(compiler_context != NULL);
187   return reinterpret_cast<art::llvm::CompilerLLVM*>(compiler_context);
188 }
189 
ArtInitCompilerContext(art::CompilerDriver * driver)190 extern "C" void ArtInitCompilerContext(art::CompilerDriver* driver) {
191   CHECK(driver->GetCompilerContext() == nullptr);
192 
193   art::llvm::CompilerLLVM* compiler_llvm = new art::llvm::CompilerLLVM(driver,
194                                                                        driver->GetInstructionSet());
195 
196   driver->SetCompilerContext(compiler_llvm);
197 }
198 
ArtUnInitCompilerContext(art::CompilerDriver * driver)199 extern "C" void ArtUnInitCompilerContext(art::CompilerDriver* driver) {
200   delete ContextOf(driver);
201   driver->SetCompilerContext(nullptr);
202 }
ArtCompileMethod(art::CompilerDriver * driver,const art::DexFile::CodeItem * code_item,uint32_t access_flags,art::InvokeType invoke_type,uint16_t class_def_idx,uint32_t method_idx,jobject class_loader,const art::DexFile & dex_file)203 extern "C" art::CompiledMethod* ArtCompileMethod(art::CompilerDriver* driver,
204                                                  const art::DexFile::CodeItem* code_item,
205                                                  uint32_t access_flags,
206                                                  art::InvokeType invoke_type,
207                                                  uint16_t class_def_idx,
208                                                  uint32_t method_idx,
209                                                  jobject class_loader,
210                                                  const art::DexFile& dex_file) {
211   UNUSED(class_def_idx);  // TODO: this is used with Compiler::RequiresConstructorBarrier.
212   art::ClassLinker *class_linker = art::Runtime::Current()->GetClassLinker();
213 
214   art::DexCompilationUnit dex_compilation_unit(
215     NULL, class_loader, class_linker, dex_file, code_item,
216     class_def_idx, method_idx, access_flags, driver->GetVerifiedMethod(&dex_file, method_idx));
217   art::llvm::CompilerLLVM* compiler_llvm = ContextOf(driver);
218   art::CompiledMethod* result = compiler_llvm->CompileDexMethod(&dex_compilation_unit, invoke_type);
219   return result;
220 }
221 
ArtLLVMJniCompileMethod(art::CompilerDriver * driver,uint32_t access_flags,uint32_t method_idx,const art::DexFile & dex_file)222 extern "C" art::CompiledMethod* ArtLLVMJniCompileMethod(art::CompilerDriver* driver,
223                                                         uint32_t access_flags, uint32_t method_idx,
224                                                         const art::DexFile& dex_file) {
225   art::ClassLinker *class_linker = art::Runtime::Current()->GetClassLinker();
226 
227   art::DexCompilationUnit dex_compilation_unit(
228       nullptr, nullptr, class_linker, dex_file, nullptr,
229       0, method_idx, access_flags, nullptr);
230 
231   art::llvm::CompilerLLVM* compiler_llvm = ContextOf(driver);
232   art::CompiledMethod* result = compiler_llvm->CompileNativeMethod(&dex_compilation_unit);
233   return result;
234 }
235 
compilerLLVMSetBitcodeFileName(const art::CompilerDriver & driver,const std::string & filename)236 extern "C" void compilerLLVMSetBitcodeFileName(const art::CompilerDriver& driver,
237                                                const std::string& filename) {
238   ContextOf(driver)->SetBitcodeFileName(filename);
239 }
240