blob: b83957f213edc5a906e42d749e09da492f40d54b [file] [log] [blame]
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001/*
2 * Copyright (C) 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
Andreas Gampe53c913b2014-08-12 23:19:23 -070017#include "optimizing_compiler.h"
18
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010019#include <fstream>
David Srbecky5cc349f2015-12-18 15:04:48 +000020#include <memory>
Nicolas Geoffray787c3072014-03-17 10:20:19 +000021#include <stdint.h>
22
Alexandre Rames44b9cf92015-08-19 15:39:06 +010023#ifdef ART_ENABLE_CODEGEN_arm64
Vladimir Markob4536b72015-11-24 13:45:23 +000024#include "dex_cache_array_fixups_arm.h"
25#endif
26
27#ifdef ART_ENABLE_CODEGEN_arm64
Alexandre Rames44b9cf92015-08-19 15:39:06 +010028#include "instruction_simplifier_arm64.h"
29#endif
30
Mark Mendell0616ae02015-04-17 12:49:27 -040031#ifdef ART_ENABLE_CODEGEN_x86
Vladimir Marko0f7dca42015-11-02 14:36:43 +000032#include "pc_relative_fixups_x86.h"
Mark Mendell0616ae02015-04-17 12:49:27 -040033#endif
34
Mathieu Chartiere401d142015-04-22 13:56:20 -070035#include "art_method-inl.h"
Mathieu Chartierb666f482015-02-18 14:33:14 -080036#include "base/arena_allocator.h"
Vladimir Markof9f64412015-09-02 14:05:49 +010037#include "base/arena_containers.h"
David Brazdil5e8b1372015-01-23 14:39:08 +000038#include "base/dumpable.h"
Vladimir Markoc90d7c72015-10-06 17:30:45 +000039#include "base/macros.h"
David Brazdil5e8b1372015-01-23 14:39:08 +000040#include "base/timing_logger.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070041#include "bounds_check_elimination.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000042#include "builder.h"
43#include "code_generator.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000044#include "compiled_method.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070045#include "compiler.h"
Roland Levillain75be2832014-10-17 17:02:00 +010046#include "constant_folding.h"
47#include "dead_code_elimination.h"
David Srbeckyc5bfa972016-02-05 15:49:10 +000048#include "debug/elf_debug_writer.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000049#include "debug/method_debug_info.h"
Andreas Gampe71fb52f2014-12-29 17:43:08 -080050#include "dex/quick/dex_file_to_method_inliner_map.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010051#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000052#include "dex/verified_method.h"
Nicolas Geoffray9523a3e2015-07-17 11:51:28 +000053#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000054#include "driver/compiler_options.h"
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000055#include "driver/dex_compilation_unit.h"
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +000056#include "elf_writer_quick.h"
David Brazdil69ba7b72015-06-23 18:27:30 +010057#include "graph_checker.h"
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010058#include "graph_visualizer.h"
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +010059#include "gvn.h"
Aart Bik22af3be2015-09-10 12:50:58 -070060#include "induction_var_analysis.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000061#include "inliner.h"
Nicolas Geoffray3c049742014-09-24 18:10:46 +010062#include "instruction_simplifier.h"
Andreas Gampe71fb52f2014-12-29 17:43:08 -080063#include "intrinsics.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000064#include "jit/debugger_interface.h"
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +000065#include "jit/jit_code_cache.h"
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +000066#include "jni/quick/jni_compiler.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000067#include "licm.h"
Mingyao Yang8df69d42015-10-22 15:40:58 -070068#include "load_store_elimination.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000069#include "nodes.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000070#include "oat_quick_method_header.h"
Nicolas Geoffray26a25ef2014-09-30 13:54:09 +010071#include "prepare_for_register_allocation.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010072#include "reference_type_propagation.h"
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010073#include "register_allocator.h"
David Brazdil74eb1b22015-12-14 11:44:01 +000074#include "select_generator.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010075#include "sharpening.h"
Nicolas Geoffray827eedb2015-01-26 15:18:36 +000076#include "side_effects_analysis.h"
Nicolas Geoffray31596742014-11-24 15:28:45 +000077#include "ssa_builder.h"
Nicolas Geoffray804d0932014-05-02 08:46:00 +010078#include "ssa_liveness_analysis.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000079#include "ssa_phi_elimination.h"
David Srbeckyc6b4dd82015-04-07 20:32:43 +010080#include "utils/assembler.h"
Calin Juravle175dc732015-08-25 15:42:32 +010081#include "verifier/method_verifier.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000082
83namespace art {
84
Nicolas Geoffray787c3072014-03-17 10:20:19 +000085/**
86 * Used by the code generator, to allocate the code in a vector.
87 */
88class CodeVectorAllocator FINAL : public CodeAllocator {
89 public:
Vladimir Markof9f64412015-09-02 14:05:49 +010090 explicit CodeVectorAllocator(ArenaAllocator* arena)
91 : memory_(arena->Adapter(kArenaAllocCodeBuffer)),
92 size_(0) {}
Nicolas Geoffray787c3072014-03-17 10:20:19 +000093
94 virtual uint8_t* Allocate(size_t size) {
95 size_ = size;
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000096 memory_.resize(size);
Nicolas Geoffray787c3072014-03-17 10:20:19 +000097 return &memory_[0];
98 }
99
100 size_t GetSize() const { return size_; }
Vladimir Markof9f64412015-09-02 14:05:49 +0100101 const ArenaVector<uint8_t>& GetMemory() const { return memory_; }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000102
103 private:
Vladimir Markof9f64412015-09-02 14:05:49 +0100104 ArenaVector<uint8_t> memory_;
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000105 size_t size_;
106
107 DISALLOW_COPY_AND_ASSIGN(CodeVectorAllocator);
108};
109
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100110/**
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100111 * Filter to apply to the visualizer. Methods whose name contain that filter will
David Brazdilee690a32014-12-01 17:04:16 +0000112 * be dumped.
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100113 */
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700114static constexpr const char kStringFilter[] = "";
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100115
David Brazdil69ba7b72015-06-23 18:27:30 +0100116class PassScope;
David Brazdil809658e2015-02-05 11:34:02 +0000117
David Brazdil69ba7b72015-06-23 18:27:30 +0100118class PassObserver : public ValueObject {
David Brazdil5e8b1372015-01-23 14:39:08 +0000119 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100120 PassObserver(HGraph* graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100121 CodeGenerator* codegen,
122 std::ostream* visualizer_output,
123 CompilerDriver* compiler_driver)
124 : graph_(graph),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000125 cached_method_name_(),
David Brazdil809658e2015-02-05 11:34:02 +0000126 timing_logger_enabled_(compiler_driver->GetDumpPasses()),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000127 timing_logger_(timing_logger_enabled_ ? GetMethodName() : "", true, true),
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100128 disasm_info_(graph->GetArena()),
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000129 visualizer_enabled_(!compiler_driver->GetCompilerOptions().GetDumpCfgFileName().empty()),
David Brazdil69ba7b72015-06-23 18:27:30 +0100130 visualizer_(visualizer_output, graph, *codegen),
131 graph_in_bad_state_(false) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700132 if (timing_logger_enabled_ || visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000133 if (!IsVerboseMethod(compiler_driver, GetMethodName())) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700134 timing_logger_enabled_ = visualizer_enabled_ = false;
135 }
136 if (visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000137 visualizer_.PrintHeader(GetMethodName());
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700138 codegen->SetDisassemblyInformation(&disasm_info_);
139 }
David Brazdil62e074f2015-04-07 18:09:37 +0100140 }
David Brazdil5e8b1372015-01-23 14:39:08 +0000141 }
142
David Brazdil69ba7b72015-06-23 18:27:30 +0100143 ~PassObserver() {
David Brazdil5e8b1372015-01-23 14:39:08 +0000144 if (timing_logger_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000145 LOG(INFO) << "TIMINGS " << GetMethodName();
David Brazdil5e8b1372015-01-23 14:39:08 +0000146 LOG(INFO) << Dumpable<TimingLogger>(timing_logger_);
147 }
148 }
149
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100150 void DumpDisassembly() const {
151 if (visualizer_enabled_) {
152 visualizer_.DumpGraphWithDisassembly();
153 }
154 }
155
David Brazdil69ba7b72015-06-23 18:27:30 +0100156 void SetGraphInBadState() { graph_in_bad_state_ = true; }
157
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000158 const char* GetMethodName() {
159 // PrettyMethod() is expensive, so we delay calling it until we actually have to.
160 if (cached_method_name_.empty()) {
161 cached_method_name_ = PrettyMethod(graph_->GetMethodIdx(), graph_->GetDexFile());
162 }
163 return cached_method_name_.c_str();
164 }
165
David Brazdil5e8b1372015-01-23 14:39:08 +0000166 private:
David Brazdil809658e2015-02-05 11:34:02 +0000167 void StartPass(const char* pass_name) {
168 // Dump graph first, then start timer.
169 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100170 visualizer_.DumpGraph(pass_name, /* is_after_pass */ false, graph_in_bad_state_);
David Brazdil809658e2015-02-05 11:34:02 +0000171 }
172 if (timing_logger_enabled_) {
173 timing_logger_.StartTiming(pass_name);
174 }
175 }
176
177 void EndPass(const char* pass_name) {
178 // Pause timer first, then dump graph.
179 if (timing_logger_enabled_) {
180 timing_logger_.EndTiming();
181 }
182 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100183 visualizer_.DumpGraph(pass_name, /* is_after_pass */ true, graph_in_bad_state_);
David Brazdil809658e2015-02-05 11:34:02 +0000184 }
David Brazdil69ba7b72015-06-23 18:27:30 +0100185
186 // Validate the HGraph if running in debug mode.
187 if (kIsDebugBuild) {
188 if (!graph_in_bad_state_) {
David Brazdilbadd8262016-02-02 16:28:56 +0000189 GraphChecker checker(graph_);
190 checker.Run();
191 if (!checker.IsValid()) {
192 LOG(FATAL) << "Error after " << pass_name << ": " << Dumpable<GraphChecker>(checker);
David Brazdil69ba7b72015-06-23 18:27:30 +0100193 }
194 }
195 }
David Brazdil809658e2015-02-05 11:34:02 +0000196 }
197
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700198 static bool IsVerboseMethod(CompilerDriver* compiler_driver, const char* method_name) {
199 // Test an exact match to --verbose-methods. If verbose-methods is set, this overrides an
200 // empty kStringFilter matching all methods.
201 if (compiler_driver->GetCompilerOptions().HasVerboseMethods()) {
202 return compiler_driver->GetCompilerOptions().IsVerboseMethod(method_name);
203 }
204
205 // Test the kStringFilter sub-string. constexpr helper variable to silence unreachable-code
206 // warning when the string is empty.
207 constexpr bool kStringFilterEmpty = arraysize(kStringFilter) <= 1;
208 if (kStringFilterEmpty || strstr(method_name, kStringFilter) != nullptr) {
209 return true;
210 }
211
212 return false;
213 }
214
David Brazdil69ba7b72015-06-23 18:27:30 +0100215 HGraph* const graph_;
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000216
217 std::string cached_method_name_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000218
219 bool timing_logger_enabled_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000220 TimingLogger timing_logger_;
221
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100222 DisassemblyInformation disasm_info_;
223
David Brazdil5e8b1372015-01-23 14:39:08 +0000224 bool visualizer_enabled_;
225 HGraphVisualizer visualizer_;
226
David Brazdil69ba7b72015-06-23 18:27:30 +0100227 // Flag to be set by the compiler if the pass failed and the graph is not
228 // expected to validate.
229 bool graph_in_bad_state_;
David Brazdil809658e2015-02-05 11:34:02 +0000230
David Brazdil69ba7b72015-06-23 18:27:30 +0100231 friend PassScope;
232
233 DISALLOW_COPY_AND_ASSIGN(PassObserver);
David Brazdil5e8b1372015-01-23 14:39:08 +0000234};
235
David Brazdil69ba7b72015-06-23 18:27:30 +0100236class PassScope : public ValueObject {
David Brazdil809658e2015-02-05 11:34:02 +0000237 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100238 PassScope(const char *pass_name, PassObserver* pass_observer)
David Brazdil809658e2015-02-05 11:34:02 +0000239 : pass_name_(pass_name),
David Brazdil69ba7b72015-06-23 18:27:30 +0100240 pass_observer_(pass_observer) {
241 pass_observer_->StartPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000242 }
243
David Brazdil69ba7b72015-06-23 18:27:30 +0100244 ~PassScope() {
245 pass_observer_->EndPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000246 }
247
248 private:
249 const char* const pass_name_;
David Brazdil69ba7b72015-06-23 18:27:30 +0100250 PassObserver* const pass_observer_;
David Brazdil809658e2015-02-05 11:34:02 +0000251};
252
Andreas Gampe53c913b2014-08-12 23:19:23 -0700253class OptimizingCompiler FINAL : public Compiler {
254 public:
255 explicit OptimizingCompiler(CompilerDriver* driver);
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100256 ~OptimizingCompiler();
Andreas Gampe53c913b2014-08-12 23:19:23 -0700257
258 bool CanCompileMethod(uint32_t method_idx, const DexFile& dex_file, CompilationUnit* cu) const
259 OVERRIDE;
260
261 CompiledMethod* Compile(const DexFile::CodeItem* code_item,
262 uint32_t access_flags,
263 InvokeType invoke_type,
264 uint16_t class_def_idx,
265 uint32_t method_idx,
266 jobject class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700267 const DexFile& dex_file,
268 Handle<mirror::DexCache> dex_cache) const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700269
Andreas Gampe53c913b2014-08-12 23:19:23 -0700270 CompiledMethod* JniCompile(uint32_t access_flags,
271 uint32_t method_idx,
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000272 const DexFile& dex_file) const OVERRIDE {
273 return ArtQuickJniCompileMethod(GetCompilerDriver(), access_flags, method_idx, dex_file);
274 }
Andreas Gampe53c913b2014-08-12 23:19:23 -0700275
Mathieu Chartiere401d142015-04-22 13:56:20 -0700276 uintptr_t GetEntryPointOf(ArtMethod* method) const OVERRIDE
Mathieu Chartier90443472015-07-16 20:32:27 -0700277 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000278 return reinterpret_cast<uintptr_t>(method->GetEntryPointFromQuickCompiledCodePtrSize(
279 InstructionSetPointerSize(GetCompilerDriver()->GetInstructionSet())));
280 }
Andreas Gampe53c913b2014-08-12 23:19:23 -0700281
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000282 void InitCompilationUnit(CompilationUnit& cu) const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700283
David Brazdilee690a32014-12-01 17:04:16 +0000284 void Init() OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700285
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000286 void UnInit() const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700287
Calin Juravle2be39e02015-04-21 13:56:34 +0100288 void MaybeRecordStat(MethodCompilationStat compilation_stat) const {
289 if (compilation_stats_.get() != nullptr) {
290 compilation_stats_->RecordStat(compilation_stat);
291 }
292 }
293
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000294 bool JitCompile(Thread* self, jit::JitCodeCache* code_cache, ArtMethod* method, bool osr)
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000295 OVERRIDE
296 SHARED_REQUIRES(Locks::mutator_lock_);
297
Andreas Gampe53c913b2014-08-12 23:19:23 -0700298 private:
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000299 // Create a 'CompiledMethod' for an optimized graph.
David Brazdil58282f42016-01-14 12:45:10 +0000300 CompiledMethod* Emit(ArenaAllocator* arena,
301 CodeVectorAllocator* code_allocator,
302 CodeGenerator* codegen,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000303 CompilerDriver* driver,
304 const DexFile::CodeItem* item) const;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000305
306 // Try compiling a method and return the code generator used for
307 // compiling it.
308 // This method:
309 // 1) Builds the graph. Returns null if it failed to build it.
David Brazdil58282f42016-01-14 12:45:10 +0000310 // 2) Transforms the graph to SSA. Returns null if it failed.
311 // 3) Runs optimizations on the graph, including register allocator.
312 // 4) Generates code with the `code_allocator` provided.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000313 CodeGenerator* TryCompile(ArenaAllocator* arena,
314 CodeVectorAllocator* code_allocator,
315 const DexFile::CodeItem* code_item,
316 uint32_t access_flags,
317 InvokeType invoke_type,
318 uint16_t class_def_idx,
319 uint32_t method_idx,
320 jobject class_loader,
321 const DexFile& dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000322 Handle<mirror::DexCache> dex_cache,
323 bool osr) const;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000324
Calin Juravle2be39e02015-04-21 13:56:34 +0100325 std::unique_ptr<OptimizingCompilerStats> compilation_stats_;
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100326
Andreas Gampe53c913b2014-08-12 23:19:23 -0700327 std::unique_ptr<std::ostream> visualizer_output_;
328
Andreas Gampe53c913b2014-08-12 23:19:23 -0700329 DISALLOW_COPY_AND_ASSIGN(OptimizingCompiler);
330};
331
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100332static const int kMaximumCompilationTimeBeforeWarning = 100; /* ms */
333
334OptimizingCompiler::OptimizingCompiler(CompilerDriver* driver)
David Brazdil58282f42016-01-14 12:45:10 +0000335 : Compiler(driver, kMaximumCompilationTimeBeforeWarning) {}
David Brazdilee690a32014-12-01 17:04:16 +0000336
337void OptimizingCompiler::Init() {
338 // Enable C1visualizer output. Must be done in Init() because the compiler
339 // driver is not fully initialized when passed to the compiler's constructor.
340 CompilerDriver* driver = GetCompilerDriver();
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000341 const std::string cfg_file_name = driver->GetCompilerOptions().GetDumpCfgFileName();
David Brazdil866c0312015-01-13 21:21:31 +0000342 if (!cfg_file_name.empty()) {
David Brazdilee690a32014-12-01 17:04:16 +0000343 CHECK_EQ(driver->GetThreadCount(), 1U)
344 << "Graph visualizer requires the compiler to run single-threaded. "
345 << "Invoke the compiler with '-j1'.";
Calin Juravle87000a92015-08-24 15:34:44 +0100346 std::ios_base::openmode cfg_file_mode =
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000347 driver->GetCompilerOptions().GetDumpCfgAppend() ? std::ofstream::app : std::ofstream::out;
Calin Juravle87000a92015-08-24 15:34:44 +0100348 visualizer_output_.reset(new std::ofstream(cfg_file_name, cfg_file_mode));
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100349 }
Calin Juravle2be39e02015-04-21 13:56:34 +0100350 if (driver->GetDumpStats()) {
351 compilation_stats_.reset(new OptimizingCompilerStats());
352 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100353}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000354
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000355void OptimizingCompiler::UnInit() const {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000356}
357
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100358OptimizingCompiler::~OptimizingCompiler() {
Calin Juravle2be39e02015-04-21 13:56:34 +0100359 if (compilation_stats_.get() != nullptr) {
360 compilation_stats_->Log();
361 }
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100362}
363
Nicolas Geoffrayda3a55b2015-10-02 11:56:50 +0100364void OptimizingCompiler::InitCompilationUnit(CompilationUnit& cu ATTRIBUTE_UNUSED) const {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000365}
366
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000367bool OptimizingCompiler::CanCompileMethod(uint32_t method_idx ATTRIBUTE_UNUSED,
368 const DexFile& dex_file ATTRIBUTE_UNUSED,
369 CompilationUnit* cu ATTRIBUTE_UNUSED) const {
370 return true;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700371}
372
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000373static bool IsInstructionSetSupported(InstructionSet instruction_set) {
Calin Juravlecff8cc72015-10-09 12:03:24 +0100374 return (instruction_set == kArm && !kArm32QuickCodeUseSoftFloat)
375 || instruction_set == kArm64
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000376 || (instruction_set == kThumb2 && !kArm32QuickCodeUseSoftFloat)
Goran Jakovljevicf652cec2015-08-25 16:11:42 +0200377 || instruction_set == kMips
Alexey Frunze4dda3372015-06-01 18:31:49 -0700378 || instruction_set == kMips64
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000379 || instruction_set == kX86
380 || instruction_set == kX86_64;
381}
382
Roland Levillain22ccc3a2015-11-24 13:10:05 +0000383// Read barrier are supported on ARM, ARM64, x86 and x86-64 at the moment.
Roland Levillain0d5a2812015-11-13 10:07:31 +0000384// TODO: Add support for other architectures and remove this function
385static bool InstructionSetSupportsReadBarrier(InstructionSet instruction_set) {
Roland Levillain22ccc3a2015-11-24 13:10:05 +0000386 return instruction_set == kArm64
387 || instruction_set == kThumb2
Roland Levillain3b359c72015-11-17 19:35:12 +0000388 || instruction_set == kX86
Roland Levillain0d5a2812015-11-13 10:07:31 +0000389 || instruction_set == kX86_64;
390}
391
Calin Juravle10e244f2015-01-26 18:54:32 +0000392static void RunOptimizations(HOptimization* optimizations[],
393 size_t length,
David Brazdil69ba7b72015-06-23 18:27:30 +0100394 PassObserver* pass_observer) {
Calin Juravle10e244f2015-01-26 18:54:32 +0000395 for (size_t i = 0; i < length; ++i) {
David Brazdil69ba7b72015-06-23 18:27:30 +0100396 PassScope scope(optimizations[i]->GetPassName(), pass_observer);
397 optimizations[i]->Run();
Calin Juravle10e244f2015-01-26 18:54:32 +0000398 }
399}
400
Calin Juravleec748352015-07-29 13:52:12 +0100401static void MaybeRunInliner(HGraph* graph,
Vladimir Markodc151b22015-10-15 18:02:30 +0100402 CodeGenerator* codegen,
Calin Juravleec748352015-07-29 13:52:12 +0100403 CompilerDriver* driver,
404 OptimizingCompilerStats* stats,
405 const DexCompilationUnit& dex_compilation_unit,
406 PassObserver* pass_observer,
407 StackHandleScopeCollection* handles) {
408 const CompilerOptions& compiler_options = driver->GetCompilerOptions();
409 bool should_inline = (compiler_options.GetInlineDepthLimit() > 0)
410 && (compiler_options.GetInlineMaxCodeUnits() > 0);
411 if (!should_inline) {
412 return;
413 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000414 size_t number_of_dex_registers = dex_compilation_unit.GetCodeItem()->registers_size_;
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000415 HInliner* inliner = new (graph->GetArena()) HInliner(
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000416 graph,
417 graph,
418 codegen,
419 dex_compilation_unit,
420 dex_compilation_unit,
421 driver,
422 handles,
423 stats,
424 number_of_dex_registers,
425 /* depth */ 0);
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000426 HOptimization* optimizations[] = { inliner };
Calin Juravleec748352015-07-29 13:52:12 +0100427
428 RunOptimizations(optimizations, arraysize(optimizations), pass_observer);
429}
430
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100431static void RunArchOptimizations(InstructionSet instruction_set,
432 HGraph* graph,
433 OptimizingCompilerStats* stats,
434 PassObserver* pass_observer) {
435 ArenaAllocator* arena = graph->GetArena();
436 switch (instruction_set) {
Vladimir Markob4536b72015-11-24 13:45:23 +0000437#ifdef ART_ENABLE_CODEGEN_arm
438 case kThumb2:
439 case kArm: {
440 arm::DexCacheArrayFixups* fixups = new (arena) arm::DexCacheArrayFixups(graph, stats);
441 HOptimization* arm_optimizations[] = {
Nicolas Geoffray6b5afdd2016-01-22 09:31:52 +0000442 fixups
Vladimir Markob4536b72015-11-24 13:45:23 +0000443 };
444 RunOptimizations(arm_optimizations, arraysize(arm_optimizations), pass_observer);
445 break;
446 }
447#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100448#ifdef ART_ENABLE_CODEGEN_arm64
449 case kArm64: {
450 arm64::InstructionSimplifierArm64* simplifier =
451 new (arena) arm64::InstructionSimplifierArm64(graph, stats);
452 SideEffectsAnalysis* side_effects = new (arena) SideEffectsAnalysis(graph);
453 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects, "GVN_after_arch");
454 HOptimization* arm64_optimizations[] = {
455 simplifier,
456 side_effects,
457 gvn
458 };
459 RunOptimizations(arm64_optimizations, arraysize(arm64_optimizations), pass_observer);
460 break;
461 }
462#endif
Mark Mendell0616ae02015-04-17 12:49:27 -0400463#ifdef ART_ENABLE_CODEGEN_x86
464 case kX86: {
Vladimir Marko0f7dca42015-11-02 14:36:43 +0000465 x86::PcRelativeFixups* pc_relative_fixups = new (arena) x86::PcRelativeFixups(graph, stats);
Mark Mendell0616ae02015-04-17 12:49:27 -0400466 HOptimization* x86_optimizations[] = {
Vladimir Marko0f7dca42015-11-02 14:36:43 +0000467 pc_relative_fixups
Mark Mendell0616ae02015-04-17 12:49:27 -0400468 };
469 RunOptimizations(x86_optimizations, arraysize(x86_optimizations), pass_observer);
470 break;
471 }
472#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100473 default:
474 break;
475 }
476}
477
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000478NO_INLINE // Avoid increasing caller's frame size by large stack-allocated objects.
479static void AllocateRegisters(HGraph* graph,
480 CodeGenerator* codegen,
481 PassObserver* pass_observer) {
482 PrepareForRegisterAllocation(graph).Run();
483 SsaLivenessAnalysis liveness(graph, codegen);
484 {
485 PassScope scope(SsaLivenessAnalysis::kLivenessPassName, pass_observer);
486 liveness.Analyze();
487 }
488 {
489 PassScope scope(RegisterAllocator::kRegisterAllocatorPassName, pass_observer);
490 RegisterAllocator(graph->GetArena(), codegen, liveness).AllocateRegisters();
491 }
492}
493
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000494static void RunOptimizations(HGraph* graph,
Vladimir Markodc151b22015-10-15 18:02:30 +0100495 CodeGenerator* codegen,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000496 CompilerDriver* driver,
497 OptimizingCompilerStats* stats,
498 const DexCompilationUnit& dex_compilation_unit,
David Brazdil4833f5a2015-12-16 10:37:39 +0000499 PassObserver* pass_observer,
500 StackHandleScopeCollection* handles) {
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100501 ArenaAllocator* arena = graph->GetArena();
502 HDeadCodeElimination* dce1 = new (arena) HDeadCodeElimination(
503 graph, stats, HDeadCodeElimination::kInitialDeadCodeEliminationPassName);
504 HDeadCodeElimination* dce2 = new (arena) HDeadCodeElimination(
505 graph, stats, HDeadCodeElimination::kFinalDeadCodeEliminationPassName);
Nicolas Geoffraye34648d2015-11-23 08:59:07 +0000506 HConstantFolding* fold1 = new (arena) HConstantFolding(graph);
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100507 InstructionSimplifier* simplify1 = new (arena) InstructionSimplifier(graph, stats);
David Brazdil74eb1b22015-12-14 11:44:01 +0000508 HSelectGenerator* select_generator = new (arena) HSelectGenerator(graph);
Nicolas Geoffraye34648d2015-11-23 08:59:07 +0000509 HConstantFolding* fold2 = new (arena) HConstantFolding(graph, "constant_folding_after_inlining");
Aart Bik4a342772015-11-30 10:17:46 -0800510 HConstantFolding* fold3 = new (arena) HConstantFolding(graph, "constant_folding_after_bce");
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100511 SideEffectsAnalysis* side_effects = new (arena) SideEffectsAnalysis(graph);
512 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects);
513 LICM* licm = new (arena) LICM(graph, *side_effects);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700514 LoadStoreElimination* lse = new (arena) LoadStoreElimination(graph, *side_effects);
Aart Bik22af3be2015-09-10 12:50:58 -0700515 HInductionVarAnalysis* induction = new (arena) HInductionVarAnalysis(graph);
Aart Bik4a342772015-11-30 10:17:46 -0800516 BoundsCheckElimination* bce = new (arena) BoundsCheckElimination(graph, *side_effects, induction);
Vladimir Markodc151b22015-10-15 18:02:30 +0100517 HSharpening* sharpening = new (arena) HSharpening(graph, codegen, dex_compilation_unit, driver);
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100518 InstructionSimplifier* simplify2 = new (arena) InstructionSimplifier(
Alex Light68289a52015-12-15 17:30:30 -0800519 graph, stats, "instruction_simplifier_after_bce");
David Brazdil4833f5a2015-12-16 10:37:39 +0000520 InstructionSimplifier* simplify3 = new (arena) InstructionSimplifier(
Nicolas Geoffrayb2bdfce2015-06-18 15:46:47 +0100521 graph, stats, "instruction_simplifier_before_codegen");
Nicolas Geoffraye34648d2015-11-23 08:59:07 +0000522 IntrinsicsRecognizer* intrinsics = new (arena) IntrinsicsRecognizer(graph, driver);
Andreas Gampe71fb52f2014-12-29 17:43:08 -0800523
Calin Juravleec748352015-07-29 13:52:12 +0100524 HOptimization* optimizations1[] = {
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100525 intrinsics,
David Brazdil4833f5a2015-12-16 10:37:39 +0000526 sharpening,
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100527 fold1,
528 simplify1,
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100529 dce1,
Calin Juravleec748352015-07-29 13:52:12 +0100530 };
Calin Juravleec748352015-07-29 13:52:12 +0100531 RunOptimizations(optimizations1, arraysize(optimizations1), pass_observer);
532
David Brazdil4833f5a2015-12-16 10:37:39 +0000533 MaybeRunInliner(graph, codegen, driver, stats, dex_compilation_unit, pass_observer, handles);
David Brazdil95177982015-10-30 12:56:58 -0500534
David Brazdil8993caf2015-12-07 10:04:40 +0000535 HOptimization* optimizations2[] = {
David Brazdil74eb1b22015-12-14 11:44:01 +0000536 // SelectGenerator depends on the InstructionSimplifier removing
David Brazdil8993caf2015-12-07 10:04:40 +0000537 // redundant suspend checks to recognize empty blocks.
David Brazdil74eb1b22015-12-14 11:44:01 +0000538 select_generator,
David Brazdil8993caf2015-12-07 10:04:40 +0000539 fold2, // TODO: if we don't inline we can also skip fold2.
540 side_effects,
541 gvn,
542 licm,
543 induction,
544 bce,
545 fold3, // evaluates code generated by dynamic bce
David Brazdil4833f5a2015-12-16 10:37:39 +0000546 simplify2,
David Brazdil8993caf2015-12-07 10:04:40 +0000547 lse,
548 dce2,
549 // The codegen has a few assumptions that only the instruction simplifier
550 // can satisfy. For example, the code generator does not expect to see a
551 // HTypeConversion from a type to the same type.
David Brazdil4833f5a2015-12-16 10:37:39 +0000552 simplify3,
David Brazdil8993caf2015-12-07 10:04:40 +0000553 };
554 RunOptimizations(optimizations2, arraysize(optimizations2), pass_observer);
David Brazdilbbd733e2015-08-18 17:48:17 +0100555
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100556 RunArchOptimizations(driver->GetInstructionSet(), graph, stats, pass_observer);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000557 AllocateRegisters(graph, codegen, pass_observer);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000558}
559
Vladimir Marko58155012015-08-19 12:49:41 +0000560static ArenaVector<LinkerPatch> EmitAndSortLinkerPatches(CodeGenerator* codegen) {
561 ArenaVector<LinkerPatch> linker_patches(codegen->GetGraph()->GetArena()->Adapter());
562 codegen->EmitLinkerPatches(&linker_patches);
563
564 // Sort patches by literal offset. Required for .oat_patches encoding.
565 std::sort(linker_patches.begin(), linker_patches.end(),
566 [](const LinkerPatch& lhs, const LinkerPatch& rhs) {
567 return lhs.LiteralOffset() < rhs.LiteralOffset();
568 });
569
570 return linker_patches;
571}
572
David Brazdil58282f42016-01-14 12:45:10 +0000573CompiledMethod* OptimizingCompiler::Emit(ArenaAllocator* arena,
574 CodeVectorAllocator* code_allocator,
575 CodeGenerator* codegen,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000576 CompilerDriver* compiler_driver,
577 const DexFile::CodeItem* code_item) const {
Vladimir Marko58155012015-08-19 12:49:41 +0000578 ArenaVector<LinkerPatch> linker_patches = EmitAndSortLinkerPatches(codegen);
Vladimir Markof9f64412015-09-02 14:05:49 +0100579 ArenaVector<uint8_t> stack_map(arena->Adapter(kArenaAllocStackMaps));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000580 stack_map.resize(codegen->ComputeStackMapsSize());
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000581 codegen->BuildStackMaps(MemoryRegion(stack_map.data(), stack_map.size()), *code_item);
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000582
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100583 CompiledMethod* compiled_method = CompiledMethod::SwapAllocCompiledMethod(
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000584 compiler_driver,
585 codegen->GetInstructionSet(),
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000586 ArrayRef<const uint8_t>(code_allocator->GetMemory()),
Roland Levillainaa9b7c42015-02-17 15:40:09 +0000587 // Follow Quick's behavior and set the frame size to zero if it is
588 // considered "empty" (see the definition of
589 // art::CodeGenerator::HasEmptyFrame).
590 codegen->HasEmptyFrame() ? 0 : codegen->GetFrameSize(),
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000591 codegen->GetCoreSpillMask(),
Nicolas Geoffrayd97dc402015-01-22 13:50:01 +0000592 codegen->GetFpuSpillMask(),
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000593 ArrayRef<const SrcMapElem>(),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100594 ArrayRef<const uint8_t>(), // mapping_table.
595 ArrayRef<const uint8_t>(stack_map),
596 ArrayRef<const uint8_t>(), // native_gc_map.
597 ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data()),
Vladimir Marko58155012015-08-19 12:49:41 +0000598 ArrayRef<const LinkerPatch>(linker_patches));
Mathieu Chartiered150002015-08-28 11:16:54 -0700599
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100600 return compiled_method;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000601}
602
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000603CodeGenerator* OptimizingCompiler::TryCompile(ArenaAllocator* arena,
604 CodeVectorAllocator* code_allocator,
605 const DexFile::CodeItem* code_item,
606 uint32_t access_flags,
607 InvokeType invoke_type,
608 uint16_t class_def_idx,
609 uint32_t method_idx,
610 jobject class_loader,
611 const DexFile& dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000612 Handle<mirror::DexCache> dex_cache,
613 bool osr) const {
Calin Juravle2be39e02015-04-21 13:56:34 +0100614 MaybeRecordStat(MethodCompilationStat::kAttemptCompilation);
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000615 CompilerDriver* compiler_driver = GetCompilerDriver();
616 InstructionSet instruction_set = compiler_driver->GetInstructionSet();
Calin Juravlecff8cc72015-10-09 12:03:24 +0100617
Roland Levillain3b359c72015-11-17 19:35:12 +0000618 // Always use the Thumb-2 assembler: some runtime functionality
619 // (like implicit stack overflow checks) assume Thumb-2.
Nicolas Geoffray8d486732014-07-16 16:23:40 +0100620 if (instruction_set == kArm) {
621 instruction_set = kThumb2;
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100622 }
623
624 // Do not attempt to compile on architectures we do not support.
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000625 if (!IsInstructionSetSupported(instruction_set)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100626 MaybeRecordStat(MethodCompilationStat::kNotCompiledUnsupportedIsa);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100627 return nullptr;
628 }
629
Roland Levillain0d5a2812015-11-13 10:07:31 +0000630 // When read barriers are enabled, do not attempt to compile for
631 // instruction sets that have no read barrier support.
632 if (kEmitCompilerReadBarrier && !InstructionSetSupportsReadBarrier(instruction_set)) {
633 return nullptr;
634 }
635
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000636 if (Compiler::IsPathologicalCase(*code_item, method_idx, dex_file)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100637 MaybeRecordStat(MethodCompilationStat::kNotCompiledPathological);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000638 return nullptr;
639 }
640
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000641 // Implementation of the space filter: do not compile a code item whose size in
Nicolas Geoffray432bf3d2015-07-17 11:11:09 +0100642 // code units is bigger than 128.
643 static constexpr size_t kSpaceFilterOptimizingThreshold = 128;
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000644 const CompilerOptions& compiler_options = compiler_driver->GetCompilerOptions();
645 if ((compiler_options.GetCompilerFilter() == CompilerOptions::kSpace)
646 && (code_item->insns_size_in_code_units_ > kSpaceFilterOptimizingThreshold)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100647 MaybeRecordStat(MethodCompilationStat::kNotCompiledSpaceFilter);
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000648 return nullptr;
649 }
650
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000651 DexCompilationUnit dex_compilation_unit(
Nicolas Geoffray9523a3e2015-07-17 11:51:28 +0000652 nullptr, class_loader, Runtime::Current()->GetClassLinker(), dex_file, code_item,
Ian Rogers72d32622014-05-06 16:20:11 -0700653 class_def_idx, method_idx, access_flags,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000654 nullptr, dex_cache);
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000655
Calin Juravle3cd4fc82015-05-14 15:15:42 +0100656 bool requires_barrier = dex_compilation_unit.IsConstructor()
657 && compiler_driver->RequiresConstructorBarrier(Thread::Current(),
658 dex_compilation_unit.GetDexFile(),
659 dex_compilation_unit.GetClassDefIndex());
David Brazdilbadd8262016-02-02 16:28:56 +0000660
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000661 HGraph* graph = new (arena) HGraph(
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000662 arena,
663 dex_file,
664 method_idx,
665 requires_barrier,
666 compiler_driver->GetInstructionSet(),
667 kInvalidInvokeType,
668 compiler_driver->GetCompilerOptions().GetDebuggable(),
669 osr);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000670
David Brazdilbadd8262016-02-02 16:28:56 +0000671 const uint8_t* interpreter_metadata = nullptr;
672 {
673 ScopedObjectAccess soa(Thread::Current());
674 StackHandleScope<1> hs(soa.Self());
675 Handle<mirror::ClassLoader> loader(hs.NewHandle(
676 soa.Decode<mirror::ClassLoader*>(class_loader)));
677 ArtMethod* art_method = compiler_driver->ResolveMethod(
678 soa, dex_cache, loader, &dex_compilation_unit, method_idx, invoke_type);
679 // We may not get a method, for example if its class is erroneous.
680 if (art_method != nullptr) {
681 graph->SetArtMethod(art_method);
682 interpreter_metadata = art_method->GetQuickenedInfo();
683 }
684 }
685
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000686 std::unique_ptr<CodeGenerator> codegen(
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000687 CodeGenerator::Create(graph,
688 instruction_set,
689 *compiler_driver->GetInstructionSetFeatures(),
690 compiler_driver->GetCompilerOptions()));
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000691 if (codegen.get() == nullptr) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100692 MaybeRecordStat(MethodCompilationStat::kNotCompiledNoCodegen);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000693 return nullptr;
694 }
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100695 codegen->GetAssembler()->cfi().SetEnabled(
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000696 compiler_driver->GetCompilerOptions().GenerateAnyDebugInfo());
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000697
David Brazdil69ba7b72015-06-23 18:27:30 +0100698 PassObserver pass_observer(graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100699 codegen.get(),
700 visualizer_output_.get(),
701 compiler_driver);
David Brazdil5e8b1372015-01-23 14:39:08 +0000702
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000703 VLOG(compiler) << "Building " << pass_observer.GetMethodName();
David Brazdil5e8b1372015-01-23 14:39:08 +0000704
David Brazdil809658e2015-02-05 11:34:02 +0000705 {
David Brazdilbadd8262016-02-02 16:28:56 +0000706 ScopedObjectAccess soa(Thread::Current());
707 StackHandleScopeCollection handles(soa.Self());
708 // Do not hold `mutator_lock_` between optimizations.
709 ScopedThreadSuspension sts(soa.Self(), kNative);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100710
David Brazdilbadd8262016-02-02 16:28:56 +0000711 {
712 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
713 HGraphBuilder builder(graph,
714 &dex_compilation_unit,
715 &dex_compilation_unit,
716 &dex_file,
717 compiler_driver,
718 compilation_stats_.get(),
719 interpreter_metadata,
720 dex_cache);
721 GraphAnalysisResult result = builder.BuildGraph(*code_item, &handles);
722 if (result != kAnalysisSuccess) {
723 switch (result) {
724 case kAnalysisInvalidBytecode:
725 break;
726 case kAnalysisFailThrowCatchLoop:
727 MaybeRecordStat(MethodCompilationStat::kNotCompiledThrowCatchLoop);
728 break;
729 case kAnalysisFailAmbiguousArrayOp:
730 MaybeRecordStat(MethodCompilationStat::kNotCompiledAmbiguousArrayOp);
731 break;
732 case kAnalysisSuccess:
733 UNREACHABLE();
734 }
735 pass_observer.SetGraphInBadState();
736 return nullptr;
David Brazdil809658e2015-02-05 11:34:02 +0000737 }
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000738 }
David Brazdil58282f42016-01-14 12:45:10 +0000739
David Brazdilbadd8262016-02-02 16:28:56 +0000740 RunOptimizations(graph,
741 codegen.get(),
742 compiler_driver,
743 compilation_stats_.get(),
744 dex_compilation_unit,
745 &pass_observer,
746 &handles);
747
748 codegen->Compile(code_allocator);
749 pass_observer.DumpDisassembly();
750 }
Vladimir Markof9f64412015-09-02 14:05:49 +0100751
752 if (kArenaAllocatorCountAllocations) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000753 if (arena->BytesAllocated() > 4 * MB) {
754 MemStats mem_stats(arena->GetMemStats());
Vladimir Markof9f64412015-09-02 14:05:49 +0100755 LOG(INFO) << PrettyMethod(method_idx, dex_file) << " " << Dumpable<MemStats>(mem_stats);
756 }
757 }
758
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000759 return codegen.release();
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000760}
761
Calin Juravle07380a22015-09-17 14:15:12 +0100762static bool CanHandleVerificationFailure(const VerifiedMethod* verified_method) {
763 // For access errors the compiler will use the unresolved helpers (e.g. HInvokeUnresolved).
764 uint32_t unresolved_mask = verifier::VerifyError::VERIFY_ERROR_NO_CLASS
765 | verifier::VerifyError::VERIFY_ERROR_ACCESS_CLASS
766 | verifier::VerifyError::VERIFY_ERROR_ACCESS_FIELD
767 | verifier::VerifyError::VERIFY_ERROR_ACCESS_METHOD;
Calin Juravle175dc732015-08-25 15:42:32 +0100768 return (verified_method->GetEncounteredVerificationFailures() & (~unresolved_mask)) == 0;
769}
770
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000771CompiledMethod* OptimizingCompiler::Compile(const DexFile::CodeItem* code_item,
772 uint32_t access_flags,
773 InvokeType invoke_type,
774 uint16_t class_def_idx,
775 uint32_t method_idx,
Calin Juravlef1c6d9e2015-04-13 18:42:21 +0100776 jobject jclass_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700777 const DexFile& dex_file,
778 Handle<mirror::DexCache> dex_cache) const {
Calin Juravlef1c6d9e2015-04-13 18:42:21 +0100779 CompilerDriver* compiler_driver = GetCompilerDriver();
780 CompiledMethod* method = nullptr;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000781 DCHECK(Runtime::Current()->IsAotCompiler());
782 const VerifiedMethod* verified_method = compiler_driver->GetVerifiedMethod(&dex_file, method_idx);
783 DCHECK(!verified_method->HasRuntimeThrow());
784 if (compiler_driver->IsMethodVerifiedWithoutFailures(method_idx, class_def_idx, dex_file)
785 || CanHandleVerificationFailure(verified_method)) {
786 ArenaAllocator arena(Runtime::Current()->GetArenaPool());
787 CodeVectorAllocator code_allocator(&arena);
788 std::unique_ptr<CodeGenerator> codegen(
789 TryCompile(&arena,
790 &code_allocator,
791 code_item,
792 access_flags,
793 invoke_type,
794 class_def_idx,
795 method_idx,
796 jclass_loader,
797 dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000798 dex_cache,
799 /* osr */ false));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000800 if (codegen.get() != nullptr) {
Calin Juravlead543382015-11-19 17:26:29 +0000801 MaybeRecordStat(MethodCompilationStat::kCompiled);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000802 method = Emit(&arena, &code_allocator, codegen.get(), compiler_driver, code_item);
Calin Juravlef1c6d9e2015-04-13 18:42:21 +0100803 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100804 } else {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000805 if (compiler_driver->GetCompilerOptions().VerifyAtRuntime()) {
806 MaybeRecordStat(MethodCompilationStat::kNotCompiledVerifyAtRuntime);
807 } else {
Calin Juravlead543382015-11-19 17:26:29 +0000808 MaybeRecordStat(MethodCompilationStat::kNotCompiledVerificationError);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000809 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +0100810 }
811
Calin Juravlecff8cc72015-10-09 12:03:24 +0100812 if (kIsDebugBuild &&
813 IsCompilingWithCoreImage() &&
Roland Levillain0d5a2812015-11-13 10:07:31 +0000814 IsInstructionSetSupported(compiler_driver->GetInstructionSet()) &&
815 (!kEmitCompilerReadBarrier ||
816 InstructionSetSupportsReadBarrier(compiler_driver->GetInstructionSet()))) {
817 // For testing purposes, we put a special marker on method names
818 // that should be compiled with this compiler (when the the
819 // instruction set is supported -- and has support for read
820 // barriers, if they are enabled). This makes sure we're not
821 // regressing.
Calin Juravle09b1d6f2015-10-07 12:08:54 +0100822 std::string method_name = PrettyMethod(method_idx, dex_file);
823 bool shouldCompile = method_name.find("$opt$") != std::string::npos;
824 DCHECK((method != nullptr) || !shouldCompile) << "Didn't compile " << method_name;
825 }
826
Nicolas Geoffray12be74e2015-03-30 13:29:08 +0100827 return method;
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000828}
829
Andreas Gampe53c913b2014-08-12 23:19:23 -0700830Compiler* CreateOptimizingCompiler(CompilerDriver* driver) {
831 return new OptimizingCompiler(driver);
832}
833
Nicolas Geoffray335005e2015-06-25 10:01:47 +0100834bool IsCompilingWithCoreImage() {
835 const std::string& image = Runtime::Current()->GetImageLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800836 // TODO: This is under-approximating...
837 if (EndsWith(image, "core.art") || EndsWith(image, "core-optimizing.art")) {
838 return true;
839 }
840 return false;
Nicolas Geoffray335005e2015-06-25 10:01:47 +0100841}
842
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000843bool OptimizingCompiler::JitCompile(Thread* self,
844 jit::JitCodeCache* code_cache,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000845 ArtMethod* method,
846 bool osr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000847 StackHandleScope<2> hs(self);
848 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
849 method->GetDeclaringClass()->GetClassLoader()));
850 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
851
852 jobject jclass_loader = class_loader.ToJObject();
853 const DexFile* dex_file = method->GetDexFile();
854 const uint16_t class_def_idx = method->GetClassDefIndex();
855 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
856 const uint32_t method_idx = method->GetDexMethodIndex();
857 const uint32_t access_flags = method->GetAccessFlags();
858 const InvokeType invoke_type = method->GetInvokeType();
859
860 ArenaAllocator arena(Runtime::Current()->GetArenaPool());
861 CodeVectorAllocator code_allocator(&arena);
862 std::unique_ptr<CodeGenerator> codegen;
863 {
864 // Go to native so that we don't block GC during compilation.
865 ScopedThreadSuspension sts(self, kNative);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000866 codegen.reset(
867 TryCompile(&arena,
868 &code_allocator,
869 code_item,
870 access_flags,
871 invoke_type,
872 class_def_idx,
873 method_idx,
874 jclass_loader,
875 *dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000876 dex_cache,
877 osr));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000878 if (codegen.get() == nullptr) {
879 return false;
880 }
881 }
882
883 size_t stack_map_size = codegen->ComputeStackMapsSize();
884 uint8_t* stack_map_data = code_cache->ReserveData(self, stack_map_size);
885 if (stack_map_data == nullptr) {
886 return false;
887 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100888 MaybeRecordStat(MethodCompilationStat::kCompiled);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000889 codegen->BuildStackMaps(MemoryRegion(stack_map_data, stack_map_size), *code_item);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000890 const void* code = code_cache->CommitCode(
891 self,
892 method,
893 nullptr,
894 stack_map_data,
895 nullptr,
896 codegen->HasEmptyFrame() ? 0 : codegen->GetFrameSize(),
897 codegen->GetCoreSpillMask(),
898 codegen->GetFpuSpillMask(),
899 code_allocator.GetMemory().data(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000900 code_allocator.GetSize(),
901 osr);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000902
903 if (code == nullptr) {
904 code_cache->ClearData(self, stack_map_data);
905 return false;
906 }
907
David Srbecky5cc349f2015-12-18 15:04:48 +0000908 if (GetCompilerDriver()->GetCompilerOptions().GetGenerateDebugInfo()) {
909 const auto* method_header = reinterpret_cast<const OatQuickMethodHeader*>(code);
910 const uintptr_t code_address = reinterpret_cast<uintptr_t>(method_header->GetCode());
911 CompiledMethod compiled_method(
912 GetCompilerDriver(),
913 codegen->GetInstructionSet(),
914 ArrayRef<const uint8_t>(code_allocator.GetMemory()),
915 codegen->HasEmptyFrame() ? 0 : codegen->GetFrameSize(),
916 codegen->GetCoreSpillMask(),
917 codegen->GetFpuSpillMask(),
918 ArrayRef<const SrcMapElem>(),
919 ArrayRef<const uint8_t>(), // mapping_table.
920 ArrayRef<const uint8_t>(stack_map_data, stack_map_size),
921 ArrayRef<const uint8_t>(), // native_gc_map.
922 ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data()),
923 ArrayRef<const LinkerPatch>());
David Srbeckyc5bfa972016-02-05 15:49:10 +0000924 debug::MethodDebugInfo method_debug_info {
David Srbecky5cc349f2015-12-18 15:04:48 +0000925 dex_file,
926 class_def_idx,
927 method_idx,
928 access_flags,
929 code_item,
930 false, // deduped.
931 code_address,
932 code_address + code_allocator.GetSize(),
933 &compiled_method
934 };
David Srbeckyc5bfa972016-02-05 15:49:10 +0000935 ArrayRef<const uint8_t> elf_file = debug::WriteDebugElfFileForMethod(method_debug_info);
David Srbecky5cc349f2015-12-18 15:04:48 +0000936 CreateJITCodeEntryForAddress(code_address,
937 std::unique_ptr<const uint8_t[]>(elf_file.data()),
938 elf_file.size());
939 }
940
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000941 return true;
942}
943
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000944} // namespace art