1 /*
2  * Copyright 2014 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 "jit_compiler.h"
18 
19 #include "android-base/stringprintf.h"
20 #include "arch/instruction_set.h"
21 #include "arch/instruction_set_features.h"
22 #include "art_method-inl.h"
23 #include "base/logging.h"  // For VLOG
24 #include "base/systrace.h"
25 #include "base/time_utils.h"
26 #include "base/timing_logger.h"
27 #include "compiler.h"
28 #include "debug/elf_debug_writer.h"
29 #include "driver/compiler_options.h"
30 #include "export/jit_create.h"
31 #include "jit/debugger_interface.h"
32 #include "jit/jit.h"
33 #include "jit/jit_code_cache.h"
34 #include "jit/jit_logger.h"
35 
36 namespace art HIDDEN {
37 namespace jit {
38 
Create()39 JitCompiler* JitCompiler::Create() {
40   return new JitCompiler();
41 }
42 
SetDebuggableCompilerOption(bool value)43 void JitCompiler::SetDebuggableCompilerOption(bool value) {
44   compiler_options_->SetDebuggable(value);
45 }
46 
ParseCompilerOptions()47 void JitCompiler::ParseCompilerOptions() {
48   // Special case max code units for inlining, whose default is "unset" (implictly
49   // meaning no limit). Do this before parsing the actual passed options.
50   compiler_options_->SetInlineMaxCodeUnits(CompilerOptions::kDefaultInlineMaxCodeUnits);
51   Runtime* runtime = Runtime::Current();
52   {
53     std::string error_msg;
54     if (!compiler_options_->ParseCompilerOptions(runtime->GetCompilerOptions(),
55                                                 /*ignore_unrecognized=*/ true,
56                                                 &error_msg)) {
57       LOG(FATAL) << error_msg;
58       UNREACHABLE();
59     }
60   }
61   // Set to appropriate JIT compiler type.
62   compiler_options_->compiler_type_ = runtime->IsZygote()
63       ? CompilerOptions::CompilerType::kSharedCodeJitCompiler
64       : CompilerOptions::CompilerType::kJitCompiler;
65   // JIT is never PIC, no matter what the runtime compiler options specify.
66   compiler_options_->SetNonPic();
67 
68   // Set the appropriate read barrier option.
69   compiler_options_->emit_read_barrier_ = gUseReadBarrier;
70 
71   // If the options don't provide whether we generate debuggable code, set
72   // debuggability based on the runtime value.
73   if (!compiler_options_->GetDebuggable()) {
74     compiler_options_->SetDebuggable(runtime->IsJavaDebuggable());
75   }
76 
77   compiler_options_->implicit_null_checks_ = runtime->GetImplicitNullChecks();
78   compiler_options_->implicit_so_checks_ = runtime->GetImplicitStackOverflowChecks();
79   compiler_options_->implicit_suspend_checks_ = runtime->GetImplicitSuspendChecks();
80 
81   const InstructionSet instruction_set = compiler_options_->GetInstructionSet();
82   if (kRuntimeISA == InstructionSet::kArm) {
83     DCHECK_EQ(instruction_set, InstructionSet::kThumb2);
84   } else {
85     DCHECK_EQ(instruction_set, kRuntimeISA);
86   }
87   std::unique_ptr<const InstructionSetFeatures> instruction_set_features;
88   for (const std::string& option : runtime->GetCompilerOptions()) {
89     VLOG(compiler) << "JIT compiler option " << option;
90     std::string error_msg;
91     if (option.starts_with("--instruction-set-variant=")) {
92       const char* str = option.c_str() + strlen("--instruction-set-variant=");
93       VLOG(compiler) << "JIT instruction set variant " << str;
94       instruction_set_features = InstructionSetFeatures::FromVariantAndHwcap(
95           instruction_set, str, &error_msg);
96       if (instruction_set_features == nullptr) {
97         LOG(WARNING) << "Error parsing " << option << " message=" << error_msg;
98       }
99     } else if (option.starts_with("--instruction-set-features=")) {
100       const char* str = option.c_str() + strlen("--instruction-set-features=");
101       VLOG(compiler) << "JIT instruction set features " << str;
102       if (instruction_set_features == nullptr) {
103         instruction_set_features = InstructionSetFeatures::FromVariant(
104             instruction_set, "default", &error_msg);
105         if (instruction_set_features == nullptr) {
106           LOG(WARNING) << "Error parsing " << option << " message=" << error_msg;
107         }
108       }
109       instruction_set_features =
110           instruction_set_features->AddFeaturesFromString(str, &error_msg);
111       if (instruction_set_features == nullptr) {
112         LOG(WARNING) << "Error parsing " << option << " message=" << error_msg;
113       }
114     }
115   }
116 
117   if (instruction_set_features == nullptr) {
118     // '--instruction-set-features/--instruction-set-variant' were not used.
119     // Use build-time defined features.
120     instruction_set_features = InstructionSetFeatures::FromCppDefines();
121   }
122   compiler_options_->instruction_set_features_ = std::move(instruction_set_features);
123 
124   if (compiler_options_->GetGenerateDebugInfo()) {
125     jit_logger_.reset(new JitLogger());
126     jit_logger_->OpenLog();
127   }
128 }
129 
jit_create()130 JitCompilerInterface* jit_create() {
131   VLOG(jit) << "Create jit compiler";
132   auto* const jit_compiler = JitCompiler::Create();
133   CHECK(jit_compiler != nullptr);
134   VLOG(jit) << "Done creating jit compiler";
135   return jit_compiler;
136 }
137 
TypesLoaded(mirror::Class ** types,size_t count)138 void JitCompiler::TypesLoaded(mirror::Class** types, size_t count) {
139   const CompilerOptions& compiler_options = GetCompilerOptions();
140   if (compiler_options.GetGenerateDebugInfo()) {
141     InstructionSet isa = compiler_options.GetInstructionSet();
142     const InstructionSetFeatures* features = compiler_options.GetInstructionSetFeatures();
143     const ArrayRef<mirror::Class*> types_array(types, count);
144     std::vector<uint8_t> elf_file =
145         debug::WriteDebugElfFileForClasses(isa, features, types_array);
146 
147     // NB: Don't allow packing since it would remove non-backtrace data.
148     MutexLock mu(Thread::Current(), *Locks::jit_lock_);
149     AddNativeDebugInfoForJit(/*code_ptr=*/ nullptr, elf_file, /*allow_packing=*/ false);
150   }
151 }
152 
GenerateDebugInfo()153 bool JitCompiler::GenerateDebugInfo() {
154   return GetCompilerOptions().GetGenerateDebugInfo();
155 }
156 
PackElfFileForJIT(ArrayRef<const JITCodeEntry * > elf_files,ArrayRef<const void * > removed_symbols,bool compress,size_t * num_symbols)157 std::vector<uint8_t> JitCompiler::PackElfFileForJIT(ArrayRef<const JITCodeEntry*> elf_files,
158                                                     ArrayRef<const void*> removed_symbols,
159                                                     bool compress,
160                                                     /*out*/ size_t* num_symbols) {
161   return debug::PackElfFileForJIT(elf_files, removed_symbols, compress, num_symbols);
162 }
163 
JitCompiler()164 JitCompiler::JitCompiler() {
165   compiler_options_.reset(new CompilerOptions());
166   ParseCompilerOptions();
167   compiler_.reset(Compiler::Create(*compiler_options_, /*storage=*/ nullptr));
168 }
169 
~JitCompiler()170 JitCompiler::~JitCompiler() {
171   if (compiler_options_->GetGenerateDebugInfo()) {
172     jit_logger_->CloseLog();
173   }
174 }
175 
CompileMethod(Thread * self,JitMemoryRegion * region,ArtMethod * method,CompilationKind compilation_kind)176 bool JitCompiler::CompileMethod(
177     Thread* self, JitMemoryRegion* region, ArtMethod* method, CompilationKind compilation_kind) {
178   SCOPED_TRACE << "JIT compiling "
179                << method->PrettyMethod()
180                << " (kind=" << compilation_kind << ")"
181                << " from " << method->GetDexFile()->GetLocation();
182 
183   DCHECK(!method->IsProxyMethod());
184   DCHECK(method->GetDeclaringClass()->IsResolved());
185 
186   TimingLogger logger(
187       "JIT compiler timing logger", true, VLOG_IS_ON(jit), TimingLogger::TimingKind::kThreadCpu);
188   self->AssertNoPendingException();
189   Runtime* runtime = Runtime::Current();
190 
191   // Do the compilation.
192   bool success = false;
193   Jit* jit = runtime->GetJit();
194   {
195     TimingLogger::ScopedTiming t2(compilation_kind == CompilationKind::kOsr
196                                       ? "Compiling OSR"
197                                       : compilation_kind == CompilationKind::kOptimized
198                                           ? "Compiling optimized"
199                                           : "Compiling baseline",
200                                   &logger);
201     JitCodeCache* const code_cache = jit->GetCodeCache();
202     metrics::AutoTimer timer{runtime->GetMetrics()->JitMethodCompileTotalTime()};
203     success = compiler_->JitCompile(
204         self, code_cache, region, method, compilation_kind, jit_logger_.get());
205     uint64_t duration_us = timer.Stop();
206     VLOG(jit) << "Compilation of " << method->PrettyMethod() << " took "
207               << PrettyDuration(UsToNs(duration_us));
208     runtime->GetMetrics()->JitMethodCompileCount()->AddOne();
209     runtime->GetMetrics()->JitMethodCompileTotalTimeDelta()->Add(duration_us);
210     runtime->GetMetrics()->JitMethodCompileCountDelta()->AddOne();
211   }
212 
213   // If we don't have a new task following this compile,
214   // trim maps to reduce memory usage.
215   if (jit->GetThreadPool() == nullptr || jit->GetThreadPool()->GetTaskCount(self) == 0) {
216     TimingLogger::ScopedTiming t2("TrimMaps", &logger);
217     runtime->GetJitArenaPool()->TrimMaps();
218   }
219 
220   jit->AddTimingLogger(logger);
221   return success;
222 }
223 
IsBaselineCompiler() const224 bool JitCompiler::IsBaselineCompiler() const {
225   return compiler_options_->IsBaseline();
226 }
227 
GetInlineMaxCodeUnits() const228 uint32_t JitCompiler::GetInlineMaxCodeUnits() const {
229   return compiler_options_->GetInlineMaxCodeUnits();
230 }
231 
232 }  // namespace jit
233 }  // namespace art
234