blob: 1add660f1b5213a3221956d041a28ff04cd77b4c [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>
Andreas Gampea0d81af2016-10-27 12:04:57 -070021#include <sstream>
22
Nicolas Geoffray787c3072014-03-17 10:20:19 +000023#include <stdint.h>
24
Aart Bikd1c40452016-03-02 16:06:13 -080025#ifdef ART_ENABLE_CODEGEN_arm
Vladimir Markob4536b72015-11-24 13:45:23 +000026#include "dex_cache_array_fixups_arm.h"
27#endif
28
29#ifdef ART_ENABLE_CODEGEN_arm64
Alexandre Rames44b9cf92015-08-19 15:39:06 +010030#include "instruction_simplifier_arm64.h"
31#endif
32
Alexey Frunzee3fb2452016-05-10 16:08:05 -070033#ifdef ART_ENABLE_CODEGEN_mips
34#include "dex_cache_array_fixups_mips.h"
35#include "pc_relative_fixups_mips.h"
36#endif
37
Mark Mendell0616ae02015-04-17 12:49:27 -040038#ifdef ART_ENABLE_CODEGEN_x86
Vladimir Marko0f7dca42015-11-02 14:36:43 +000039#include "pc_relative_fixups_x86.h"
Mark Mendell0616ae02015-04-17 12:49:27 -040040#endif
41
Mark Mendellee8d9712016-07-12 11:13:15 -040042#if defined(ART_ENABLE_CODEGEN_x86) || defined(ART_ENABLE_CODEGEN_x86_64)
43#include "x86_memory_gen.h"
44#endif
45
Mathieu Chartiere401d142015-04-22 13:56:20 -070046#include "art_method-inl.h"
Mathieu Chartierb666f482015-02-18 14:33:14 -080047#include "base/arena_allocator.h"
Vladimir Markof9f64412015-09-02 14:05:49 +010048#include "base/arena_containers.h"
David Brazdil5e8b1372015-01-23 14:39:08 +000049#include "base/dumpable.h"
Vladimir Markoc90d7c72015-10-06 17:30:45 +000050#include "base/macros.h"
Andreas Gampea0d81af2016-10-27 12:04:57 -070051#include "base/mutex.h"
David Brazdil5e8b1372015-01-23 14:39:08 +000052#include "base/timing_logger.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070053#include "bounds_check_elimination.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000054#include "builder.h"
55#include "code_generator.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000056#include "compiled_method.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070057#include "compiler.h"
Roland Levillain75be2832014-10-17 17:02:00 +010058#include "constant_folding.h"
59#include "dead_code_elimination.h"
David Srbeckyc5bfa972016-02-05 15:49:10 +000060#include "debug/elf_debug_writer.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000061#include "debug/method_debug_info.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010062#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000063#include "dex/verified_method.h"
Nicolas Geoffray9523a3e2015-07-17 11:51:28 +000064#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000065#include "driver/compiler_options.h"
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000066#include "driver/dex_compilation_unit.h"
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +000067#include "elf_writer_quick.h"
David Brazdil69ba7b72015-06-23 18:27:30 +010068#include "graph_checker.h"
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010069#include "graph_visualizer.h"
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +010070#include "gvn.h"
Aart Bik22af3be2015-09-10 12:50:58 -070071#include "induction_var_analysis.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000072#include "inliner.h"
Nicolas Geoffray3c049742014-09-24 18:10:46 +010073#include "instruction_simplifier.h"
Artem Udovichenko4a0dad62016-01-26 12:28:31 +030074#include "instruction_simplifier_arm.h"
Andreas Gampe71fb52f2014-12-29 17:43:08 -080075#include "intrinsics.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000076#include "jit/debugger_interface.h"
Nicolas Geoffraya4f81542016-03-08 16:57:48 +000077#include "jit/jit.h"
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +000078#include "jit/jit_code_cache.h"
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +000079#include "jni/quick/jni_compiler.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000080#include "licm.h"
Mingyao Yang8df69d42015-10-22 15:40:58 -070081#include "load_store_elimination.h"
Aart Bik281c6812016-08-26 11:31:48 -070082#include "loop_optimization.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000083#include "nodes.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000084#include "oat_quick_method_header.h"
Nicolas Geoffray26a25ef2014-09-30 13:54:09 +010085#include "prepare_for_register_allocation.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010086#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070087#include "register_allocator_linear_scan.h"
David Brazdil74eb1b22015-12-14 11:44:01 +000088#include "select_generator.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010089#include "sharpening.h"
Nicolas Geoffray827eedb2015-01-26 15:18:36 +000090#include "side_effects_analysis.h"
Nicolas Geoffray31596742014-11-24 15:28:45 +000091#include "ssa_builder.h"
Nicolas Geoffray804d0932014-05-02 08:46:00 +010092#include "ssa_liveness_analysis.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000093#include "ssa_phi_elimination.h"
David Srbeckyc6b4dd82015-04-07 20:32:43 +010094#include "utils/assembler.h"
Calin Juravle175dc732015-08-25 15:42:32 +010095#include "verifier/method_verifier.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000096
97namespace art {
98
Vladimir Marko3a40bf22016-03-22 16:26:33 +000099static constexpr size_t kArenaAllocatorMemoryReportThreshold = 8 * MB;
100
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700101static constexpr const char* kPassNameSeparator = "$";
102
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000103/**
104 * Used by the code generator, to allocate the code in a vector.
105 */
106class CodeVectorAllocator FINAL : public CodeAllocator {
107 public:
Vladimir Markof9f64412015-09-02 14:05:49 +0100108 explicit CodeVectorAllocator(ArenaAllocator* arena)
109 : memory_(arena->Adapter(kArenaAllocCodeBuffer)),
110 size_(0) {}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000111
112 virtual uint8_t* Allocate(size_t size) {
113 size_ = size;
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000114 memory_.resize(size);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000115 return &memory_[0];
116 }
117
118 size_t GetSize() const { return size_; }
Vladimir Markof9f64412015-09-02 14:05:49 +0100119 const ArenaVector<uint8_t>& GetMemory() const { return memory_; }
Nicolas Geoffray75afcdd2016-11-10 10:38:11 +0000120 uint8_t* GetData() { return memory_.data(); }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000121
122 private:
Vladimir Markof9f64412015-09-02 14:05:49 +0100123 ArenaVector<uint8_t> memory_;
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000124 size_t size_;
125
126 DISALLOW_COPY_AND_ASSIGN(CodeVectorAllocator);
127};
128
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100129/**
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100130 * Filter to apply to the visualizer. Methods whose name contain that filter will
David Brazdilee690a32014-12-01 17:04:16 +0000131 * be dumped.
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100132 */
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700133static constexpr const char kStringFilter[] = "";
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100134
David Brazdil69ba7b72015-06-23 18:27:30 +0100135class PassScope;
David Brazdil809658e2015-02-05 11:34:02 +0000136
David Brazdil69ba7b72015-06-23 18:27:30 +0100137class PassObserver : public ValueObject {
David Brazdil5e8b1372015-01-23 14:39:08 +0000138 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100139 PassObserver(HGraph* graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100140 CodeGenerator* codegen,
141 std::ostream* visualizer_output,
Andreas Gampea0d81af2016-10-27 12:04:57 -0700142 CompilerDriver* compiler_driver,
143 Mutex& dump_mutex)
David Brazdil69ba7b72015-06-23 18:27:30 +0100144 : graph_(graph),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000145 cached_method_name_(),
David Brazdil809658e2015-02-05 11:34:02 +0000146 timing_logger_enabled_(compiler_driver->GetDumpPasses()),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000147 timing_logger_(timing_logger_enabled_ ? GetMethodName() : "", true, true),
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100148 disasm_info_(graph->GetArena()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700149 visualizer_oss_(),
150 visualizer_output_(visualizer_output),
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000151 visualizer_enabled_(!compiler_driver->GetCompilerOptions().GetDumpCfgFileName().empty()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700152 visualizer_(&visualizer_oss_, graph, *codegen),
153 visualizer_dump_mutex_(dump_mutex),
David Brazdil69ba7b72015-06-23 18:27:30 +0100154 graph_in_bad_state_(false) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700155 if (timing_logger_enabled_ || visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000156 if (!IsVerboseMethod(compiler_driver, GetMethodName())) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700157 timing_logger_enabled_ = visualizer_enabled_ = false;
158 }
159 if (visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000160 visualizer_.PrintHeader(GetMethodName());
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700161 codegen->SetDisassemblyInformation(&disasm_info_);
162 }
David Brazdil62e074f2015-04-07 18:09:37 +0100163 }
David Brazdil5e8b1372015-01-23 14:39:08 +0000164 }
165
David Brazdil69ba7b72015-06-23 18:27:30 +0100166 ~PassObserver() {
David Brazdil5e8b1372015-01-23 14:39:08 +0000167 if (timing_logger_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000168 LOG(INFO) << "TIMINGS " << GetMethodName();
David Brazdil5e8b1372015-01-23 14:39:08 +0000169 LOG(INFO) << Dumpable<TimingLogger>(timing_logger_);
170 }
Andreas Gampea0d81af2016-10-27 12:04:57 -0700171 if (visualizer_enabled_) {
172 MutexLock mu(Thread::Current(), visualizer_dump_mutex_);
173 *visualizer_output_ << visualizer_oss_.str();
Roland Levillainb0103ca2016-11-01 14:48:47 +0000174 // The destructor of `visualizer_output_` is normally
175 // responsible for flushing (and closing) the stream, but it
176 // won't be invoked during fast exits in non-debug mode -- see
177 // art::Dex2Oat::~Dex2Oat, which explicitly abandons some
178 // objects (such as the compiler driver) in non-debug mode, to
179 // avoid the cost of destructing them. Therefore we explicitly
180 // flush the stream here to prevent truncated CFG visualizer
181 // files.
182 visualizer_output_->flush();
Andreas Gampea0d81af2016-10-27 12:04:57 -0700183 }
David Brazdil5e8b1372015-01-23 14:39:08 +0000184 }
185
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100186 void DumpDisassembly() const {
187 if (visualizer_enabled_) {
188 visualizer_.DumpGraphWithDisassembly();
189 }
190 }
191
David Brazdil69ba7b72015-06-23 18:27:30 +0100192 void SetGraphInBadState() { graph_in_bad_state_ = true; }
193
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000194 const char* GetMethodName() {
195 // PrettyMethod() is expensive, so we delay calling it until we actually have to.
196 if (cached_method_name_.empty()) {
David Sehr709b0702016-10-13 09:12:37 -0700197 cached_method_name_ = graph_->GetDexFile().PrettyMethod(graph_->GetMethodIdx());
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000198 }
199 return cached_method_name_.c_str();
200 }
201
David Brazdil5e8b1372015-01-23 14:39:08 +0000202 private:
David Brazdil809658e2015-02-05 11:34:02 +0000203 void StartPass(const char* pass_name) {
Wojciech Staszkiewicze7060702016-08-16 17:31:19 -0700204 VLOG(compiler) << "Starting pass: " << pass_name;
David Brazdil809658e2015-02-05 11:34:02 +0000205 // Dump graph first, then start timer.
206 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100207 visualizer_.DumpGraph(pass_name, /* is_after_pass */ false, graph_in_bad_state_);
David Brazdil809658e2015-02-05 11:34:02 +0000208 }
209 if (timing_logger_enabled_) {
210 timing_logger_.StartTiming(pass_name);
211 }
212 }
213
214 void EndPass(const char* pass_name) {
215 // Pause timer first, then dump graph.
216 if (timing_logger_enabled_) {
217 timing_logger_.EndTiming();
218 }
219 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100220 visualizer_.DumpGraph(pass_name, /* is_after_pass */ true, graph_in_bad_state_);
David Brazdil809658e2015-02-05 11:34:02 +0000221 }
David Brazdil69ba7b72015-06-23 18:27:30 +0100222
223 // Validate the HGraph if running in debug mode.
224 if (kIsDebugBuild) {
225 if (!graph_in_bad_state_) {
David Brazdilbadd8262016-02-02 16:28:56 +0000226 GraphChecker checker(graph_);
227 checker.Run();
228 if (!checker.IsValid()) {
229 LOG(FATAL) << "Error after " << pass_name << ": " << Dumpable<GraphChecker>(checker);
David Brazdil69ba7b72015-06-23 18:27:30 +0100230 }
231 }
232 }
David Brazdil809658e2015-02-05 11:34:02 +0000233 }
234
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700235 static bool IsVerboseMethod(CompilerDriver* compiler_driver, const char* method_name) {
236 // Test an exact match to --verbose-methods. If verbose-methods is set, this overrides an
237 // empty kStringFilter matching all methods.
238 if (compiler_driver->GetCompilerOptions().HasVerboseMethods()) {
239 return compiler_driver->GetCompilerOptions().IsVerboseMethod(method_name);
240 }
241
242 // Test the kStringFilter sub-string. constexpr helper variable to silence unreachable-code
243 // warning when the string is empty.
244 constexpr bool kStringFilterEmpty = arraysize(kStringFilter) <= 1;
245 if (kStringFilterEmpty || strstr(method_name, kStringFilter) != nullptr) {
246 return true;
247 }
248
249 return false;
250 }
251
David Brazdil69ba7b72015-06-23 18:27:30 +0100252 HGraph* const graph_;
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000253
254 std::string cached_method_name_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000255
256 bool timing_logger_enabled_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000257 TimingLogger timing_logger_;
258
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100259 DisassemblyInformation disasm_info_;
260
Andreas Gampea0d81af2016-10-27 12:04:57 -0700261 std::ostringstream visualizer_oss_;
262 std::ostream* visualizer_output_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000263 bool visualizer_enabled_;
264 HGraphVisualizer visualizer_;
Andreas Gampea0d81af2016-10-27 12:04:57 -0700265 Mutex& visualizer_dump_mutex_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000266
David Brazdil69ba7b72015-06-23 18:27:30 +0100267 // Flag to be set by the compiler if the pass failed and the graph is not
268 // expected to validate.
269 bool graph_in_bad_state_;
David Brazdil809658e2015-02-05 11:34:02 +0000270
David Brazdil69ba7b72015-06-23 18:27:30 +0100271 friend PassScope;
272
273 DISALLOW_COPY_AND_ASSIGN(PassObserver);
David Brazdil5e8b1372015-01-23 14:39:08 +0000274};
275
David Brazdil69ba7b72015-06-23 18:27:30 +0100276class PassScope : public ValueObject {
David Brazdil809658e2015-02-05 11:34:02 +0000277 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100278 PassScope(const char *pass_name, PassObserver* pass_observer)
David Brazdil809658e2015-02-05 11:34:02 +0000279 : pass_name_(pass_name),
David Brazdil69ba7b72015-06-23 18:27:30 +0100280 pass_observer_(pass_observer) {
281 pass_observer_->StartPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000282 }
283
David Brazdil69ba7b72015-06-23 18:27:30 +0100284 ~PassScope() {
285 pass_observer_->EndPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000286 }
287
288 private:
289 const char* const pass_name_;
David Brazdil69ba7b72015-06-23 18:27:30 +0100290 PassObserver* const pass_observer_;
David Brazdil809658e2015-02-05 11:34:02 +0000291};
292
Andreas Gampe53c913b2014-08-12 23:19:23 -0700293class OptimizingCompiler FINAL : public Compiler {
294 public:
295 explicit OptimizingCompiler(CompilerDriver* driver);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700296 ~OptimizingCompiler() OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700297
Vladimir Markodf739842016-03-23 16:59:07 +0000298 bool CanCompileMethod(uint32_t method_idx, const DexFile& dex_file) const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700299
300 CompiledMethod* Compile(const DexFile::CodeItem* code_item,
301 uint32_t access_flags,
302 InvokeType invoke_type,
303 uint16_t class_def_idx,
304 uint32_t method_idx,
305 jobject class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700306 const DexFile& dex_file,
307 Handle<mirror::DexCache> dex_cache) const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700308
Andreas Gampe53c913b2014-08-12 23:19:23 -0700309 CompiledMethod* JniCompile(uint32_t access_flags,
310 uint32_t method_idx,
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700311 const DexFile& dex_file,
312 JniOptimizationFlags optimization_flags) const OVERRIDE {
313 return ArtQuickJniCompileMethod(GetCompilerDriver(),
314 access_flags,
315 method_idx,
316 dex_file,
317 optimization_flags);
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000318 }
Andreas Gampe53c913b2014-08-12 23:19:23 -0700319
Mathieu Chartiere401d142015-04-22 13:56:20 -0700320 uintptr_t GetEntryPointOf(ArtMethod* method) const OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700321 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000322 return reinterpret_cast<uintptr_t>(method->GetEntryPointFromQuickCompiledCodePtrSize(
323 InstructionSetPointerSize(GetCompilerDriver()->GetInstructionSet())));
324 }
Andreas Gampe53c913b2014-08-12 23:19:23 -0700325
David Brazdilee690a32014-12-01 17:04:16 +0000326 void Init() OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700327
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000328 void UnInit() const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700329
Calin Juravle2be39e02015-04-21 13:56:34 +0100330 void MaybeRecordStat(MethodCompilationStat compilation_stat) const {
331 if (compilation_stats_.get() != nullptr) {
332 compilation_stats_->RecordStat(compilation_stat);
333 }
334 }
335
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000336 bool JitCompile(Thread* self, jit::JitCodeCache* code_cache, ArtMethod* method, bool osr)
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000337 OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700338 REQUIRES_SHARED(Locks::mutator_lock_);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000339
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700340 private:
341 void RunOptimizations(HGraph* graph,
342 CodeGenerator* codegen,
343 CompilerDriver* driver,
344 const DexCompilationUnit& dex_compilation_unit,
345 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700346 VariableSizedHandleScope* handles) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700347
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700348 void RunOptimizations(HOptimization* optimizations[],
349 size_t length,
350 PassObserver* pass_observer) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700351
Andreas Gampe53c913b2014-08-12 23:19:23 -0700352 private:
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000353 // Create a 'CompiledMethod' for an optimized graph.
David Brazdil58282f42016-01-14 12:45:10 +0000354 CompiledMethod* Emit(ArenaAllocator* arena,
355 CodeVectorAllocator* code_allocator,
356 CodeGenerator* codegen,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000357 CompilerDriver* driver,
358 const DexFile::CodeItem* item) const;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000359
360 // Try compiling a method and return the code generator used for
361 // compiling it.
362 // This method:
363 // 1) Builds the graph. Returns null if it failed to build it.
David Brazdil58282f42016-01-14 12:45:10 +0000364 // 2) Transforms the graph to SSA. Returns null if it failed.
365 // 3) Runs optimizations on the graph, including register allocator.
366 // 4) Generates code with the `code_allocator` provided.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000367 CodeGenerator* TryCompile(ArenaAllocator* arena,
368 CodeVectorAllocator* code_allocator,
369 const DexFile::CodeItem* code_item,
370 uint32_t access_flags,
371 InvokeType invoke_type,
372 uint16_t class_def_idx,
373 uint32_t method_idx,
374 jobject class_loader,
375 const DexFile& dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000376 Handle<mirror::DexCache> dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000377 ArtMethod* method,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000378 bool osr) const;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000379
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700380 void MaybeRunInliner(HGraph* graph,
381 CodeGenerator* codegen,
382 CompilerDriver* driver,
383 const DexCompilationUnit& dex_compilation_unit,
384 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700385 VariableSizedHandleScope* handles) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700386
387 void RunArchOptimizations(InstructionSet instruction_set,
388 HGraph* graph,
389 CodeGenerator* codegen,
390 PassObserver* pass_observer) const;
391
Calin Juravle2be39e02015-04-21 13:56:34 +0100392 std::unique_ptr<OptimizingCompilerStats> compilation_stats_;
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100393
Andreas Gampe53c913b2014-08-12 23:19:23 -0700394 std::unique_ptr<std::ostream> visualizer_output_;
395
Andreas Gampea0d81af2016-10-27 12:04:57 -0700396 mutable Mutex dump_mutex_; // To synchronize visualizer writing.
397
Andreas Gampe53c913b2014-08-12 23:19:23 -0700398 DISALLOW_COPY_AND_ASSIGN(OptimizingCompiler);
399};
400
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100401static const int kMaximumCompilationTimeBeforeWarning = 100; /* ms */
402
403OptimizingCompiler::OptimizingCompiler(CompilerDriver* driver)
Andreas Gampea0d81af2016-10-27 12:04:57 -0700404 : Compiler(driver, kMaximumCompilationTimeBeforeWarning),
405 dump_mutex_("Visualizer dump lock") {}
David Brazdilee690a32014-12-01 17:04:16 +0000406
407void OptimizingCompiler::Init() {
408 // Enable C1visualizer output. Must be done in Init() because the compiler
409 // driver is not fully initialized when passed to the compiler's constructor.
410 CompilerDriver* driver = GetCompilerDriver();
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000411 const std::string cfg_file_name = driver->GetCompilerOptions().GetDumpCfgFileName();
David Brazdil866c0312015-01-13 21:21:31 +0000412 if (!cfg_file_name.empty()) {
Calin Juravle87000a92015-08-24 15:34:44 +0100413 std::ios_base::openmode cfg_file_mode =
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000414 driver->GetCompilerOptions().GetDumpCfgAppend() ? std::ofstream::app : std::ofstream::out;
Calin Juravle87000a92015-08-24 15:34:44 +0100415 visualizer_output_.reset(new std::ofstream(cfg_file_name, cfg_file_mode));
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100416 }
Calin Juravle2be39e02015-04-21 13:56:34 +0100417 if (driver->GetDumpStats()) {
418 compilation_stats_.reset(new OptimizingCompilerStats());
419 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100420}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000421
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000422void OptimizingCompiler::UnInit() const {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000423}
424
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100425OptimizingCompiler::~OptimizingCompiler() {
Calin Juravle2be39e02015-04-21 13:56:34 +0100426 if (compilation_stats_.get() != nullptr) {
427 compilation_stats_->Log();
428 }
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100429}
430
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000431bool OptimizingCompiler::CanCompileMethod(uint32_t method_idx ATTRIBUTE_UNUSED,
Vladimir Markodf739842016-03-23 16:59:07 +0000432 const DexFile& dex_file ATTRIBUTE_UNUSED) const {
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000433 return true;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700434}
435
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000436static bool IsInstructionSetSupported(InstructionSet instruction_set) {
Calin Juravlecff8cc72015-10-09 12:03:24 +0100437 return (instruction_set == kArm && !kArm32QuickCodeUseSoftFloat)
438 || instruction_set == kArm64
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000439 || (instruction_set == kThumb2 && !kArm32QuickCodeUseSoftFloat)
Goran Jakovljevicf652cec2015-08-25 16:11:42 +0200440 || instruction_set == kMips
Alexey Frunze4dda3372015-06-01 18:31:49 -0700441 || instruction_set == kMips64
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000442 || instruction_set == kX86
443 || instruction_set == kX86_64;
444}
445
Roland Levillain22ccc3a2015-11-24 13:10:05 +0000446// Read barrier are supported on ARM, ARM64, x86 and x86-64 at the moment.
Roland Levillain0d5a2812015-11-13 10:07:31 +0000447// TODO: Add support for other architectures and remove this function
448static bool InstructionSetSupportsReadBarrier(InstructionSet instruction_set) {
Roland Levillain22ccc3a2015-11-24 13:10:05 +0000449 return instruction_set == kArm64
450 || instruction_set == kThumb2
Roland Levillain3b359c72015-11-17 19:35:12 +0000451 || instruction_set == kX86
Roland Levillain0d5a2812015-11-13 10:07:31 +0000452 || instruction_set == kX86_64;
453}
454
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700455// Strip pass name suffix to get optimization name.
456static std::string ConvertPassNameToOptimizationName(const std::string& pass_name) {
457 size_t pos = pass_name.find(kPassNameSeparator);
458 return pos == std::string::npos ? pass_name : pass_name.substr(0, pos);
459}
460
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700461static HOptimization* BuildOptimization(
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700462 const std::string& pass_name,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700463 ArenaAllocator* arena,
464 HGraph* graph,
465 OptimizingCompilerStats* stats,
466 CodeGenerator* codegen,
467 CompilerDriver* driver,
468 const DexCompilationUnit& dex_compilation_unit,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700469 VariableSizedHandleScope* handles,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700470 SideEffectsAnalysis* most_recent_side_effects,
471 HInductionVarAnalysis* most_recent_induction) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700472 std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700473 if (opt_name == BoundsCheckElimination::kBoundsCheckEliminationPassName) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700474 CHECK(most_recent_side_effects != nullptr && most_recent_induction != nullptr);
475 return new (arena) BoundsCheckElimination(graph,
476 *most_recent_side_effects,
477 most_recent_induction);
478 } else if (opt_name == GVNOptimization::kGlobalValueNumberingPassName) {
479 CHECK(most_recent_side_effects != nullptr);
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700480 return new (arena) GVNOptimization(graph, *most_recent_side_effects, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700481 } else if (opt_name == HConstantFolding::kConstantFoldingPassName) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700482 return new (arena) HConstantFolding(graph, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700483 } else if (opt_name == HDeadCodeElimination::kDeadCodeEliminationPassName) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700484 return new (arena) HDeadCodeElimination(graph, stats, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700485 } else if (opt_name == HInliner::kInlinerPassName) {
486 size_t number_of_dex_registers = dex_compilation_unit.GetCodeItem()->registers_size_;
487 return new (arena) HInliner(graph, // outer_graph
488 graph, // outermost_graph
489 codegen,
490 dex_compilation_unit, // outer_compilation_unit
491 dex_compilation_unit, // outermost_compilation_unit
492 driver,
493 handles,
494 stats,
495 number_of_dex_registers,
496 /* depth */ 0);
497 } else if (opt_name == HSharpening::kSharpeningPassName) {
498 return new (arena) HSharpening(graph, codegen, dex_compilation_unit, driver);
499 } else if (opt_name == HSelectGenerator::kSelectGeneratorPassName) {
500 return new (arena) HSelectGenerator(graph, stats);
501 } else if (opt_name == HInductionVarAnalysis::kInductionPassName) {
502 return new (arena) HInductionVarAnalysis(graph);
503 } else if (opt_name == InstructionSimplifier::kInstructionSimplifierPassName) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700504 return new (arena) InstructionSimplifier(graph, stats, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700505 } else if (opt_name == IntrinsicsRecognizer::kIntrinsicsRecognizerPassName) {
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100506 return new (arena) IntrinsicsRecognizer(graph, stats);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700507 } else if (opt_name == LICM::kLoopInvariantCodeMotionPassName) {
508 CHECK(most_recent_side_effects != nullptr);
509 return new (arena) LICM(graph, *most_recent_side_effects, stats);
510 } else if (opt_name == LoadStoreElimination::kLoadStoreEliminationPassName) {
511 CHECK(most_recent_side_effects != nullptr);
512 return new (arena) LoadStoreElimination(graph, *most_recent_side_effects);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700513 } else if (opt_name == SideEffectsAnalysis::kSideEffectsAnalysisPassName) {
514 return new (arena) SideEffectsAnalysis(graph);
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100515 } else if (opt_name == HLoopOptimization::kLoopOptimizationPassName) {
516 return new (arena) HLoopOptimization(graph, most_recent_induction);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700517#ifdef ART_ENABLE_CODEGEN_arm
518 } else if (opt_name == arm::DexCacheArrayFixups::kDexCacheArrayFixupsArmPassName) {
Vladimir Marko68c981f2016-08-26 13:13:33 +0100519 return new (arena) arm::DexCacheArrayFixups(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700520 } else if (opt_name == arm::InstructionSimplifierArm::kInstructionSimplifierArmPassName) {
521 return new (arena) arm::InstructionSimplifierArm(graph, stats);
522#endif
523#ifdef ART_ENABLE_CODEGEN_arm64
524 } else if (opt_name == arm64::InstructionSimplifierArm64::kInstructionSimplifierArm64PassName) {
525 return new (arena) arm64::InstructionSimplifierArm64(graph, stats);
526#endif
527#ifdef ART_ENABLE_CODEGEN_mips
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700528 } else if (opt_name == mips::DexCacheArrayFixups::kDexCacheArrayFixupsMipsPassName) {
529 return new (arena) mips::DexCacheArrayFixups(graph, codegen, stats);
530 } else if (opt_name == mips::PcRelativeFixups::kPcRelativeFixupsMipsPassName) {
531 return new (arena) mips::PcRelativeFixups(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700532#endif
533#ifdef ART_ENABLE_CODEGEN_x86
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700534 } else if (opt_name == x86::PcRelativeFixups::kPcRelativeFixupsX86PassName) {
535 return new (arena) x86::PcRelativeFixups(graph, codegen, stats);
536 } else if (opt_name == x86::X86MemoryOperandGeneration::kX86MemoryOperandGenerationPassName) {
537 return new (arena) x86::X86MemoryOperandGeneration(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700538#endif
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700539 }
540 return nullptr;
541}
542
543static ArenaVector<HOptimization*> BuildOptimizations(
544 const std::vector<std::string>& pass_names,
545 ArenaAllocator* arena,
546 HGraph* graph,
547 OptimizingCompilerStats* stats,
548 CodeGenerator* codegen,
549 CompilerDriver* driver,
550 const DexCompilationUnit& dex_compilation_unit,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700551 VariableSizedHandleScope* handles) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700552 // Few HOptimizations constructors require SideEffectsAnalysis or HInductionVarAnalysis
553 // instances. This method assumes that each of them expects the nearest instance preceeding it
554 // in the pass name list.
555 SideEffectsAnalysis* most_recent_side_effects = nullptr;
556 HInductionVarAnalysis* most_recent_induction = nullptr;
557 ArenaVector<HOptimization*> ret(arena->Adapter());
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700558 for (const std::string& pass_name : pass_names) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700559 HOptimization* opt = BuildOptimization(
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700560 pass_name,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700561 arena,
562 graph,
563 stats,
564 codegen,
565 driver,
566 dex_compilation_unit,
567 handles,
568 most_recent_side_effects,
569 most_recent_induction);
570 CHECK(opt != nullptr) << "Couldn't build optimization: \"" << pass_name << "\"";
571 ret.push_back(opt);
572
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700573 std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700574 if (opt_name == SideEffectsAnalysis::kSideEffectsAnalysisPassName) {
575 most_recent_side_effects = down_cast<SideEffectsAnalysis*>(opt);
576 } else if (opt_name == HInductionVarAnalysis::kInductionPassName) {
577 most_recent_induction = down_cast<HInductionVarAnalysis*>(opt);
578 }
579 }
580 return ret;
581}
582
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700583void OptimizingCompiler::RunOptimizations(HOptimization* optimizations[],
584 size_t length,
585 PassObserver* pass_observer) const {
Calin Juravle10e244f2015-01-26 18:54:32 +0000586 for (size_t i = 0; i < length; ++i) {
David Brazdil69ba7b72015-06-23 18:27:30 +0100587 PassScope scope(optimizations[i]->GetPassName(), pass_observer);
588 optimizations[i]->Run();
Calin Juravle10e244f2015-01-26 18:54:32 +0000589 }
590}
591
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700592void OptimizingCompiler::MaybeRunInliner(HGraph* graph,
593 CodeGenerator* codegen,
594 CompilerDriver* driver,
595 const DexCompilationUnit& dex_compilation_unit,
596 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700597 VariableSizedHandleScope* handles) const {
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700598 OptimizingCompilerStats* stats = compilation_stats_.get();
Calin Juravleec748352015-07-29 13:52:12 +0100599 const CompilerOptions& compiler_options = driver->GetCompilerOptions();
600 bool should_inline = (compiler_options.GetInlineDepthLimit() > 0)
601 && (compiler_options.GetInlineMaxCodeUnits() > 0);
602 if (!should_inline) {
603 return;
604 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000605 size_t number_of_dex_registers = dex_compilation_unit.GetCodeItem()->registers_size_;
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000606 HInliner* inliner = new (graph->GetArena()) HInliner(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700607 graph, // outer_graph
608 graph, // outermost_graph
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000609 codegen,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700610 dex_compilation_unit, // outer_compilation_unit
611 dex_compilation_unit, // outermost_compilation_unit
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000612 driver,
613 handles,
614 stats,
615 number_of_dex_registers,
616 /* depth */ 0);
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000617 HOptimization* optimizations[] = { inliner };
Calin Juravleec748352015-07-29 13:52:12 +0100618
619 RunOptimizations(optimizations, arraysize(optimizations), pass_observer);
620}
621
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700622void OptimizingCompiler::RunArchOptimizations(InstructionSet instruction_set,
623 HGraph* graph,
624 CodeGenerator* codegen,
625 PassObserver* pass_observer) const {
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700626 UNUSED(codegen); // To avoid compilation error when compiling for svelte
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700627 OptimizingCompilerStats* stats = compilation_stats_.get();
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100628 ArenaAllocator* arena = graph->GetArena();
Scott Wakelinga7812ae2016-10-17 10:03:36 +0100629#ifdef ART_USE_VIXL_ARM_BACKEND
630 UNUSED(arena);
631 UNUSED(pass_observer);
632 UNUSED(stats);
633#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100634 switch (instruction_set) {
Scott Wakelinga7812ae2016-10-17 10:03:36 +0100635#if defined(ART_ENABLE_CODEGEN_arm) && !defined(ART_USE_VIXL_ARM_BACKEND)
Vladimir Markob4536b72015-11-24 13:45:23 +0000636 case kThumb2:
637 case kArm: {
Vladimir Marko68c981f2016-08-26 13:13:33 +0100638 arm::DexCacheArrayFixups* fixups =
639 new (arena) arm::DexCacheArrayFixups(graph, codegen, stats);
Artem Udovichenko4a0dad62016-01-26 12:28:31 +0300640 arm::InstructionSimplifierArm* simplifier =
641 new (arena) arm::InstructionSimplifierArm(graph, stats);
Artem Serov328429f2016-07-06 16:23:04 +0100642 SideEffectsAnalysis* side_effects = new (arena) SideEffectsAnalysis(graph);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700643 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects, "GVN$after_arch");
Vladimir Markob4536b72015-11-24 13:45:23 +0000644 HOptimization* arm_optimizations[] = {
Artem Udovichenko4a0dad62016-01-26 12:28:31 +0300645 simplifier,
Artem Serov328429f2016-07-06 16:23:04 +0100646 side_effects,
647 gvn,
Nicolas Geoffray6b5afdd2016-01-22 09:31:52 +0000648 fixups
Vladimir Markob4536b72015-11-24 13:45:23 +0000649 };
650 RunOptimizations(arm_optimizations, arraysize(arm_optimizations), pass_observer);
651 break;
652 }
653#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100654#ifdef ART_ENABLE_CODEGEN_arm64
655 case kArm64: {
656 arm64::InstructionSimplifierArm64* simplifier =
657 new (arena) arm64::InstructionSimplifierArm64(graph, stats);
658 SideEffectsAnalysis* side_effects = new (arena) SideEffectsAnalysis(graph);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700659 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects, "GVN$after_arch");
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100660 HOptimization* arm64_optimizations[] = {
661 simplifier,
662 side_effects,
663 gvn
664 };
665 RunOptimizations(arm64_optimizations, arraysize(arm64_optimizations), pass_observer);
666 break;
667 }
668#endif
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700669#ifdef ART_ENABLE_CODEGEN_mips
670 case kMips: {
671 mips::PcRelativeFixups* pc_relative_fixups =
672 new (arena) mips::PcRelativeFixups(graph, codegen, stats);
673 mips::DexCacheArrayFixups* dex_cache_array_fixups =
Alexey Frunze06a46c42016-07-19 15:00:40 -0700674 new (arena) mips::DexCacheArrayFixups(graph, codegen, stats);
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700675 HOptimization* mips_optimizations[] = {
676 pc_relative_fixups,
677 dex_cache_array_fixups
678 };
679 RunOptimizations(mips_optimizations, arraysize(mips_optimizations), pass_observer);
680 break;
681 }
682#endif
Mark Mendell0616ae02015-04-17 12:49:27 -0400683#ifdef ART_ENABLE_CODEGEN_x86
684 case kX86: {
Aart Bikd1c40452016-03-02 16:06:13 -0800685 x86::PcRelativeFixups* pc_relative_fixups =
686 new (arena) x86::PcRelativeFixups(graph, codegen, stats);
Mark Mendellee8d9712016-07-12 11:13:15 -0400687 x86::X86MemoryOperandGeneration* memory_gen =
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700688 new (arena) x86::X86MemoryOperandGeneration(graph, codegen, stats);
Mark Mendell0616ae02015-04-17 12:49:27 -0400689 HOptimization* x86_optimizations[] = {
Mark Mendellee8d9712016-07-12 11:13:15 -0400690 pc_relative_fixups,
691 memory_gen
Mark Mendell0616ae02015-04-17 12:49:27 -0400692 };
693 RunOptimizations(x86_optimizations, arraysize(x86_optimizations), pass_observer);
694 break;
695 }
696#endif
Mark Mendellee8d9712016-07-12 11:13:15 -0400697#ifdef ART_ENABLE_CODEGEN_x86_64
698 case kX86_64: {
699 x86::X86MemoryOperandGeneration* memory_gen =
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700700 new (arena) x86::X86MemoryOperandGeneration(graph, codegen, stats);
Mark Mendellee8d9712016-07-12 11:13:15 -0400701 HOptimization* x86_64_optimizations[] = {
702 memory_gen
703 };
704 RunOptimizations(x86_64_optimizations, arraysize(x86_64_optimizations), pass_observer);
705 break;
706 }
707#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100708 default:
709 break;
710 }
711}
712
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000713NO_INLINE // Avoid increasing caller's frame size by large stack-allocated objects.
714static void AllocateRegisters(HGraph* graph,
715 CodeGenerator* codegen,
Matthew Gharrity2cd05b72016-08-03 16:57:37 -0700716 PassObserver* pass_observer,
717 RegisterAllocator::Strategy strategy) {
Mingyao Yang700347e2016-03-02 14:59:32 -0800718 {
719 PassScope scope(PrepareForRegisterAllocation::kPrepareForRegisterAllocationPassName,
720 pass_observer);
721 PrepareForRegisterAllocation(graph).Run();
722 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000723 SsaLivenessAnalysis liveness(graph, codegen);
724 {
725 PassScope scope(SsaLivenessAnalysis::kLivenessPassName, pass_observer);
726 liveness.Analyze();
727 }
728 {
729 PassScope scope(RegisterAllocator::kRegisterAllocatorPassName, pass_observer);
Matthew Gharrity2cd05b72016-08-03 16:57:37 -0700730 RegisterAllocator::Create(graph->GetArena(), codegen, liveness, strategy)->AllocateRegisters();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000731 }
732}
733
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700734void OptimizingCompiler::RunOptimizations(HGraph* graph,
735 CodeGenerator* codegen,
736 CompilerDriver* driver,
737 const DexCompilationUnit& dex_compilation_unit,
738 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700739 VariableSizedHandleScope* handles) const {
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700740 OptimizingCompilerStats* stats = compilation_stats_.get();
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100741 ArenaAllocator* arena = graph->GetArena();
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700742 if (driver->GetCompilerOptions().GetPassesToRun() != nullptr) {
743 ArenaVector<HOptimization*> optimizations = BuildOptimizations(
744 *driver->GetCompilerOptions().GetPassesToRun(),
745 arena,
746 graph,
747 stats,
748 codegen,
749 driver,
750 dex_compilation_unit,
751 handles);
752 RunOptimizations(&optimizations[0], optimizations.size(), pass_observer);
753 return;
754 }
755
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100756 HDeadCodeElimination* dce1 = new (arena) HDeadCodeElimination(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700757 graph, stats, "dead_code_elimination$initial");
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100758 HDeadCodeElimination* dce2 = new (arena) HDeadCodeElimination(
Aart Bik2767f4b2016-10-28 15:03:53 -0700759 graph, stats, "dead_code_elimination$after_inlining");
760 HDeadCodeElimination* dce3 = new (arena) HDeadCodeElimination(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700761 graph, stats, "dead_code_elimination$final");
Andreas Gampeca620d72016-11-08 08:09:33 -0800762 HConstantFolding* fold1 = new (arena) HConstantFolding(graph, "constant_folding");
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100763 InstructionSimplifier* simplify1 = new (arena) InstructionSimplifier(graph, stats);
Jean-Philippe Halimi38e9e802016-02-18 16:42:03 +0100764 HSelectGenerator* select_generator = new (arena) HSelectGenerator(graph, stats);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700765 HConstantFolding* fold2 = new (arena) HConstantFolding(
766 graph, "constant_folding$after_inlining");
767 HConstantFolding* fold3 = new (arena) HConstantFolding(graph, "constant_folding$after_bce");
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100768 SideEffectsAnalysis* side_effects = new (arena) SideEffectsAnalysis(graph);
769 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects);
Jean-Philippe Halimi38e9e802016-02-18 16:42:03 +0100770 LICM* licm = new (arena) LICM(graph, *side_effects, stats);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700771 LoadStoreElimination* lse = new (arena) LoadStoreElimination(graph, *side_effects);
Aart Bik22af3be2015-09-10 12:50:58 -0700772 HInductionVarAnalysis* induction = new (arena) HInductionVarAnalysis(graph);
Aart Bik4a342772015-11-30 10:17:46 -0800773 BoundsCheckElimination* bce = new (arena) BoundsCheckElimination(graph, *side_effects, induction);
Aart Bik281c6812016-08-26 11:31:48 -0700774 HLoopOptimization* loop = new (arena) HLoopOptimization(graph, induction);
Vladimir Markodc151b22015-10-15 18:02:30 +0100775 HSharpening* sharpening = new (arena) HSharpening(graph, codegen, dex_compilation_unit, driver);
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100776 InstructionSimplifier* simplify2 = new (arena) InstructionSimplifier(
Aart Bik639cc8c2016-10-18 13:03:31 -0700777 graph, stats, "instruction_simplifier$after_inlining");
David Brazdil4833f5a2015-12-16 10:37:39 +0000778 InstructionSimplifier* simplify3 = new (arena) InstructionSimplifier(
Aart Bik639cc8c2016-10-18 13:03:31 -0700779 graph, stats, "instruction_simplifier$after_bce");
780 InstructionSimplifier* simplify4 = new (arena) InstructionSimplifier(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700781 graph, stats, "instruction_simplifier$before_codegen");
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100782 IntrinsicsRecognizer* intrinsics = new (arena) IntrinsicsRecognizer(graph, stats);
Andreas Gampe71fb52f2014-12-29 17:43:08 -0800783
Calin Juravleec748352015-07-29 13:52:12 +0100784 HOptimization* optimizations1[] = {
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100785 intrinsics,
David Brazdil4833f5a2015-12-16 10:37:39 +0000786 sharpening,
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100787 fold1,
788 simplify1,
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100789 dce1,
Calin Juravleec748352015-07-29 13:52:12 +0100790 };
Calin Juravleec748352015-07-29 13:52:12 +0100791 RunOptimizations(optimizations1, arraysize(optimizations1), pass_observer);
792
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700793 MaybeRunInliner(graph, codegen, driver, dex_compilation_unit, pass_observer, handles);
David Brazdil95177982015-10-30 12:56:58 -0500794
David Brazdil8993caf2015-12-07 10:04:40 +0000795 HOptimization* optimizations2[] = {
David Brazdil74eb1b22015-12-14 11:44:01 +0000796 // SelectGenerator depends on the InstructionSimplifier removing
David Brazdil8993caf2015-12-07 10:04:40 +0000797 // redundant suspend checks to recognize empty blocks.
David Brazdil74eb1b22015-12-14 11:44:01 +0000798 select_generator,
David Brazdil8993caf2015-12-07 10:04:40 +0000799 fold2, // TODO: if we don't inline we can also skip fold2.
Aart Bik639cc8c2016-10-18 13:03:31 -0700800 simplify2,
Aart Bik2767f4b2016-10-28 15:03:53 -0700801 dce2,
David Brazdil8993caf2015-12-07 10:04:40 +0000802 side_effects,
803 gvn,
804 licm,
805 induction,
806 bce,
Aart Bik281c6812016-08-26 11:31:48 -0700807 loop,
David Brazdil8993caf2015-12-07 10:04:40 +0000808 fold3, // evaluates code generated by dynamic bce
Aart Bik639cc8c2016-10-18 13:03:31 -0700809 simplify3,
David Brazdil8993caf2015-12-07 10:04:40 +0000810 lse,
Aart Bik2767f4b2016-10-28 15:03:53 -0700811 dce3,
David Brazdil8993caf2015-12-07 10:04:40 +0000812 // The codegen has a few assumptions that only the instruction simplifier
813 // can satisfy. For example, the code generator does not expect to see a
814 // HTypeConversion from a type to the same type.
Aart Bik639cc8c2016-10-18 13:03:31 -0700815 simplify4,
David Brazdil8993caf2015-12-07 10:04:40 +0000816 };
817 RunOptimizations(optimizations2, arraysize(optimizations2), pass_observer);
David Brazdilbbd733e2015-08-18 17:48:17 +0100818
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700819 RunArchOptimizations(driver->GetInstructionSet(), graph, codegen, pass_observer);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000820}
821
Vladimir Marko58155012015-08-19 12:49:41 +0000822static ArenaVector<LinkerPatch> EmitAndSortLinkerPatches(CodeGenerator* codegen) {
823 ArenaVector<LinkerPatch> linker_patches(codegen->GetGraph()->GetArena()->Adapter());
824 codegen->EmitLinkerPatches(&linker_patches);
825
826 // Sort patches by literal offset. Required for .oat_patches encoding.
827 std::sort(linker_patches.begin(), linker_patches.end(),
828 [](const LinkerPatch& lhs, const LinkerPatch& rhs) {
829 return lhs.LiteralOffset() < rhs.LiteralOffset();
830 });
831
832 return linker_patches;
833}
834
David Brazdil58282f42016-01-14 12:45:10 +0000835CompiledMethod* OptimizingCompiler::Emit(ArenaAllocator* arena,
836 CodeVectorAllocator* code_allocator,
837 CodeGenerator* codegen,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000838 CompilerDriver* compiler_driver,
839 const DexFile::CodeItem* code_item) const {
Vladimir Marko58155012015-08-19 12:49:41 +0000840 ArenaVector<LinkerPatch> linker_patches = EmitAndSortLinkerPatches(codegen);
Vladimir Markof9f64412015-09-02 14:05:49 +0100841 ArenaVector<uint8_t> stack_map(arena->Adapter(kArenaAllocStackMaps));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000842 stack_map.resize(codegen->ComputeStackMapsSize());
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000843 codegen->BuildStackMaps(MemoryRegion(stack_map.data(), stack_map.size()), *code_item);
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000844
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100845 CompiledMethod* compiled_method = CompiledMethod::SwapAllocCompiledMethod(
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000846 compiler_driver,
847 codegen->GetInstructionSet(),
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000848 ArrayRef<const uint8_t>(code_allocator->GetMemory()),
Roland Levillainaa9b7c42015-02-17 15:40:09 +0000849 // Follow Quick's behavior and set the frame size to zero if it is
850 // considered "empty" (see the definition of
851 // art::CodeGenerator::HasEmptyFrame).
852 codegen->HasEmptyFrame() ? 0 : codegen->GetFrameSize(),
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000853 codegen->GetCoreSpillMask(),
Nicolas Geoffrayd97dc402015-01-22 13:50:01 +0000854 codegen->GetFpuSpillMask(),
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000855 ArrayRef<const SrcMapElem>(),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100856 ArrayRef<const uint8_t>(stack_map),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100857 ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data()),
Vladimir Marko58155012015-08-19 12:49:41 +0000858 ArrayRef<const LinkerPatch>(linker_patches));
Mathieu Chartiered150002015-08-28 11:16:54 -0700859
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100860 return compiled_method;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000861}
862
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000863CodeGenerator* OptimizingCompiler::TryCompile(ArenaAllocator* arena,
864 CodeVectorAllocator* code_allocator,
865 const DexFile::CodeItem* code_item,
866 uint32_t access_flags,
867 InvokeType invoke_type,
868 uint16_t class_def_idx,
869 uint32_t method_idx,
870 jobject class_loader,
871 const DexFile& dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000872 Handle<mirror::DexCache> dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000873 ArtMethod* method,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000874 bool osr) const {
Calin Juravle2be39e02015-04-21 13:56:34 +0100875 MaybeRecordStat(MethodCompilationStat::kAttemptCompilation);
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000876 CompilerDriver* compiler_driver = GetCompilerDriver();
877 InstructionSet instruction_set = compiler_driver->GetInstructionSet();
Calin Juravlecff8cc72015-10-09 12:03:24 +0100878
Roland Levillain3b359c72015-11-17 19:35:12 +0000879 // Always use the Thumb-2 assembler: some runtime functionality
880 // (like implicit stack overflow checks) assume Thumb-2.
Artem Serovba6b6792016-08-15 14:22:07 +0100881 DCHECK_NE(instruction_set, kArm);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100882
883 // Do not attempt to compile on architectures we do not support.
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000884 if (!IsInstructionSetSupported(instruction_set)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100885 MaybeRecordStat(MethodCompilationStat::kNotCompiledUnsupportedIsa);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100886 return nullptr;
887 }
888
Roland Levillain0d5a2812015-11-13 10:07:31 +0000889 // When read barriers are enabled, do not attempt to compile for
890 // instruction sets that have no read barrier support.
891 if (kEmitCompilerReadBarrier && !InstructionSetSupportsReadBarrier(instruction_set)) {
892 return nullptr;
893 }
894
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000895 if (Compiler::IsPathologicalCase(*code_item, method_idx, dex_file)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100896 MaybeRecordStat(MethodCompilationStat::kNotCompiledPathological);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000897 return nullptr;
898 }
899
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000900 // Implementation of the space filter: do not compile a code item whose size in
Nicolas Geoffray432bf3d2015-07-17 11:11:09 +0100901 // code units is bigger than 128.
902 static constexpr size_t kSpaceFilterOptimizingThreshold = 128;
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000903 const CompilerOptions& compiler_options = compiler_driver->GetCompilerOptions();
Andreas Gampe29d38e72016-03-23 15:31:51 +0000904 if ((compiler_options.GetCompilerFilter() == CompilerFilter::kSpace)
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000905 && (code_item->insns_size_in_code_units_ > kSpaceFilterOptimizingThreshold)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100906 MaybeRecordStat(MethodCompilationStat::kNotCompiledSpaceFilter);
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000907 return nullptr;
908 }
909
Vladimir Marko97d7e1c2016-10-04 14:44:28 +0100910 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000911 DexCompilationUnit dex_compilation_unit(
Vladimir Markodf739842016-03-23 16:59:07 +0000912 class_loader,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +0100913 class_linker,
Vladimir Markodf739842016-03-23 16:59:07 +0000914 dex_file,
915 code_item,
916 class_def_idx,
917 method_idx,
918 access_flags,
919 /* verified_method */ nullptr,
920 dex_cache);
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000921
Calin Juravle3cd4fc82015-05-14 15:15:42 +0100922 bool requires_barrier = dex_compilation_unit.IsConstructor()
923 && compiler_driver->RequiresConstructorBarrier(Thread::Current(),
924 dex_compilation_unit.GetDexFile(),
925 dex_compilation_unit.GetClassDefIndex());
David Brazdilbadd8262016-02-02 16:28:56 +0000926
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000927 HGraph* graph = new (arena) HGraph(
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000928 arena,
929 dex_file,
930 method_idx,
931 requires_barrier,
932 compiler_driver->GetInstructionSet(),
933 kInvalidInvokeType,
934 compiler_driver->GetCompilerOptions().GetDebuggable(),
935 osr);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000936
David Brazdilbadd8262016-02-02 16:28:56 +0000937 const uint8_t* interpreter_metadata = nullptr;
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000938 if (method == nullptr) {
David Brazdilbadd8262016-02-02 16:28:56 +0000939 ScopedObjectAccess soa(Thread::Current());
940 StackHandleScope<1> hs(soa.Self());
941 Handle<mirror::ClassLoader> loader(hs.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700942 soa.Decode<mirror::ClassLoader>(class_loader)));
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000943 method = compiler_driver->ResolveMethod(
David Brazdilbadd8262016-02-02 16:28:56 +0000944 soa, dex_cache, loader, &dex_compilation_unit, method_idx, invoke_type);
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000945 }
946 // For AOT compilation, we may not get a method, for example if its class is erroneous.
947 // JIT should always have a method.
948 DCHECK(Runtime::Current()->IsAotCompiler() || method != nullptr);
949 if (method != nullptr) {
950 graph->SetArtMethod(method);
951 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +0100952 interpreter_metadata = method->GetQuickenedInfo(class_linker->GetImagePointerSize());
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000953 uint16_t type_index = method->GetDeclaringClass()->GetDexTypeIndex();
954
955 // Update the dex cache if the type is not in it yet. Note that under AOT,
956 // the verifier must have set it, but under JIT, there's no guarantee, as we
957 // don't necessarily run the verifier.
958 // The compiler and the compiler driver assume the compiling class is
959 // in the dex cache.
960 if (dex_cache->GetResolvedType(type_index) == nullptr) {
961 dex_cache->SetResolvedType(type_index, method->GetDeclaringClass());
Nicolas Geoffray12abcbd2016-06-06 15:51:58 +0000962 }
David Brazdilbadd8262016-02-02 16:28:56 +0000963 }
964
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000965 std::unique_ptr<CodeGenerator> codegen(
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000966 CodeGenerator::Create(graph,
967 instruction_set,
968 *compiler_driver->GetInstructionSetFeatures(),
Calin Juravle2ae48182016-03-16 14:05:09 +0000969 compiler_driver->GetCompilerOptions(),
970 compilation_stats_.get()));
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000971 if (codegen.get() == nullptr) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100972 MaybeRecordStat(MethodCompilationStat::kNotCompiledNoCodegen);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000973 return nullptr;
974 }
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100975 codegen->GetAssembler()->cfi().SetEnabled(
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000976 compiler_driver->GetCompilerOptions().GenerateAnyDebugInfo());
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000977
David Brazdil69ba7b72015-06-23 18:27:30 +0100978 PassObserver pass_observer(graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100979 codegen.get(),
980 visualizer_output_.get(),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700981 compiler_driver,
982 dump_mutex_);
David Brazdil5e8b1372015-01-23 14:39:08 +0000983
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000984 VLOG(compiler) << "Building " << pass_observer.GetMethodName();
David Brazdil5e8b1372015-01-23 14:39:08 +0000985
David Brazdil809658e2015-02-05 11:34:02 +0000986 {
David Brazdilbadd8262016-02-02 16:28:56 +0000987 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700988 VariableSizedHandleScope handles(soa.Self());
David Brazdilbadd8262016-02-02 16:28:56 +0000989 // Do not hold `mutator_lock_` between optimizations.
990 ScopedThreadSuspension sts(soa.Self(), kNative);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100991
David Brazdilbadd8262016-02-02 16:28:56 +0000992 {
993 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
994 HGraphBuilder builder(graph,
995 &dex_compilation_unit,
996 &dex_compilation_unit,
997 &dex_file,
David Brazdil86ea7ee2016-02-16 09:26:07 +0000998 *code_item,
David Brazdilbadd8262016-02-02 16:28:56 +0000999 compiler_driver,
1000 compilation_stats_.get(),
1001 interpreter_metadata,
David Brazdildee58d62016-04-07 09:54:26 +00001002 dex_cache,
1003 &handles);
1004 GraphAnalysisResult result = builder.BuildGraph();
David Brazdilbadd8262016-02-02 16:28:56 +00001005 if (result != kAnalysisSuccess) {
1006 switch (result) {
David Brazdil86ea7ee2016-02-16 09:26:07 +00001007 case kAnalysisSkipped:
1008 MaybeRecordStat(MethodCompilationStat::kNotCompiledSkipped);
1009 break;
David Brazdilbadd8262016-02-02 16:28:56 +00001010 case kAnalysisInvalidBytecode:
David Brazdil86ea7ee2016-02-16 09:26:07 +00001011 MaybeRecordStat(MethodCompilationStat::kNotCompiledInvalidBytecode);
David Brazdilbadd8262016-02-02 16:28:56 +00001012 break;
1013 case kAnalysisFailThrowCatchLoop:
1014 MaybeRecordStat(MethodCompilationStat::kNotCompiledThrowCatchLoop);
1015 break;
1016 case kAnalysisFailAmbiguousArrayOp:
1017 MaybeRecordStat(MethodCompilationStat::kNotCompiledAmbiguousArrayOp);
1018 break;
1019 case kAnalysisSuccess:
1020 UNREACHABLE();
1021 }
1022 pass_observer.SetGraphInBadState();
1023 return nullptr;
David Brazdil809658e2015-02-05 11:34:02 +00001024 }
Nicolas Geoffrayf5370122014-12-02 11:51:19 +00001025 }
David Brazdil58282f42016-01-14 12:45:10 +00001026
David Brazdilbadd8262016-02-02 16:28:56 +00001027 RunOptimizations(graph,
1028 codegen.get(),
1029 compiler_driver,
David Brazdilbadd8262016-02-02 16:28:56 +00001030 dex_compilation_unit,
1031 &pass_observer,
1032 &handles);
1033
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07001034 RegisterAllocator::Strategy regalloc_strategy =
1035 compiler_options.GetRegisterAllocationStrategy();
1036 AllocateRegisters(graph, codegen.get(), &pass_observer, regalloc_strategy);
1037
David Brazdilbadd8262016-02-02 16:28:56 +00001038 codegen->Compile(code_allocator);
1039 pass_observer.DumpDisassembly();
1040 }
Vladimir Markof9f64412015-09-02 14:05:49 +01001041
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001042 return codegen.release();
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001043}
1044
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001045CompiledMethod* OptimizingCompiler::Compile(const DexFile::CodeItem* code_item,
1046 uint32_t access_flags,
1047 InvokeType invoke_type,
1048 uint16_t class_def_idx,
1049 uint32_t method_idx,
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001050 jobject jclass_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -07001051 const DexFile& dex_file,
1052 Handle<mirror::DexCache> dex_cache) const {
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001053 CompilerDriver* compiler_driver = GetCompilerDriver();
1054 CompiledMethod* method = nullptr;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001055 DCHECK(Runtime::Current()->IsAotCompiler());
1056 const VerifiedMethod* verified_method = compiler_driver->GetVerifiedMethod(&dex_file, method_idx);
1057 DCHECK(!verified_method->HasRuntimeThrow());
1058 if (compiler_driver->IsMethodVerifiedWithoutFailures(method_idx, class_def_idx, dex_file)
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001059 || verifier::MethodVerifier::CanCompilerHandleVerificationFailure(
1060 verified_method->GetEncounteredVerificationFailures())) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001061 ArenaAllocator arena(Runtime::Current()->GetArenaPool());
1062 CodeVectorAllocator code_allocator(&arena);
1063 std::unique_ptr<CodeGenerator> codegen(
1064 TryCompile(&arena,
1065 &code_allocator,
1066 code_item,
1067 access_flags,
1068 invoke_type,
1069 class_def_idx,
1070 method_idx,
1071 jclass_loader,
1072 dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001073 dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +00001074 nullptr,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001075 /* osr */ false));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001076 if (codegen.get() != nullptr) {
Calin Juravlead543382015-11-19 17:26:29 +00001077 MaybeRecordStat(MethodCompilationStat::kCompiled);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001078 method = Emit(&arena, &code_allocator, codegen.get(), compiler_driver, code_item);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001079
1080 if (kArenaAllocatorCountAllocations) {
1081 if (arena.BytesAllocated() > kArenaAllocatorMemoryReportThreshold) {
1082 MemStats mem_stats(arena.GetMemStats());
David Sehr709b0702016-10-13 09:12:37 -07001083 LOG(INFO) << dex_file.PrettyMethod(method_idx) << " " << Dumpable<MemStats>(mem_stats);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001084 }
1085 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001086 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001087 } else {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001088 if (compiler_driver->GetCompilerOptions().VerifyAtRuntime()) {
1089 MaybeRecordStat(MethodCompilationStat::kNotCompiledVerifyAtRuntime);
1090 } else {
Calin Juravlead543382015-11-19 17:26:29 +00001091 MaybeRecordStat(MethodCompilationStat::kNotCompiledVerificationError);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001092 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001093 }
1094
Calin Juravlecff8cc72015-10-09 12:03:24 +01001095 if (kIsDebugBuild &&
1096 IsCompilingWithCoreImage() &&
Roland Levillain0d5a2812015-11-13 10:07:31 +00001097 IsInstructionSetSupported(compiler_driver->GetInstructionSet()) &&
1098 (!kEmitCompilerReadBarrier ||
1099 InstructionSetSupportsReadBarrier(compiler_driver->GetInstructionSet()))) {
1100 // For testing purposes, we put a special marker on method names
1101 // that should be compiled with this compiler (when the the
1102 // instruction set is supported -- and has support for read
1103 // barriers, if they are enabled). This makes sure we're not
1104 // regressing.
David Sehr709b0702016-10-13 09:12:37 -07001105 std::string method_name = dex_file.PrettyMethod(method_idx);
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001106 bool shouldCompile = method_name.find("$opt$") != std::string::npos;
1107 DCHECK((method != nullptr) || !shouldCompile) << "Didn't compile " << method_name;
1108 }
1109
Nicolas Geoffray12be74e2015-03-30 13:29:08 +01001110 return method;
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001111}
1112
Andreas Gampe53c913b2014-08-12 23:19:23 -07001113Compiler* CreateOptimizingCompiler(CompilerDriver* driver) {
1114 return new OptimizingCompiler(driver);
1115}
1116
Nicolas Geoffray335005e2015-06-25 10:01:47 +01001117bool IsCompilingWithCoreImage() {
1118 const std::string& image = Runtime::Current()->GetImageLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001119 // TODO: This is under-approximating...
1120 if (EndsWith(image, "core.art") || EndsWith(image, "core-optimizing.art")) {
1121 return true;
1122 }
1123 return false;
Nicolas Geoffray335005e2015-06-25 10:01:47 +01001124}
1125
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001126bool OptimizingCompiler::JitCompile(Thread* self,
1127 jit::JitCodeCache* code_cache,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001128 ArtMethod* method,
1129 bool osr) {
Nicolas Geoffray75afcdd2016-11-10 10:38:11 +00001130 StackHandleScope<3> hs(self);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001131 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1132 method->GetDeclaringClass()->GetClassLoader()));
1133 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001134 DCHECK(method->IsCompilable());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001135
1136 jobject jclass_loader = class_loader.ToJObject();
1137 const DexFile* dex_file = method->GetDexFile();
1138 const uint16_t class_def_idx = method->GetClassDefIndex();
1139 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
1140 const uint32_t method_idx = method->GetDexMethodIndex();
1141 const uint32_t access_flags = method->GetAccessFlags();
1142 const InvokeType invoke_type = method->GetInvokeType();
1143
Nicolas Geoffray25e04562016-03-01 13:17:58 +00001144 ArenaAllocator arena(Runtime::Current()->GetJitArenaPool());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001145 CodeVectorAllocator code_allocator(&arena);
1146 std::unique_ptr<CodeGenerator> codegen;
1147 {
1148 // Go to native so that we don't block GC during compilation.
1149 ScopedThreadSuspension sts(self, kNative);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001150 codegen.reset(
1151 TryCompile(&arena,
1152 &code_allocator,
1153 code_item,
1154 access_flags,
1155 invoke_type,
1156 class_def_idx,
1157 method_idx,
1158 jclass_loader,
1159 *dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001160 dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +00001161 method,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001162 osr));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001163 if (codegen.get() == nullptr) {
1164 return false;
1165 }
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001166
1167 if (kArenaAllocatorCountAllocations) {
1168 if (arena.BytesAllocated() > kArenaAllocatorMemoryReportThreshold) {
1169 MemStats mem_stats(arena.GetMemStats());
David Sehr709b0702016-10-13 09:12:37 -07001170 LOG(INFO) << dex_file->PrettyMethod(method_idx) << " " << Dumpable<MemStats>(mem_stats);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001171 }
1172 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001173 }
1174
1175 size_t stack_map_size = codegen->ComputeStackMapsSize();
Nicolas Geoffray75afcdd2016-11-10 10:38:11 +00001176 size_t number_of_roots = codegen->GetNumberOfJitRoots();
1177 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1178 // We allocate an object array to ensure the JIT roots that we will collect in EmitJitRoots
1179 // will be visible by the GC between EmitLiterals and CommitCode. Once CommitCode is
1180 // executed, this array is not needed.
1181 Handle<mirror::ObjectArray<mirror::Object>> roots(
1182 hs.NewHandle(mirror::ObjectArray<mirror::Object>::Alloc(
1183 self, class_linker->GetClassRoot(ClassLinker::kObjectArrayClass), number_of_roots)));
1184 if (roots.Get() == nullptr) {
1185 // Out of memory, just clear the exception to avoid any Java exception uncaught problems.
1186 DCHECK(self->IsExceptionPending());
1187 self->ClearException();
1188 return false;
1189 }
1190 uint8_t* stack_map_data = nullptr;
1191 uint8_t* roots_data = nullptr;
1192 code_cache->ReserveData(
1193 self, stack_map_size, number_of_roots, method, &stack_map_data, &roots_data);
1194 if (stack_map_data == nullptr || roots_data == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001195 return false;
1196 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001197 MaybeRecordStat(MethodCompilationStat::kCompiled);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001198 codegen->BuildStackMaps(MemoryRegion(stack_map_data, stack_map_size), *code_item);
Nicolas Geoffray75afcdd2016-11-10 10:38:11 +00001199 codegen->EmitJitRoots(code_allocator.GetData(), roots, roots_data, dex_cache);
1200
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001201 const void* code = code_cache->CommitCode(
1202 self,
1203 method,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001204 stack_map_data,
Nicolas Geoffray75afcdd2016-11-10 10:38:11 +00001205 roots_data,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001206 codegen->HasEmptyFrame() ? 0 : codegen->GetFrameSize(),
1207 codegen->GetCoreSpillMask(),
1208 codegen->GetFpuSpillMask(),
1209 code_allocator.GetMemory().data(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001210 code_allocator.GetSize(),
Nicolas Geoffray75afcdd2016-11-10 10:38:11 +00001211 osr,
1212 roots);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001213
1214 if (code == nullptr) {
1215 code_cache->ClearData(self, stack_map_data);
1216 return false;
1217 }
1218
David Srbecky91cc06c2016-03-07 16:13:58 +00001219 const CompilerOptions& compiler_options = GetCompilerDriver()->GetCompilerOptions();
1220 if (compiler_options.GetGenerateDebugInfo()) {
David Srbecky5cc349f2015-12-18 15:04:48 +00001221 const auto* method_header = reinterpret_cast<const OatQuickMethodHeader*>(code);
1222 const uintptr_t code_address = reinterpret_cast<uintptr_t>(method_header->GetCode());
David Srbecky09c2a6b2016-03-11 17:11:44 +00001223 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1224 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +00001225 info.dex_file = dex_file;
1226 info.class_def_index = class_def_idx;
1227 info.dex_method_index = method_idx;
1228 info.access_flags = access_flags;
1229 info.code_item = code_item;
1230 info.isa = codegen->GetInstructionSet();
1231 info.deduped = false;
1232 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1233 info.is_optimized = true;
1234 info.is_code_address_text_relative = false;
1235 info.code_address = code_address;
1236 info.code_size = code_allocator.GetSize();
1237 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
1238 info.code_info = stack_map_size == 0 ? nullptr : stack_map_data;
1239 info.cfi = ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data());
Vladimir Marko93205e32016-04-13 11:59:46 +01001240 std::vector<uint8_t> elf_file = debug::WriteDebugElfFileForMethods(
David Srbecky5d811202016-03-08 13:21:22 +00001241 GetCompilerDriver()->GetInstructionSet(),
1242 GetCompilerDriver()->GetInstructionSetFeatures(),
David Srbeckyfe736b72016-03-09 11:44:44 +00001243 ArrayRef<const debug::MethodDebugInfo>(&info, 1));
Vladimir Marko93205e32016-04-13 11:59:46 +01001244 CreateJITCodeEntryForAddress(code_address, std::move(elf_file));
David Srbecky5cc349f2015-12-18 15:04:48 +00001245 }
1246
Nicolas Geoffraya4f81542016-03-08 16:57:48 +00001247 Runtime::Current()->GetJit()->AddMemoryUsage(method, arena.BytesUsed());
1248
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001249 return true;
1250}
1251
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001252} // namespace art