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 
21 #include "arch/instruction_set.h"
22 #include "arch/instruction_set_features.h"
23 #include "art_method-inl.h"
24 #include "base/logging.h"  // For VLOG
25 #include "base/string_view_cpp20.h"
26 #include "base/systrace.h"
27 #include "base/time_utils.h"
28 #include "base/timing_logger.h"
29 #include "compiler.h"
30 #include "debug/elf_debug_writer.h"
31 #include "driver/compiler_options.h"
32 #include "jit/debugger_interface.h"
33 #include "jit/jit.h"
34 #include "jit/jit_code_cache.h"
35 #include "jit/jit_logger.h"
36 
37 namespace art {
38 namespace jit {
39 
Create()40 JitCompiler* JitCompiler::Create() {
41   return new JitCompiler();
42 }
43 
ParseCompilerOptions()44 void JitCompiler::ParseCompilerOptions() {
45   // Special case max code units for inlining, whose default is "unset" (implictly
46   // meaning no limit). Do this before parsing the actual passed options.
47   compiler_options_->SetInlineMaxCodeUnits(CompilerOptions::kDefaultInlineMaxCodeUnits);
48   Runtime* runtime = Runtime::Current();
49   {
50     std::string error_msg;
51     if (!compiler_options_->ParseCompilerOptions(runtime->GetCompilerOptions(),
52                                                 /*ignore_unrecognized=*/ true,
53                                                 &error_msg)) {
54       LOG(FATAL) << error_msg;
55       UNREACHABLE();
56     }
57   }
58   // JIT is never PIC, no matter what the runtime compiler options specify.
59   compiler_options_->SetNonPic();
60 
61   // If the options don't provide whether we generate debuggable code, set
62   // debuggability based on the runtime value.
63   if (!compiler_options_->GetDebuggable()) {
64     compiler_options_->SetDebuggable(runtime->IsJavaDebuggable());
65   }
66 
67   const InstructionSet instruction_set = compiler_options_->GetInstructionSet();
68   if (kRuntimeISA == InstructionSet::kArm) {
69     DCHECK_EQ(instruction_set, InstructionSet::kThumb2);
70   } else {
71     DCHECK_EQ(instruction_set, kRuntimeISA);
72   }
73   std::unique_ptr<const InstructionSetFeatures> instruction_set_features;
74   for (const std::string& option : runtime->GetCompilerOptions()) {
75     VLOG(compiler) << "JIT compiler option " << option;
76     std::string error_msg;
77     if (StartsWith(option, "--instruction-set-variant=")) {
78       const char* str = option.c_str() + strlen("--instruction-set-variant=");
79       VLOG(compiler) << "JIT instruction set variant " << str;
80       instruction_set_features = InstructionSetFeatures::FromVariant(
81           instruction_set, str, &error_msg);
82       if (instruction_set_features == nullptr) {
83         LOG(WARNING) << "Error parsing " << option << " message=" << error_msg;
84       }
85     } else if (StartsWith(option, "--instruction-set-features=")) {
86       const char* str = option.c_str() + strlen("--instruction-set-features=");
87       VLOG(compiler) << "JIT instruction set features " << str;
88       if (instruction_set_features == nullptr) {
89         instruction_set_features = InstructionSetFeatures::FromVariant(
90             instruction_set, "default", &error_msg);
91         if (instruction_set_features == nullptr) {
92           LOG(WARNING) << "Error parsing " << option << " message=" << error_msg;
93         }
94       }
95       instruction_set_features =
96           instruction_set_features->AddFeaturesFromString(str, &error_msg);
97       if (instruction_set_features == nullptr) {
98         LOG(WARNING) << "Error parsing " << option << " message=" << error_msg;
99       }
100     }
101   }
102 
103   if (instruction_set_features == nullptr) {
104     // '--instruction-set-features/--instruction-set-variant' were not used.
105     // Use build-time defined features.
106     instruction_set_features = InstructionSetFeatures::FromCppDefines();
107   }
108   compiler_options_->instruction_set_features_ = std::move(instruction_set_features);
109   compiler_options_->compiling_with_core_image_ =
110       CompilerOptions::IsCoreImageFilename(runtime->GetImageLocation());
111 
112   if (compiler_options_->GetGenerateDebugInfo()) {
113     jit_logger_.reset(new JitLogger());
114     jit_logger_->OpenLog();
115   }
116 }
117 
jit_load()118 extern "C" JitCompilerInterface* jit_load() {
119   VLOG(jit) << "Create jit compiler";
120   auto* const jit_compiler = JitCompiler::Create();
121   CHECK(jit_compiler != nullptr);
122   VLOG(jit) << "Done creating jit compiler";
123   return jit_compiler;
124 }
125 
TypesLoaded(mirror::Class ** types,size_t count)126 void JitCompiler::TypesLoaded(mirror::Class** types, size_t count) {
127   const CompilerOptions& compiler_options = GetCompilerOptions();
128   if (compiler_options.GetGenerateDebugInfo()) {
129     InstructionSet isa = compiler_options.GetInstructionSet();
130     const InstructionSetFeatures* features = compiler_options.GetInstructionSetFeatures();
131     const ArrayRef<mirror::Class*> types_array(types, count);
132     std::vector<uint8_t> elf_file =
133         debug::WriteDebugElfFileForClasses(isa, features, types_array);
134 
135     // NB: Don't allow packing since it would remove non-backtrace data.
136     MutexLock mu(Thread::Current(), *Locks::jit_lock_);
137     AddNativeDebugInfoForJit(/*code_ptr=*/ nullptr, elf_file, /*allow_packing=*/ false);
138   }
139 }
140 
GenerateDebugInfo()141 bool JitCompiler::GenerateDebugInfo() {
142   return GetCompilerOptions().GetGenerateDebugInfo();
143 }
144 
PackElfFileForJIT(ArrayRef<const JITCodeEntry * > elf_files,ArrayRef<const void * > removed_symbols,bool compress,size_t * num_symbols)145 std::vector<uint8_t> JitCompiler::PackElfFileForJIT(ArrayRef<const JITCodeEntry*> elf_files,
146                                                     ArrayRef<const void*> removed_symbols,
147                                                     bool compress,
148                                                     /*out*/ size_t* num_symbols) {
149   return debug::PackElfFileForJIT(elf_files, removed_symbols, compress, num_symbols);
150 }
151 
JitCompiler()152 JitCompiler::JitCompiler() {
153   compiler_options_.reset(new CompilerOptions());
154   ParseCompilerOptions();
155   compiler_.reset(
156       Compiler::Create(*compiler_options_, /*storage=*/ nullptr, Compiler::kOptimizing));
157 }
158 
~JitCompiler()159 JitCompiler::~JitCompiler() {
160   if (compiler_options_->GetGenerateDebugInfo()) {
161     jit_logger_->CloseLog();
162   }
163 }
164 
CompileMethod(Thread * self,JitMemoryRegion * region,ArtMethod * method,bool baseline,bool osr)165 bool JitCompiler::CompileMethod(
166     Thread* self, JitMemoryRegion* region, ArtMethod* method, bool baseline, bool osr) {
167   SCOPED_TRACE << "JIT compiling "
168                << method->PrettyMethod()
169                << " (baseline=" << baseline << ", osr=" << osr << ")";
170 
171   DCHECK(!method->IsProxyMethod());
172   DCHECK(method->GetDeclaringClass()->IsResolved());
173 
174   TimingLogger logger(
175       "JIT compiler timing logger", true, VLOG_IS_ON(jit), TimingLogger::TimingKind::kThreadCpu);
176   self->AssertNoPendingException();
177   Runtime* runtime = Runtime::Current();
178 
179   // Do the compilation.
180   bool success = false;
181   {
182     TimingLogger::ScopedTiming t2("Compiling", &logger);
183     JitCodeCache* const code_cache = runtime->GetJit()->GetCodeCache();
184     uint64_t start_ns = NanoTime();
185     success = compiler_->JitCompile(
186         self, code_cache, region, method, baseline, osr, jit_logger_.get());
187     uint64_t duration_ns = NanoTime() - start_ns;
188     VLOG(jit) << "Compilation of "
189               << method->PrettyMethod()
190               << " took "
191               << PrettyDuration(duration_ns);
192   }
193 
194   // Trim maps to reduce memory usage.
195   // TODO: move this to an idle phase.
196   {
197     TimingLogger::ScopedTiming t2("TrimMaps", &logger);
198     runtime->GetJitArenaPool()->TrimMaps();
199   }
200 
201   runtime->GetJit()->AddTimingLogger(logger);
202   return success;
203 }
204 
205 }  // namespace jit
206 }  // namespace art
207