blob: 2c65e5ca65ab123c105d7071b53fb557dfb0bb58 [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
Andreas Gampe9186ced2016-12-12 14:28:21 -080025#include "android-base/strings.h"
26
Aart Bikd1c40452016-03-02 16:06:13 -080027#ifdef ART_ENABLE_CODEGEN_arm
Vladimir Markob4536b72015-11-24 13:45:23 +000028#include "dex_cache_array_fixups_arm.h"
29#endif
30
31#ifdef ART_ENABLE_CODEGEN_arm64
Alexandre Rames44b9cf92015-08-19 15:39:06 +010032#include "instruction_simplifier_arm64.h"
33#endif
34
Alexey Frunzee3fb2452016-05-10 16:08:05 -070035#ifdef ART_ENABLE_CODEGEN_mips
36#include "dex_cache_array_fixups_mips.h"
37#include "pc_relative_fixups_mips.h"
38#endif
39
Mark Mendell0616ae02015-04-17 12:49:27 -040040#ifdef ART_ENABLE_CODEGEN_x86
Vladimir Marko0f7dca42015-11-02 14:36:43 +000041#include "pc_relative_fixups_x86.h"
Mark Mendell0616ae02015-04-17 12:49:27 -040042#endif
43
Mark Mendellee8d9712016-07-12 11:13:15 -040044#if defined(ART_ENABLE_CODEGEN_x86) || defined(ART_ENABLE_CODEGEN_x86_64)
45#include "x86_memory_gen.h"
46#endif
47
Mathieu Chartiere401d142015-04-22 13:56:20 -070048#include "art_method-inl.h"
Mathieu Chartierb666f482015-02-18 14:33:14 -080049#include "base/arena_allocator.h"
Vladimir Markof9f64412015-09-02 14:05:49 +010050#include "base/arena_containers.h"
David Brazdil5e8b1372015-01-23 14:39:08 +000051#include "base/dumpable.h"
Vladimir Markoc90d7c72015-10-06 17:30:45 +000052#include "base/macros.h"
Andreas Gampea0d81af2016-10-27 12:04:57 -070053#include "base/mutex.h"
David Brazdil5e8b1372015-01-23 14:39:08 +000054#include "base/timing_logger.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070055#include "bounds_check_elimination.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000056#include "builder.h"
Mingyao Yangb0b051a2016-11-17 09:04:53 -080057#include "cha_guard_optimization.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000058#include "code_generator.h"
Nicolas Geoffrayb813ca12017-02-16 22:08:29 +000059#include "code_sinking.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000060#include "compiled_method.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070061#include "compiler.h"
Roland Levillain75be2832014-10-17 17:02:00 +010062#include "constant_folding.h"
63#include "dead_code_elimination.h"
David Srbeckyc5bfa972016-02-05 15:49:10 +000064#include "debug/elf_debug_writer.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000065#include "debug/method_debug_info.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010066#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000067#include "dex/verified_method.h"
Andreas Gampea5b09a62016-11-17 15:21:22 -080068#include "dex_file_types.h"
Nicolas Geoffray9523a3e2015-07-17 11:51:28 +000069#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000070#include "driver/compiler_options.h"
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000071#include "driver/dex_compilation_unit.h"
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +000072#include "elf_writer_quick.h"
David Brazdil69ba7b72015-06-23 18:27:30 +010073#include "graph_checker.h"
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010074#include "graph_visualizer.h"
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +010075#include "gvn.h"
Aart Bik22af3be2015-09-10 12:50:58 -070076#include "induction_var_analysis.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000077#include "inliner.h"
Nicolas Geoffray3c049742014-09-24 18:10:46 +010078#include "instruction_simplifier.h"
Artem Udovichenko4a0dad62016-01-26 12:28:31 +030079#include "instruction_simplifier_arm.h"
Andreas Gampe71fb52f2014-12-29 17:43:08 -080080#include "intrinsics.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000081#include "jit/debugger_interface.h"
Nicolas Geoffraya4f81542016-03-08 16:57:48 +000082#include "jit/jit.h"
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +000083#include "jit/jit_code_cache.h"
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +000084#include "jni/quick/jni_compiler.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000085#include "licm.h"
xueliang.zhongc239a2b2017-04-27 15:31:37 +010086#include "load_store_analysis.h"
Mingyao Yang8df69d42015-10-22 15:40:58 -070087#include "load_store_elimination.h"
Aart Bik281c6812016-08-26 11:31:48 -070088#include "loop_optimization.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000089#include "nodes.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000090#include "oat_quick_method_header.h"
Nicolas Geoffray26a25ef2014-09-30 13:54:09 +010091#include "prepare_for_register_allocation.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010092#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070093#include "register_allocator_linear_scan.h"
David Brazdil74eb1b22015-12-14 11:44:01 +000094#include "select_generator.h"
Alexandre Rames22aa54b2016-10-18 09:32:29 +010095#include "scheduler.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010096#include "sharpening.h"
Nicolas Geoffray827eedb2015-01-26 15:18:36 +000097#include "side_effects_analysis.h"
Nicolas Geoffray31596742014-11-24 15:28:45 +000098#include "ssa_builder.h"
Nicolas Geoffray804d0932014-05-02 08:46:00 +010099#include "ssa_liveness_analysis.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +0000100#include "ssa_phi_elimination.h"
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100101#include "utils/assembler.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -0700102#include "verifier/verifier_compiler_binding.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000103
104namespace art {
105
Vladimir Marko3a40bf22016-03-22 16:26:33 +0000106static constexpr size_t kArenaAllocatorMemoryReportThreshold = 8 * MB;
107
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700108static constexpr const char* kPassNameSeparator = "$";
109
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000110/**
111 * Used by the code generator, to allocate the code in a vector.
112 */
113class CodeVectorAllocator FINAL : public CodeAllocator {
114 public:
Vladimir Markof9f64412015-09-02 14:05:49 +0100115 explicit CodeVectorAllocator(ArenaAllocator* arena)
116 : memory_(arena->Adapter(kArenaAllocCodeBuffer)),
117 size_(0) {}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000118
119 virtual uint8_t* Allocate(size_t size) {
120 size_ = size;
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000121 memory_.resize(size);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000122 return &memory_[0];
123 }
124
125 size_t GetSize() const { return size_; }
Vladimir Markof9f64412015-09-02 14:05:49 +0100126 const ArenaVector<uint8_t>& GetMemory() const { return memory_; }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000127 uint8_t* GetData() { return memory_.data(); }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000128
129 private:
Vladimir Markof9f64412015-09-02 14:05:49 +0100130 ArenaVector<uint8_t> memory_;
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000131 size_t size_;
132
133 DISALLOW_COPY_AND_ASSIGN(CodeVectorAllocator);
134};
135
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100136/**
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100137 * Filter to apply to the visualizer. Methods whose name contain that filter will
David Brazdilee690a32014-12-01 17:04:16 +0000138 * be dumped.
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100139 */
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700140static constexpr const char kStringFilter[] = "";
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100141
David Brazdil69ba7b72015-06-23 18:27:30 +0100142class PassScope;
David Brazdil809658e2015-02-05 11:34:02 +0000143
David Brazdil69ba7b72015-06-23 18:27:30 +0100144class PassObserver : public ValueObject {
David Brazdil5e8b1372015-01-23 14:39:08 +0000145 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100146 PassObserver(HGraph* graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100147 CodeGenerator* codegen,
148 std::ostream* visualizer_output,
Andreas Gampea0d81af2016-10-27 12:04:57 -0700149 CompilerDriver* compiler_driver,
150 Mutex& dump_mutex)
David Brazdil69ba7b72015-06-23 18:27:30 +0100151 : graph_(graph),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000152 cached_method_name_(),
David Brazdil809658e2015-02-05 11:34:02 +0000153 timing_logger_enabled_(compiler_driver->GetDumpPasses()),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000154 timing_logger_(timing_logger_enabled_ ? GetMethodName() : "", true, true),
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100155 disasm_info_(graph->GetArena()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700156 visualizer_oss_(),
157 visualizer_output_(visualizer_output),
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000158 visualizer_enabled_(!compiler_driver->GetCompilerOptions().GetDumpCfgFileName().empty()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700159 visualizer_(&visualizer_oss_, graph, *codegen),
160 visualizer_dump_mutex_(dump_mutex),
David Brazdil69ba7b72015-06-23 18:27:30 +0100161 graph_in_bad_state_(false) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700162 if (timing_logger_enabled_ || visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000163 if (!IsVerboseMethod(compiler_driver, GetMethodName())) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700164 timing_logger_enabled_ = visualizer_enabled_ = false;
165 }
166 if (visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000167 visualizer_.PrintHeader(GetMethodName());
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700168 codegen->SetDisassemblyInformation(&disasm_info_);
169 }
David Brazdil62e074f2015-04-07 18:09:37 +0100170 }
David Brazdil5e8b1372015-01-23 14:39:08 +0000171 }
172
David Brazdil69ba7b72015-06-23 18:27:30 +0100173 ~PassObserver() {
David Brazdil5e8b1372015-01-23 14:39:08 +0000174 if (timing_logger_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000175 LOG(INFO) << "TIMINGS " << GetMethodName();
David Brazdil5e8b1372015-01-23 14:39:08 +0000176 LOG(INFO) << Dumpable<TimingLogger>(timing_logger_);
177 }
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000178 DCHECK(visualizer_oss_.str().empty());
David Brazdil5e8b1372015-01-23 14:39:08 +0000179 }
180
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000181 void DumpDisassembly() REQUIRES(!visualizer_dump_mutex_) {
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100182 if (visualizer_enabled_) {
183 visualizer_.DumpGraphWithDisassembly();
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000184 FlushVisualizer();
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100185 }
186 }
187
David Brazdil69ba7b72015-06-23 18:27:30 +0100188 void SetGraphInBadState() { graph_in_bad_state_ = true; }
189
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000190 const char* GetMethodName() {
191 // PrettyMethod() is expensive, so we delay calling it until we actually have to.
192 if (cached_method_name_.empty()) {
David Sehr709b0702016-10-13 09:12:37 -0700193 cached_method_name_ = graph_->GetDexFile().PrettyMethod(graph_->GetMethodIdx());
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000194 }
195 return cached_method_name_.c_str();
196 }
197
David Brazdil5e8b1372015-01-23 14:39:08 +0000198 private:
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000199 void StartPass(const char* pass_name) REQUIRES(!visualizer_dump_mutex_) {
Wojciech Staszkiewicze7060702016-08-16 17:31:19 -0700200 VLOG(compiler) << "Starting pass: " << pass_name;
David Brazdil809658e2015-02-05 11:34:02 +0000201 // Dump graph first, then start timer.
202 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100203 visualizer_.DumpGraph(pass_name, /* is_after_pass */ false, graph_in_bad_state_);
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000204 FlushVisualizer();
David Brazdil809658e2015-02-05 11:34:02 +0000205 }
206 if (timing_logger_enabled_) {
207 timing_logger_.StartTiming(pass_name);
208 }
209 }
210
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000211 void FlushVisualizer() REQUIRES(!visualizer_dump_mutex_) {
212 MutexLock mu(Thread::Current(), visualizer_dump_mutex_);
213 *visualizer_output_ << visualizer_oss_.str();
214 visualizer_output_->flush();
215 visualizer_oss_.str("");
216 visualizer_oss_.clear();
217 }
218
219 void EndPass(const char* pass_name) REQUIRES(!visualizer_dump_mutex_) {
David Brazdil809658e2015-02-05 11:34:02 +0000220 // Pause timer first, then dump graph.
221 if (timing_logger_enabled_) {
222 timing_logger_.EndTiming();
223 }
224 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100225 visualizer_.DumpGraph(pass_name, /* is_after_pass */ true, graph_in_bad_state_);
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000226 FlushVisualizer();
David Brazdil809658e2015-02-05 11:34:02 +0000227 }
David Brazdil69ba7b72015-06-23 18:27:30 +0100228
229 // Validate the HGraph if running in debug mode.
230 if (kIsDebugBuild) {
231 if (!graph_in_bad_state_) {
David Brazdilbadd8262016-02-02 16:28:56 +0000232 GraphChecker checker(graph_);
233 checker.Run();
234 if (!checker.IsValid()) {
235 LOG(FATAL) << "Error after " << pass_name << ": " << Dumpable<GraphChecker>(checker);
David Brazdil69ba7b72015-06-23 18:27:30 +0100236 }
237 }
238 }
David Brazdil809658e2015-02-05 11:34:02 +0000239 }
240
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700241 static bool IsVerboseMethod(CompilerDriver* compiler_driver, const char* method_name) {
242 // Test an exact match to --verbose-methods. If verbose-methods is set, this overrides an
243 // empty kStringFilter matching all methods.
244 if (compiler_driver->GetCompilerOptions().HasVerboseMethods()) {
245 return compiler_driver->GetCompilerOptions().IsVerboseMethod(method_name);
246 }
247
248 // Test the kStringFilter sub-string. constexpr helper variable to silence unreachable-code
249 // warning when the string is empty.
250 constexpr bool kStringFilterEmpty = arraysize(kStringFilter) <= 1;
251 if (kStringFilterEmpty || strstr(method_name, kStringFilter) != nullptr) {
252 return true;
253 }
254
255 return false;
256 }
257
David Brazdil69ba7b72015-06-23 18:27:30 +0100258 HGraph* const graph_;
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000259
260 std::string cached_method_name_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000261
262 bool timing_logger_enabled_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000263 TimingLogger timing_logger_;
264
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100265 DisassemblyInformation disasm_info_;
266
Andreas Gampea0d81af2016-10-27 12:04:57 -0700267 std::ostringstream visualizer_oss_;
268 std::ostream* visualizer_output_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000269 bool visualizer_enabled_;
270 HGraphVisualizer visualizer_;
Andreas Gampea0d81af2016-10-27 12:04:57 -0700271 Mutex& visualizer_dump_mutex_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000272
David Brazdil69ba7b72015-06-23 18:27:30 +0100273 // Flag to be set by the compiler if the pass failed and the graph is not
274 // expected to validate.
275 bool graph_in_bad_state_;
David Brazdil809658e2015-02-05 11:34:02 +0000276
David Brazdil69ba7b72015-06-23 18:27:30 +0100277 friend PassScope;
278
279 DISALLOW_COPY_AND_ASSIGN(PassObserver);
David Brazdil5e8b1372015-01-23 14:39:08 +0000280};
281
David Brazdil69ba7b72015-06-23 18:27:30 +0100282class PassScope : public ValueObject {
David Brazdil809658e2015-02-05 11:34:02 +0000283 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100284 PassScope(const char *pass_name, PassObserver* pass_observer)
David Brazdil809658e2015-02-05 11:34:02 +0000285 : pass_name_(pass_name),
David Brazdil69ba7b72015-06-23 18:27:30 +0100286 pass_observer_(pass_observer) {
287 pass_observer_->StartPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000288 }
289
David Brazdil69ba7b72015-06-23 18:27:30 +0100290 ~PassScope() {
291 pass_observer_->EndPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000292 }
293
294 private:
295 const char* const pass_name_;
David Brazdil69ba7b72015-06-23 18:27:30 +0100296 PassObserver* const pass_observer_;
David Brazdil809658e2015-02-05 11:34:02 +0000297};
298
Andreas Gampe53c913b2014-08-12 23:19:23 -0700299class OptimizingCompiler FINAL : public Compiler {
300 public:
301 explicit OptimizingCompiler(CompilerDriver* driver);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700302 ~OptimizingCompiler() OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700303
Vladimir Markodf739842016-03-23 16:59:07 +0000304 bool CanCompileMethod(uint32_t method_idx, const DexFile& dex_file) const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700305
306 CompiledMethod* Compile(const DexFile::CodeItem* code_item,
307 uint32_t access_flags,
308 InvokeType invoke_type,
309 uint16_t class_def_idx,
310 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000311 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700312 const DexFile& dex_file,
313 Handle<mirror::DexCache> dex_cache) const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700314
Andreas Gampe53c913b2014-08-12 23:19:23 -0700315 CompiledMethod* JniCompile(uint32_t access_flags,
316 uint32_t method_idx,
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700317 const DexFile& dex_file,
318 JniOptimizationFlags optimization_flags) const OVERRIDE {
319 return ArtQuickJniCompileMethod(GetCompilerDriver(),
320 access_flags,
321 method_idx,
322 dex_file,
323 optimization_flags);
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000324 }
Andreas Gampe53c913b2014-08-12 23:19:23 -0700325
Mathieu Chartiere401d142015-04-22 13:56:20 -0700326 uintptr_t GetEntryPointOf(ArtMethod* method) const OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700327 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000328 return reinterpret_cast<uintptr_t>(method->GetEntryPointFromQuickCompiledCodePtrSize(
329 InstructionSetPointerSize(GetCompilerDriver()->GetInstructionSet())));
330 }
Andreas Gampe53c913b2014-08-12 23:19:23 -0700331
David Brazdilee690a32014-12-01 17:04:16 +0000332 void Init() OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700333
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000334 void UnInit() const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700335
Calin Juravle2be39e02015-04-21 13:56:34 +0100336 void MaybeRecordStat(MethodCompilationStat compilation_stat) const {
337 if (compilation_stats_.get() != nullptr) {
338 compilation_stats_->RecordStat(compilation_stat);
339 }
340 }
341
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000342 bool JitCompile(Thread* self, jit::JitCodeCache* code_cache, ArtMethod* method, bool osr)
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000343 OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700344 REQUIRES_SHARED(Locks::mutator_lock_);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000345
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700346 private:
347 void RunOptimizations(HGraph* graph,
348 CodeGenerator* codegen,
349 CompilerDriver* driver,
350 const DexCompilationUnit& dex_compilation_unit,
351 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700352 VariableSizedHandleScope* handles) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700353
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700354 void RunOptimizations(HOptimization* optimizations[],
355 size_t length,
356 PassObserver* pass_observer) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700357
Andreas Gampe53c913b2014-08-12 23:19:23 -0700358 private:
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000359 // Create a 'CompiledMethod' for an optimized graph.
David Brazdil58282f42016-01-14 12:45:10 +0000360 CompiledMethod* Emit(ArenaAllocator* arena,
361 CodeVectorAllocator* code_allocator,
362 CodeGenerator* codegen,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000363 CompilerDriver* driver,
364 const DexFile::CodeItem* item) const;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000365
366 // Try compiling a method and return the code generator used for
367 // compiling it.
368 // This method:
369 // 1) Builds the graph. Returns null if it failed to build it.
David Brazdil58282f42016-01-14 12:45:10 +0000370 // 2) Transforms the graph to SSA. Returns null if it failed.
371 // 3) Runs optimizations on the graph, including register allocator.
372 // 4) Generates code with the `code_allocator` provided.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000373 CodeGenerator* TryCompile(ArenaAllocator* arena,
374 CodeVectorAllocator* code_allocator,
375 const DexFile::CodeItem* code_item,
376 uint32_t access_flags,
377 InvokeType invoke_type,
378 uint16_t class_def_idx,
379 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000380 Handle<mirror::ClassLoader> class_loader,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000381 const DexFile& dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000382 Handle<mirror::DexCache> dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000383 ArtMethod* method,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000384 bool osr,
385 VariableSizedHandleScope* handles) const;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000386
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700387 void MaybeRunInliner(HGraph* graph,
388 CodeGenerator* codegen,
389 CompilerDriver* driver,
390 const DexCompilationUnit& dex_compilation_unit,
391 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700392 VariableSizedHandleScope* handles) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700393
394 void RunArchOptimizations(InstructionSet instruction_set,
395 HGraph* graph,
396 CodeGenerator* codegen,
397 PassObserver* pass_observer) const;
398
Calin Juravle2be39e02015-04-21 13:56:34 +0100399 std::unique_ptr<OptimizingCompilerStats> compilation_stats_;
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100400
Andreas Gampe53c913b2014-08-12 23:19:23 -0700401 std::unique_ptr<std::ostream> visualizer_output_;
402
Andreas Gampea0d81af2016-10-27 12:04:57 -0700403 mutable Mutex dump_mutex_; // To synchronize visualizer writing.
404
Andreas Gampe53c913b2014-08-12 23:19:23 -0700405 DISALLOW_COPY_AND_ASSIGN(OptimizingCompiler);
406};
407
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100408static const int kMaximumCompilationTimeBeforeWarning = 100; /* ms */
409
410OptimizingCompiler::OptimizingCompiler(CompilerDriver* driver)
Andreas Gampea0d81af2016-10-27 12:04:57 -0700411 : Compiler(driver, kMaximumCompilationTimeBeforeWarning),
412 dump_mutex_("Visualizer dump lock") {}
David Brazdilee690a32014-12-01 17:04:16 +0000413
414void OptimizingCompiler::Init() {
415 // Enable C1visualizer output. Must be done in Init() because the compiler
416 // driver is not fully initialized when passed to the compiler's constructor.
417 CompilerDriver* driver = GetCompilerDriver();
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000418 const std::string cfg_file_name = driver->GetCompilerOptions().GetDumpCfgFileName();
David Brazdil866c0312015-01-13 21:21:31 +0000419 if (!cfg_file_name.empty()) {
Calin Juravle87000a92015-08-24 15:34:44 +0100420 std::ios_base::openmode cfg_file_mode =
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000421 driver->GetCompilerOptions().GetDumpCfgAppend() ? std::ofstream::app : std::ofstream::out;
Calin Juravle87000a92015-08-24 15:34:44 +0100422 visualizer_output_.reset(new std::ofstream(cfg_file_name, cfg_file_mode));
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100423 }
Calin Juravle2be39e02015-04-21 13:56:34 +0100424 if (driver->GetDumpStats()) {
425 compilation_stats_.reset(new OptimizingCompilerStats());
426 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100427}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000428
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000429void OptimizingCompiler::UnInit() const {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000430}
431
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100432OptimizingCompiler::~OptimizingCompiler() {
Calin Juravle2be39e02015-04-21 13:56:34 +0100433 if (compilation_stats_.get() != nullptr) {
434 compilation_stats_->Log();
435 }
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100436}
437
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000438bool OptimizingCompiler::CanCompileMethod(uint32_t method_idx ATTRIBUTE_UNUSED,
Vladimir Markodf739842016-03-23 16:59:07 +0000439 const DexFile& dex_file ATTRIBUTE_UNUSED) const {
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000440 return true;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700441}
442
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000443static bool IsInstructionSetSupported(InstructionSet instruction_set) {
Calin Juravlecff8cc72015-10-09 12:03:24 +0100444 return (instruction_set == kArm && !kArm32QuickCodeUseSoftFloat)
445 || instruction_set == kArm64
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000446 || (instruction_set == kThumb2 && !kArm32QuickCodeUseSoftFloat)
Goran Jakovljevicf652cec2015-08-25 16:11:42 +0200447 || instruction_set == kMips
Alexey Frunze4dda3372015-06-01 18:31:49 -0700448 || instruction_set == kMips64
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000449 || instruction_set == kX86
450 || instruction_set == kX86_64;
451}
452
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700453// Strip pass name suffix to get optimization name.
454static std::string ConvertPassNameToOptimizationName(const std::string& pass_name) {
455 size_t pos = pass_name.find(kPassNameSeparator);
456 return pos == std::string::npos ? pass_name : pass_name.substr(0, pos);
457}
458
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700459static HOptimization* BuildOptimization(
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700460 const std::string& pass_name,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700461 ArenaAllocator* arena,
462 HGraph* graph,
463 OptimizingCompilerStats* stats,
464 CodeGenerator* codegen,
465 CompilerDriver* driver,
466 const DexCompilationUnit& dex_compilation_unit,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700467 VariableSizedHandleScope* handles,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700468 SideEffectsAnalysis* most_recent_side_effects,
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100469 HInductionVarAnalysis* most_recent_induction,
470 LoadStoreAnalysis* most_recent_lsa) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700471 std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700472 if (opt_name == BoundsCheckElimination::kBoundsCheckEliminationPassName) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700473 CHECK(most_recent_side_effects != nullptr && most_recent_induction != nullptr);
474 return new (arena) BoundsCheckElimination(graph,
475 *most_recent_side_effects,
476 most_recent_induction);
477 } else if (opt_name == GVNOptimization::kGlobalValueNumberingPassName) {
478 CHECK(most_recent_side_effects != nullptr);
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700479 return new (arena) GVNOptimization(graph, *most_recent_side_effects, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700480 } else if (opt_name == HConstantFolding::kConstantFoldingPassName) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700481 return new (arena) HConstantFolding(graph, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700482 } else if (opt_name == HDeadCodeElimination::kDeadCodeEliminationPassName) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700483 return new (arena) HDeadCodeElimination(graph, stats, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700484 } else if (opt_name == HInliner::kInlinerPassName) {
485 size_t number_of_dex_registers = dex_compilation_unit.GetCodeItem()->registers_size_;
486 return new (arena) HInliner(graph, // outer_graph
487 graph, // outermost_graph
488 codegen,
489 dex_compilation_unit, // outer_compilation_unit
490 dex_compilation_unit, // outermost_compilation_unit
491 driver,
492 handles,
493 stats,
494 number_of_dex_registers,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000495 /* total_number_of_instructions */ 0,
496 /* parent */ nullptr);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700497 } else if (opt_name == HSharpening::kSharpeningPassName) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000498 return new (arena) HSharpening(graph, codegen, dex_compilation_unit, driver, handles);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700499 } 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) {
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000504 return new (arena) InstructionSimplifier(graph, codegen, 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);
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100510 } else if (opt_name == LoadStoreAnalysis::kLoadStoreAnalysisPassName) {
511 return new (arena) LoadStoreAnalysis(graph);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700512 } else if (opt_name == LoadStoreElimination::kLoadStoreEliminationPassName) {
513 CHECK(most_recent_side_effects != nullptr);
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100514 CHECK(most_recent_lsa != nullptr);
515 return new (arena) LoadStoreElimination(graph, *most_recent_side_effects, *most_recent_lsa);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700516 } else if (opt_name == SideEffectsAnalysis::kSideEffectsAnalysisPassName) {
517 return new (arena) SideEffectsAnalysis(graph);
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100518 } else if (opt_name == HLoopOptimization::kLoopOptimizationPassName) {
Aart Bik92685a82017-03-06 11:13:43 -0800519 return new (arena) HLoopOptimization(graph, driver, most_recent_induction);
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800520 } else if (opt_name == CHAGuardOptimization::kCHAGuardOptimizationPassName) {
521 return new (arena) CHAGuardOptimization(graph);
Nicolas Geoffrayb813ca12017-02-16 22:08:29 +0000522 } else if (opt_name == CodeSinking::kCodeSinkingPassName) {
523 return new (arena) CodeSinking(graph, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700524#ifdef ART_ENABLE_CODEGEN_arm
525 } else if (opt_name == arm::DexCacheArrayFixups::kDexCacheArrayFixupsArmPassName) {
Vladimir Marko68c981f2016-08-26 13:13:33 +0100526 return new (arena) arm::DexCacheArrayFixups(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700527 } else if (opt_name == arm::InstructionSimplifierArm::kInstructionSimplifierArmPassName) {
528 return new (arena) arm::InstructionSimplifierArm(graph, stats);
529#endif
530#ifdef ART_ENABLE_CODEGEN_arm64
531 } else if (opt_name == arm64::InstructionSimplifierArm64::kInstructionSimplifierArm64PassName) {
532 return new (arena) arm64::InstructionSimplifierArm64(graph, stats);
533#endif
534#ifdef ART_ENABLE_CODEGEN_mips
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700535 } else if (opt_name == mips::DexCacheArrayFixups::kDexCacheArrayFixupsMipsPassName) {
536 return new (arena) mips::DexCacheArrayFixups(graph, codegen, stats);
537 } else if (opt_name == mips::PcRelativeFixups::kPcRelativeFixupsMipsPassName) {
538 return new (arena) mips::PcRelativeFixups(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700539#endif
540#ifdef ART_ENABLE_CODEGEN_x86
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700541 } else if (opt_name == x86::PcRelativeFixups::kPcRelativeFixupsX86PassName) {
542 return new (arena) x86::PcRelativeFixups(graph, codegen, stats);
543 } else if (opt_name == x86::X86MemoryOperandGeneration::kX86MemoryOperandGenerationPassName) {
544 return new (arena) x86::X86MemoryOperandGeneration(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700545#endif
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700546 }
547 return nullptr;
548}
549
550static ArenaVector<HOptimization*> BuildOptimizations(
551 const std::vector<std::string>& pass_names,
552 ArenaAllocator* arena,
553 HGraph* graph,
554 OptimizingCompilerStats* stats,
555 CodeGenerator* codegen,
556 CompilerDriver* driver,
557 const DexCompilationUnit& dex_compilation_unit,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700558 VariableSizedHandleScope* handles) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700559 // Few HOptimizations constructors require SideEffectsAnalysis or HInductionVarAnalysis
560 // instances. This method assumes that each of them expects the nearest instance preceeding it
561 // in the pass name list.
562 SideEffectsAnalysis* most_recent_side_effects = nullptr;
563 HInductionVarAnalysis* most_recent_induction = nullptr;
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100564 LoadStoreAnalysis* most_recent_lsa = nullptr;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700565 ArenaVector<HOptimization*> ret(arena->Adapter());
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700566 for (const std::string& pass_name : pass_names) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700567 HOptimization* opt = BuildOptimization(
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700568 pass_name,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700569 arena,
570 graph,
571 stats,
572 codegen,
573 driver,
574 dex_compilation_unit,
575 handles,
576 most_recent_side_effects,
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100577 most_recent_induction,
578 most_recent_lsa);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700579 CHECK(opt != nullptr) << "Couldn't build optimization: \"" << pass_name << "\"";
580 ret.push_back(opt);
581
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700582 std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700583 if (opt_name == SideEffectsAnalysis::kSideEffectsAnalysisPassName) {
584 most_recent_side_effects = down_cast<SideEffectsAnalysis*>(opt);
585 } else if (opt_name == HInductionVarAnalysis::kInductionPassName) {
586 most_recent_induction = down_cast<HInductionVarAnalysis*>(opt);
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100587 } else if (opt_name == LoadStoreAnalysis::kLoadStoreAnalysisPassName) {
588 most_recent_lsa = down_cast<LoadStoreAnalysis*>(opt);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700589 }
590 }
591 return ret;
592}
593
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700594void OptimizingCompiler::RunOptimizations(HOptimization* optimizations[],
595 size_t length,
596 PassObserver* pass_observer) const {
Calin Juravle10e244f2015-01-26 18:54:32 +0000597 for (size_t i = 0; i < length; ++i) {
David Brazdil69ba7b72015-06-23 18:27:30 +0100598 PassScope scope(optimizations[i]->GetPassName(), pass_observer);
599 optimizations[i]->Run();
Calin Juravle10e244f2015-01-26 18:54:32 +0000600 }
601}
602
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700603void OptimizingCompiler::MaybeRunInliner(HGraph* graph,
604 CodeGenerator* codegen,
605 CompilerDriver* driver,
606 const DexCompilationUnit& dex_compilation_unit,
607 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700608 VariableSizedHandleScope* handles) const {
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700609 OptimizingCompilerStats* stats = compilation_stats_.get();
Calin Juravleec748352015-07-29 13:52:12 +0100610 const CompilerOptions& compiler_options = driver->GetCompilerOptions();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000611 bool should_inline = (compiler_options.GetInlineMaxCodeUnits() > 0);
Calin Juravleec748352015-07-29 13:52:12 +0100612 if (!should_inline) {
613 return;
614 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000615 size_t number_of_dex_registers = dex_compilation_unit.GetCodeItem()->registers_size_;
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000616 HInliner* inliner = new (graph->GetArena()) HInliner(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700617 graph, // outer_graph
618 graph, // outermost_graph
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000619 codegen,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700620 dex_compilation_unit, // outer_compilation_unit
621 dex_compilation_unit, // outermost_compilation_unit
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000622 driver,
623 handles,
624 stats,
625 number_of_dex_registers,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000626 /* total_number_of_instructions */ 0,
627 /* parent */ nullptr);
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000628 HOptimization* optimizations[] = { inliner };
Calin Juravleec748352015-07-29 13:52:12 +0100629
630 RunOptimizations(optimizations, arraysize(optimizations), pass_observer);
631}
632
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700633void OptimizingCompiler::RunArchOptimizations(InstructionSet instruction_set,
634 HGraph* graph,
635 CodeGenerator* codegen,
636 PassObserver* pass_observer) const {
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700637 UNUSED(codegen); // To avoid compilation error when compiling for svelte
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700638 OptimizingCompilerStats* stats = compilation_stats_.get();
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100639 ArenaAllocator* arena = graph->GetArena();
640 switch (instruction_set) {
Artem Serov2bbc9532016-10-21 11:51:50 +0100641#if defined(ART_ENABLE_CODEGEN_arm)
Vladimir Markob4536b72015-11-24 13:45:23 +0000642 case kThumb2:
643 case kArm: {
Vladimir Marko68c981f2016-08-26 13:13:33 +0100644 arm::DexCacheArrayFixups* fixups =
645 new (arena) arm::DexCacheArrayFixups(graph, codegen, stats);
Artem Udovichenko4a0dad62016-01-26 12:28:31 +0300646 arm::InstructionSimplifierArm* simplifier =
647 new (arena) arm::InstructionSimplifierArm(graph, stats);
Artem Serov328429f2016-07-06 16:23:04 +0100648 SideEffectsAnalysis* side_effects = new (arena) SideEffectsAnalysis(graph);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700649 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects, "GVN$after_arch");
xueliang.zhongf7caf682017-03-01 16:07:02 +0000650 HInstructionScheduling* scheduling =
651 new (arena) HInstructionScheduling(graph, instruction_set, codegen);
Vladimir Markob4536b72015-11-24 13:45:23 +0000652 HOptimization* arm_optimizations[] = {
Artem Udovichenko4a0dad62016-01-26 12:28:31 +0300653 simplifier,
Artem Serov328429f2016-07-06 16:23:04 +0100654 side_effects,
655 gvn,
xueliang.zhongf7caf682017-03-01 16:07:02 +0000656 fixups,
657 scheduling,
Vladimir Markob4536b72015-11-24 13:45:23 +0000658 };
659 RunOptimizations(arm_optimizations, arraysize(arm_optimizations), pass_observer);
660 break;
661 }
662#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100663#ifdef ART_ENABLE_CODEGEN_arm64
664 case kArm64: {
665 arm64::InstructionSimplifierArm64* simplifier =
666 new (arena) arm64::InstructionSimplifierArm64(graph, stats);
667 SideEffectsAnalysis* side_effects = new (arena) SideEffectsAnalysis(graph);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700668 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects, "GVN$after_arch");
Alexandre Rames22aa54b2016-10-18 09:32:29 +0100669 HInstructionScheduling* scheduling =
670 new (arena) HInstructionScheduling(graph, instruction_set);
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100671 HOptimization* arm64_optimizations[] = {
672 simplifier,
673 side_effects,
Alexandre Rames22aa54b2016-10-18 09:32:29 +0100674 gvn,
675 scheduling,
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100676 };
677 RunOptimizations(arm64_optimizations, arraysize(arm64_optimizations), pass_observer);
678 break;
679 }
680#endif
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700681#ifdef ART_ENABLE_CODEGEN_mips
682 case kMips: {
683 mips::PcRelativeFixups* pc_relative_fixups =
684 new (arena) mips::PcRelativeFixups(graph, codegen, stats);
685 mips::DexCacheArrayFixups* dex_cache_array_fixups =
Alexey Frunze06a46c42016-07-19 15:00:40 -0700686 new (arena) mips::DexCacheArrayFixups(graph, codegen, stats);
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700687 HOptimization* mips_optimizations[] = {
688 pc_relative_fixups,
689 dex_cache_array_fixups
690 };
691 RunOptimizations(mips_optimizations, arraysize(mips_optimizations), pass_observer);
692 break;
693 }
694#endif
Mark Mendell0616ae02015-04-17 12:49:27 -0400695#ifdef ART_ENABLE_CODEGEN_x86
696 case kX86: {
Aart Bikd1c40452016-03-02 16:06:13 -0800697 x86::PcRelativeFixups* pc_relative_fixups =
698 new (arena) x86::PcRelativeFixups(graph, codegen, stats);
Mark Mendellee8d9712016-07-12 11:13:15 -0400699 x86::X86MemoryOperandGeneration* memory_gen =
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700700 new (arena) x86::X86MemoryOperandGeneration(graph, codegen, stats);
Mark Mendell0616ae02015-04-17 12:49:27 -0400701 HOptimization* x86_optimizations[] = {
Mark Mendellee8d9712016-07-12 11:13:15 -0400702 pc_relative_fixups,
703 memory_gen
Mark Mendell0616ae02015-04-17 12:49:27 -0400704 };
705 RunOptimizations(x86_optimizations, arraysize(x86_optimizations), pass_observer);
706 break;
707 }
708#endif
Mark Mendellee8d9712016-07-12 11:13:15 -0400709#ifdef ART_ENABLE_CODEGEN_x86_64
710 case kX86_64: {
711 x86::X86MemoryOperandGeneration* memory_gen =
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700712 new (arena) x86::X86MemoryOperandGeneration(graph, codegen, stats);
Mark Mendellee8d9712016-07-12 11:13:15 -0400713 HOptimization* x86_64_optimizations[] = {
714 memory_gen
715 };
716 RunOptimizations(x86_64_optimizations, arraysize(x86_64_optimizations), pass_observer);
717 break;
718 }
719#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100720 default:
721 break;
722 }
723}
724
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000725NO_INLINE // Avoid increasing caller's frame size by large stack-allocated objects.
726static void AllocateRegisters(HGraph* graph,
727 CodeGenerator* codegen,
Matthew Gharrity2cd05b72016-08-03 16:57:37 -0700728 PassObserver* pass_observer,
729 RegisterAllocator::Strategy strategy) {
Mingyao Yang700347e2016-03-02 14:59:32 -0800730 {
731 PassScope scope(PrepareForRegisterAllocation::kPrepareForRegisterAllocationPassName,
732 pass_observer);
733 PrepareForRegisterAllocation(graph).Run();
734 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000735 SsaLivenessAnalysis liveness(graph, codegen);
736 {
737 PassScope scope(SsaLivenessAnalysis::kLivenessPassName, pass_observer);
738 liveness.Analyze();
739 }
740 {
741 PassScope scope(RegisterAllocator::kRegisterAllocatorPassName, pass_observer);
Matthew Gharrity2cd05b72016-08-03 16:57:37 -0700742 RegisterAllocator::Create(graph->GetArena(), codegen, liveness, strategy)->AllocateRegisters();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000743 }
744}
745
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700746void OptimizingCompiler::RunOptimizations(HGraph* graph,
747 CodeGenerator* codegen,
748 CompilerDriver* driver,
749 const DexCompilationUnit& dex_compilation_unit,
750 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700751 VariableSizedHandleScope* handles) const {
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700752 OptimizingCompilerStats* stats = compilation_stats_.get();
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100753 ArenaAllocator* arena = graph->GetArena();
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700754 if (driver->GetCompilerOptions().GetPassesToRun() != nullptr) {
755 ArenaVector<HOptimization*> optimizations = BuildOptimizations(
756 *driver->GetCompilerOptions().GetPassesToRun(),
757 arena,
758 graph,
759 stats,
760 codegen,
761 driver,
762 dex_compilation_unit,
763 handles);
764 RunOptimizations(&optimizations[0], optimizations.size(), pass_observer);
765 return;
766 }
767
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100768 HDeadCodeElimination* dce1 = new (arena) HDeadCodeElimination(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700769 graph, stats, "dead_code_elimination$initial");
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100770 HDeadCodeElimination* dce2 = new (arena) HDeadCodeElimination(
Aart Bik2767f4b2016-10-28 15:03:53 -0700771 graph, stats, "dead_code_elimination$after_inlining");
772 HDeadCodeElimination* dce3 = new (arena) HDeadCodeElimination(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700773 graph, stats, "dead_code_elimination$final");
Andreas Gampeca620d72016-11-08 08:09:33 -0800774 HConstantFolding* fold1 = new (arena) HConstantFolding(graph, "constant_folding");
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000775 InstructionSimplifier* simplify1 = new (arena) InstructionSimplifier(graph, codegen, stats);
Jean-Philippe Halimi38e9e802016-02-18 16:42:03 +0100776 HSelectGenerator* select_generator = new (arena) HSelectGenerator(graph, stats);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700777 HConstantFolding* fold2 = new (arena) HConstantFolding(
778 graph, "constant_folding$after_inlining");
779 HConstantFolding* fold3 = new (arena) HConstantFolding(graph, "constant_folding$after_bce");
Aart Bik92685a82017-03-06 11:13:43 -0800780 SideEffectsAnalysis* side_effects1 = new (arena) SideEffectsAnalysis(
781 graph, "side_effects$before_gvn");
782 SideEffectsAnalysis* side_effects2 = new (arena) SideEffectsAnalysis(
783 graph, "side_effects$before_lse");
784 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects1);
785 LICM* licm = new (arena) LICM(graph, *side_effects1, stats);
Aart Bik22af3be2015-09-10 12:50:58 -0700786 HInductionVarAnalysis* induction = new (arena) HInductionVarAnalysis(graph);
Aart Bik92685a82017-03-06 11:13:43 -0800787 BoundsCheckElimination* bce = new (arena) BoundsCheckElimination(graph, *side_effects1, induction);
788 HLoopOptimization* loop = new (arena) HLoopOptimization(graph, driver, induction);
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100789 LoadStoreAnalysis* lsa = new (arena) LoadStoreAnalysis(graph);
790 LoadStoreElimination* lse = new (arena) LoadStoreElimination(graph, *side_effects2, *lsa);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000791 HSharpening* sharpening = new (arena) HSharpening(
792 graph, codegen, dex_compilation_unit, driver, handles);
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100793 InstructionSimplifier* simplify2 = new (arena) InstructionSimplifier(
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000794 graph, codegen, stats, "instruction_simplifier$after_inlining");
David Brazdil4833f5a2015-12-16 10:37:39 +0000795 InstructionSimplifier* simplify3 = new (arena) InstructionSimplifier(
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000796 graph, codegen, stats, "instruction_simplifier$after_bce");
Aart Bik639cc8c2016-10-18 13:03:31 -0700797 InstructionSimplifier* simplify4 = new (arena) InstructionSimplifier(
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000798 graph, codegen, stats, "instruction_simplifier$before_codegen");
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100799 IntrinsicsRecognizer* intrinsics = new (arena) IntrinsicsRecognizer(graph, stats);
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800800 CHAGuardOptimization* cha_guard = new (arena) CHAGuardOptimization(graph);
Nicolas Geoffrayb813ca12017-02-16 22:08:29 +0000801 CodeSinking* code_sinking = new (arena) CodeSinking(graph, stats);
Andreas Gampe71fb52f2014-12-29 17:43:08 -0800802
Calin Juravleec748352015-07-29 13:52:12 +0100803 HOptimization* optimizations1[] = {
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100804 intrinsics,
David Brazdil4833f5a2015-12-16 10:37:39 +0000805 sharpening,
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100806 fold1,
807 simplify1,
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100808 dce1,
Calin Juravleec748352015-07-29 13:52:12 +0100809 };
Calin Juravleec748352015-07-29 13:52:12 +0100810 RunOptimizations(optimizations1, arraysize(optimizations1), pass_observer);
811
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700812 MaybeRunInliner(graph, codegen, driver, dex_compilation_unit, pass_observer, handles);
David Brazdil95177982015-10-30 12:56:58 -0500813
David Brazdil8993caf2015-12-07 10:04:40 +0000814 HOptimization* optimizations2[] = {
David Brazdil74eb1b22015-12-14 11:44:01 +0000815 // SelectGenerator depends on the InstructionSimplifier removing
David Brazdil8993caf2015-12-07 10:04:40 +0000816 // redundant suspend checks to recognize empty blocks.
David Brazdil74eb1b22015-12-14 11:44:01 +0000817 select_generator,
David Brazdil8993caf2015-12-07 10:04:40 +0000818 fold2, // TODO: if we don't inline we can also skip fold2.
Aart Bik639cc8c2016-10-18 13:03:31 -0700819 simplify2,
Aart Bik2767f4b2016-10-28 15:03:53 -0700820 dce2,
Aart Bik92685a82017-03-06 11:13:43 -0800821 side_effects1,
David Brazdil8993caf2015-12-07 10:04:40 +0000822 gvn,
823 licm,
824 induction,
825 bce,
Aart Bik281c6812016-08-26 11:31:48 -0700826 loop,
David Brazdil8993caf2015-12-07 10:04:40 +0000827 fold3, // evaluates code generated by dynamic bce
Aart Bik639cc8c2016-10-18 13:03:31 -0700828 simplify3,
Aart Bik92685a82017-03-06 11:13:43 -0800829 side_effects2,
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100830 lsa,
David Brazdil8993caf2015-12-07 10:04:40 +0000831 lse,
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800832 cha_guard,
Aart Bik2767f4b2016-10-28 15:03:53 -0700833 dce3,
Nicolas Geoffrayb813ca12017-02-16 22:08:29 +0000834 code_sinking,
David Brazdil8993caf2015-12-07 10:04:40 +0000835 // The codegen has a few assumptions that only the instruction simplifier
836 // can satisfy. For example, the code generator does not expect to see a
837 // HTypeConversion from a type to the same type.
Aart Bik639cc8c2016-10-18 13:03:31 -0700838 simplify4,
David Brazdil8993caf2015-12-07 10:04:40 +0000839 };
840 RunOptimizations(optimizations2, arraysize(optimizations2), pass_observer);
David Brazdilbbd733e2015-08-18 17:48:17 +0100841
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700842 RunArchOptimizations(driver->GetInstructionSet(), graph, codegen, pass_observer);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000843}
844
Vladimir Marko58155012015-08-19 12:49:41 +0000845static ArenaVector<LinkerPatch> EmitAndSortLinkerPatches(CodeGenerator* codegen) {
846 ArenaVector<LinkerPatch> linker_patches(codegen->GetGraph()->GetArena()->Adapter());
847 codegen->EmitLinkerPatches(&linker_patches);
848
849 // Sort patches by literal offset. Required for .oat_patches encoding.
850 std::sort(linker_patches.begin(), linker_patches.end(),
851 [](const LinkerPatch& lhs, const LinkerPatch& rhs) {
852 return lhs.LiteralOffset() < rhs.LiteralOffset();
853 });
854
855 return linker_patches;
856}
857
David Brazdil58282f42016-01-14 12:45:10 +0000858CompiledMethod* OptimizingCompiler::Emit(ArenaAllocator* arena,
859 CodeVectorAllocator* code_allocator,
860 CodeGenerator* codegen,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000861 CompilerDriver* compiler_driver,
862 const DexFile::CodeItem* code_item) const {
Vladimir Marko58155012015-08-19 12:49:41 +0000863 ArenaVector<LinkerPatch> linker_patches = EmitAndSortLinkerPatches(codegen);
Vladimir Markof9f64412015-09-02 14:05:49 +0100864 ArenaVector<uint8_t> stack_map(arena->Adapter(kArenaAllocStackMaps));
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700865 ArenaVector<uint8_t> method_info(arena->Adapter(kArenaAllocStackMaps));
866 size_t stack_map_size = 0;
867 size_t method_info_size = 0;
868 codegen->ComputeStackMapAndMethodInfoSize(&stack_map_size, &method_info_size);
869 stack_map.resize(stack_map_size);
870 method_info.resize(method_info_size);
871 codegen->BuildStackMaps(MemoryRegion(stack_map.data(), stack_map.size()),
872 MemoryRegion(method_info.data(), method_info.size()),
873 *code_item);
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000874
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100875 CompiledMethod* compiled_method = CompiledMethod::SwapAllocCompiledMethod(
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000876 compiler_driver,
877 codegen->GetInstructionSet(),
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000878 ArrayRef<const uint8_t>(code_allocator->GetMemory()),
Roland Levillainaa9b7c42015-02-17 15:40:09 +0000879 // Follow Quick's behavior and set the frame size to zero if it is
880 // considered "empty" (see the definition of
881 // art::CodeGenerator::HasEmptyFrame).
882 codegen->HasEmptyFrame() ? 0 : codegen->GetFrameSize(),
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000883 codegen->GetCoreSpillMask(),
Nicolas Geoffrayd97dc402015-01-22 13:50:01 +0000884 codegen->GetFpuSpillMask(),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700885 ArrayRef<const uint8_t>(method_info),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100886 ArrayRef<const uint8_t>(stack_map),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100887 ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data()),
Vladimir Marko58155012015-08-19 12:49:41 +0000888 ArrayRef<const LinkerPatch>(linker_patches));
Mathieu Chartiered150002015-08-28 11:16:54 -0700889
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100890 return compiled_method;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000891}
892
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000893CodeGenerator* OptimizingCompiler::TryCompile(ArenaAllocator* arena,
894 CodeVectorAllocator* code_allocator,
895 const DexFile::CodeItem* code_item,
896 uint32_t access_flags,
897 InvokeType invoke_type,
898 uint16_t class_def_idx,
899 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000900 Handle<mirror::ClassLoader> class_loader,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000901 const DexFile& dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000902 Handle<mirror::DexCache> dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000903 ArtMethod* method,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000904 bool osr,
905 VariableSizedHandleScope* handles) const {
Calin Juravle2be39e02015-04-21 13:56:34 +0100906 MaybeRecordStat(MethodCompilationStat::kAttemptCompilation);
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000907 CompilerDriver* compiler_driver = GetCompilerDriver();
908 InstructionSet instruction_set = compiler_driver->GetInstructionSet();
Calin Juravlecff8cc72015-10-09 12:03:24 +0100909
Roland Levillain3b359c72015-11-17 19:35:12 +0000910 // Always use the Thumb-2 assembler: some runtime functionality
911 // (like implicit stack overflow checks) assume Thumb-2.
Artem Serovba6b6792016-08-15 14:22:07 +0100912 DCHECK_NE(instruction_set, kArm);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100913
914 // Do not attempt to compile on architectures we do not support.
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000915 if (!IsInstructionSetSupported(instruction_set)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100916 MaybeRecordStat(MethodCompilationStat::kNotCompiledUnsupportedIsa);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100917 return nullptr;
918 }
919
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000920 if (Compiler::IsPathologicalCase(*code_item, method_idx, dex_file)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100921 MaybeRecordStat(MethodCompilationStat::kNotCompiledPathological);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000922 return nullptr;
923 }
924
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000925 // Implementation of the space filter: do not compile a code item whose size in
Nicolas Geoffray432bf3d2015-07-17 11:11:09 +0100926 // code units is bigger than 128.
927 static constexpr size_t kSpaceFilterOptimizingThreshold = 128;
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000928 const CompilerOptions& compiler_options = compiler_driver->GetCompilerOptions();
Andreas Gampe29d38e72016-03-23 15:31:51 +0000929 if ((compiler_options.GetCompilerFilter() == CompilerFilter::kSpace)
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000930 && (code_item->insns_size_in_code_units_ > kSpaceFilterOptimizingThreshold)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100931 MaybeRecordStat(MethodCompilationStat::kNotCompiledSpaceFilter);
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000932 return nullptr;
933 }
934
Vladimir Marko97d7e1c2016-10-04 14:44:28 +0100935 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000936 DexCompilationUnit dex_compilation_unit(
Vladimir Markodf739842016-03-23 16:59:07 +0000937 class_loader,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +0100938 class_linker,
Vladimir Markodf739842016-03-23 16:59:07 +0000939 dex_file,
940 code_item,
941 class_def_idx,
942 method_idx,
943 access_flags,
944 /* verified_method */ nullptr,
945 dex_cache);
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000946
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000947 HGraph* graph = new (arena) HGraph(
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000948 arena,
949 dex_file,
950 method_idx,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000951 compiler_driver->GetInstructionSet(),
952 kInvalidInvokeType,
953 compiler_driver->GetCompilerOptions().GetDebuggable(),
954 osr);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000955
David Brazdilbadd8262016-02-02 16:28:56 +0000956 const uint8_t* interpreter_metadata = nullptr;
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000957 if (method == nullptr) {
David Brazdilbadd8262016-02-02 16:28:56 +0000958 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000959 method = compiler_driver->ResolveMethod(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000960 soa, dex_cache, class_loader, &dex_compilation_unit, method_idx, invoke_type);
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000961 }
962 // For AOT compilation, we may not get a method, for example if its class is erroneous.
963 // JIT should always have a method.
964 DCHECK(Runtime::Current()->IsAotCompiler() || method != nullptr);
965 if (method != nullptr) {
966 graph->SetArtMethod(method);
967 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +0100968 interpreter_metadata = method->GetQuickenedInfo(class_linker->GetImagePointerSize());
David Brazdilbadd8262016-02-02 16:28:56 +0000969 }
970
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000971 std::unique_ptr<CodeGenerator> codegen(
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000972 CodeGenerator::Create(graph,
973 instruction_set,
974 *compiler_driver->GetInstructionSetFeatures(),
Calin Juravle2ae48182016-03-16 14:05:09 +0000975 compiler_driver->GetCompilerOptions(),
976 compilation_stats_.get()));
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000977 if (codegen.get() == nullptr) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100978 MaybeRecordStat(MethodCompilationStat::kNotCompiledNoCodegen);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000979 return nullptr;
980 }
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100981 codegen->GetAssembler()->cfi().SetEnabled(
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000982 compiler_driver->GetCompilerOptions().GenerateAnyDebugInfo());
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000983
David Brazdil69ba7b72015-06-23 18:27:30 +0100984 PassObserver pass_observer(graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100985 codegen.get(),
986 visualizer_output_.get(),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700987 compiler_driver,
988 dump_mutex_);
David Brazdil5e8b1372015-01-23 14:39:08 +0000989
David Brazdil809658e2015-02-05 11:34:02 +0000990 {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000991 VLOG(compiler) << "Building " << pass_observer.GetMethodName();
992 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
993 HGraphBuilder builder(graph,
994 &dex_compilation_unit,
995 &dex_compilation_unit,
996 &dex_file,
997 *code_item,
998 compiler_driver,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000999 codegen.get(),
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001000 compilation_stats_.get(),
1001 interpreter_metadata,
1002 dex_cache,
1003 handles);
1004 GraphAnalysisResult result = builder.BuildGraph();
1005 if (result != kAnalysisSuccess) {
1006 switch (result) {
1007 case kAnalysisSkipped:
1008 MaybeRecordStat(MethodCompilationStat::kNotCompiledSkipped);
1009 break;
1010 case kAnalysisInvalidBytecode:
1011 MaybeRecordStat(MethodCompilationStat::kNotCompiledInvalidBytecode);
1012 break;
1013 case kAnalysisFailThrowCatchLoop:
1014 MaybeRecordStat(MethodCompilationStat::kNotCompiledThrowCatchLoop);
1015 break;
1016 case kAnalysisFailAmbiguousArrayOp:
1017 MaybeRecordStat(MethodCompilationStat::kNotCompiledAmbiguousArrayOp);
1018 break;
1019 case kAnalysisSuccess:
1020 UNREACHABLE();
David Brazdil809658e2015-02-05 11:34:02 +00001021 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001022 pass_observer.SetGraphInBadState();
1023 return nullptr;
Nicolas Geoffrayf5370122014-12-02 11:51:19 +00001024 }
David Brazdilbadd8262016-02-02 16:28:56 +00001025 }
Vladimir Markof9f64412015-09-02 14:05:49 +01001026
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001027 RunOptimizations(graph,
1028 codegen.get(),
1029 compiler_driver,
1030 dex_compilation_unit,
1031 &pass_observer,
1032 handles);
1033
1034 RegisterAllocator::Strategy regalloc_strategy =
1035 compiler_options.GetRegisterAllocationStrategy();
1036 AllocateRegisters(graph, codegen.get(), &pass_observer, regalloc_strategy);
1037
1038 codegen->Compile(code_allocator);
1039 pass_observer.DumpDisassembly();
1040
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001041 return codegen.release();
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001042}
1043
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001044CompiledMethod* OptimizingCompiler::Compile(const DexFile::CodeItem* code_item,
1045 uint32_t access_flags,
1046 InvokeType invoke_type,
1047 uint16_t class_def_idx,
1048 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001049 Handle<mirror::ClassLoader> jclass_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -07001050 const DexFile& dex_file,
1051 Handle<mirror::DexCache> dex_cache) const {
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001052 CompilerDriver* compiler_driver = GetCompilerDriver();
1053 CompiledMethod* method = nullptr;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001054 DCHECK(Runtime::Current()->IsAotCompiler());
1055 const VerifiedMethod* verified_method = compiler_driver->GetVerifiedMethod(&dex_file, method_idx);
1056 DCHECK(!verified_method->HasRuntimeThrow());
1057 if (compiler_driver->IsMethodVerifiedWithoutFailures(method_idx, class_def_idx, dex_file)
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001058 || verifier::CanCompilerHandleVerificationFailure(
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001059 verified_method->GetEncounteredVerificationFailures())) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001060 ArenaAllocator arena(Runtime::Current()->GetArenaPool());
1061 CodeVectorAllocator code_allocator(&arena);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001062 std::unique_ptr<CodeGenerator> codegen;
1063 {
1064 ScopedObjectAccess soa(Thread::Current());
1065 VariableSizedHandleScope handles(soa.Self());
1066 // Go to native so that we don't block GC during compilation.
1067 ScopedThreadSuspension sts(soa.Self(), kNative);
1068 codegen.reset(
1069 TryCompile(&arena,
1070 &code_allocator,
1071 code_item,
1072 access_flags,
1073 invoke_type,
1074 class_def_idx,
1075 method_idx,
1076 jclass_loader,
1077 dex_file,
1078 dex_cache,
1079 nullptr,
1080 /* osr */ false,
1081 &handles));
1082 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001083 if (codegen.get() != nullptr) {
Calin Juravlead543382015-11-19 17:26:29 +00001084 MaybeRecordStat(MethodCompilationStat::kCompiled);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001085 method = Emit(&arena, &code_allocator, codegen.get(), compiler_driver, code_item);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001086
1087 if (kArenaAllocatorCountAllocations) {
1088 if (arena.BytesAllocated() > kArenaAllocatorMemoryReportThreshold) {
1089 MemStats mem_stats(arena.GetMemStats());
David Sehr709b0702016-10-13 09:12:37 -07001090 LOG(INFO) << dex_file.PrettyMethod(method_idx) << " " << Dumpable<MemStats>(mem_stats);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001091 }
1092 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001093 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001094 } else {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001095 if (compiler_driver->GetCompilerOptions().VerifyAtRuntime()) {
1096 MaybeRecordStat(MethodCompilationStat::kNotCompiledVerifyAtRuntime);
1097 } else {
Calin Juravlead543382015-11-19 17:26:29 +00001098 MaybeRecordStat(MethodCompilationStat::kNotCompiledVerificationError);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001099 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001100 }
1101
Calin Juravlecff8cc72015-10-09 12:03:24 +01001102 if (kIsDebugBuild &&
1103 IsCompilingWithCoreImage() &&
Goran Jakovljevic9c4f0d8f2017-04-05 16:27:25 +02001104 IsInstructionSetSupported(compiler_driver->GetInstructionSet())) {
Roland Levillain0d5a2812015-11-13 10:07:31 +00001105 // For testing purposes, we put a special marker on method names
Goran Jakovljevic9c4f0d8f2017-04-05 16:27:25 +02001106 // that should be compiled with this compiler (when the
1107 // instruction set is supported). This makes sure we're not
Roland Levillain0d5a2812015-11-13 10:07:31 +00001108 // regressing.
David Sehr709b0702016-10-13 09:12:37 -07001109 std::string method_name = dex_file.PrettyMethod(method_idx);
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001110 bool shouldCompile = method_name.find("$opt$") != std::string::npos;
1111 DCHECK((method != nullptr) || !shouldCompile) << "Didn't compile " << method_name;
1112 }
1113
Nicolas Geoffray12be74e2015-03-30 13:29:08 +01001114 return method;
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001115}
1116
Andreas Gampe53c913b2014-08-12 23:19:23 -07001117Compiler* CreateOptimizingCompiler(CompilerDriver* driver) {
1118 return new OptimizingCompiler(driver);
1119}
1120
Nicolas Geoffray335005e2015-06-25 10:01:47 +01001121bool IsCompilingWithCoreImage() {
1122 const std::string& image = Runtime::Current()->GetImageLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001123 // TODO: This is under-approximating...
Andreas Gampe9186ced2016-12-12 14:28:21 -08001124 if (android::base::EndsWith(image, "core.art") ||
1125 android::base::EndsWith(image, "core-optimizing.art")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001126 return true;
1127 }
1128 return false;
Nicolas Geoffray335005e2015-06-25 10:01:47 +01001129}
1130
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001131bool EncodeArtMethodInInlineInfo(ArtMethod* method ATTRIBUTE_UNUSED) {
1132 // Note: the runtime is null only for unit testing.
1133 return Runtime::Current() == nullptr || !Runtime::Current()->IsAotCompiler();
1134}
1135
1136bool CanEncodeInlinedMethodInStackMap(const DexFile& caller_dex_file, ArtMethod* callee) {
1137 if (!Runtime::Current()->IsAotCompiler()) {
1138 // JIT can always encode methods in stack maps.
1139 return true;
1140 }
1141 if (IsSameDexFile(caller_dex_file, *callee->GetDexFile())) {
1142 return true;
1143 }
1144 // TODO(ngeoffray): Support more AOT cases for inlining:
1145 // - methods in multidex
1146 // - methods in boot image for on-device non-PIC compilation.
1147 return false;
1148}
1149
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001150bool OptimizingCompiler::JitCompile(Thread* self,
1151 jit::JitCodeCache* code_cache,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001152 ArtMethod* method,
1153 bool osr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001154 StackHandleScope<3> hs(self);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001155 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1156 method->GetDeclaringClass()->GetClassLoader()));
1157 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001158 DCHECK(method->IsCompilable());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001159
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001160 const DexFile* dex_file = method->GetDexFile();
1161 const uint16_t class_def_idx = method->GetClassDefIndex();
1162 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
1163 const uint32_t method_idx = method->GetDexMethodIndex();
1164 const uint32_t access_flags = method->GetAccessFlags();
1165 const InvokeType invoke_type = method->GetInvokeType();
1166
Nicolas Geoffray25e04562016-03-01 13:17:58 +00001167 ArenaAllocator arena(Runtime::Current()->GetJitArenaPool());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001168 CodeVectorAllocator code_allocator(&arena);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001169 VariableSizedHandleScope handles(self);
1170
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001171 std::unique_ptr<CodeGenerator> codegen;
1172 {
1173 // Go to native so that we don't block GC during compilation.
1174 ScopedThreadSuspension sts(self, kNative);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001175 codegen.reset(
1176 TryCompile(&arena,
1177 &code_allocator,
1178 code_item,
1179 access_flags,
1180 invoke_type,
1181 class_def_idx,
1182 method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001183 class_loader,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001184 *dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001185 dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +00001186 method,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001187 osr,
1188 &handles));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001189 if (codegen.get() == nullptr) {
1190 return false;
1191 }
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001192
1193 if (kArenaAllocatorCountAllocations) {
1194 if (arena.BytesAllocated() > kArenaAllocatorMemoryReportThreshold) {
1195 MemStats mem_stats(arena.GetMemStats());
David Sehr709b0702016-10-13 09:12:37 -07001196 LOG(INFO) << dex_file->PrettyMethod(method_idx) << " " << Dumpable<MemStats>(mem_stats);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001197 }
1198 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001199 }
1200
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001201 size_t stack_map_size = 0;
1202 size_t method_info_size = 0;
1203 codegen->ComputeStackMapAndMethodInfoSize(&stack_map_size, &method_info_size);
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001204 size_t number_of_roots = codegen->GetNumberOfJitRoots();
1205 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1206 // We allocate an object array to ensure the JIT roots that we will collect in EmitJitRoots
1207 // will be visible by the GC between EmitLiterals and CommitCode. Once CommitCode is
1208 // executed, this array is not needed.
1209 Handle<mirror::ObjectArray<mirror::Object>> roots(
1210 hs.NewHandle(mirror::ObjectArray<mirror::Object>::Alloc(
1211 self, class_linker->GetClassRoot(ClassLinker::kObjectArrayClass), number_of_roots)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001212 if (roots == nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001213 // Out of memory, just clear the exception to avoid any Java exception uncaught problems.
1214 DCHECK(self->IsExceptionPending());
1215 self->ClearException();
1216 return false;
1217 }
1218 uint8_t* stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001219 uint8_t* method_info_data = nullptr;
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001220 uint8_t* roots_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001221 uint32_t data_size = code_cache->ReserveData(self,
1222 stack_map_size,
1223 method_info_size,
1224 number_of_roots,
1225 method,
1226 &stack_map_data,
1227 &method_info_data,
1228 &roots_data);
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001229 if (stack_map_data == nullptr || roots_data == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001230 return false;
1231 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001232 MaybeRecordStat(MethodCompilationStat::kCompiled);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001233 codegen->BuildStackMaps(MemoryRegion(stack_map_data, stack_map_size),
1234 MemoryRegion(method_info_data, method_info_size),
1235 *code_item);
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00001236 codegen->EmitJitRoots(code_allocator.GetData(), roots, roots_data);
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001237
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001238 const void* code = code_cache->CommitCode(
1239 self,
1240 method,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001241 stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001242 method_info_data,
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001243 roots_data,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001244 codegen->HasEmptyFrame() ? 0 : codegen->GetFrameSize(),
1245 codegen->GetCoreSpillMask(),
1246 codegen->GetFpuSpillMask(),
1247 code_allocator.GetMemory().data(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001248 code_allocator.GetSize(),
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001249 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001250 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -07001251 roots,
1252 codegen->GetGraph()->HasShouldDeoptimizeFlag(),
1253 codegen->GetGraph()->GetCHASingleImplementationList());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001254
1255 if (code == nullptr) {
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001256 code_cache->ClearData(self, stack_map_data, roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001257 return false;
1258 }
1259
David Srbecky91cc06c2016-03-07 16:13:58 +00001260 const CompilerOptions& compiler_options = GetCompilerDriver()->GetCompilerOptions();
1261 if (compiler_options.GetGenerateDebugInfo()) {
David Srbecky5cc349f2015-12-18 15:04:48 +00001262 const auto* method_header = reinterpret_cast<const OatQuickMethodHeader*>(code);
1263 const uintptr_t code_address = reinterpret_cast<uintptr_t>(method_header->GetCode());
David Srbecky09c2a6b2016-03-11 17:11:44 +00001264 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1265 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +00001266 info.dex_file = dex_file;
1267 info.class_def_index = class_def_idx;
1268 info.dex_method_index = method_idx;
1269 info.access_flags = access_flags;
1270 info.code_item = code_item;
1271 info.isa = codegen->GetInstructionSet();
1272 info.deduped = false;
1273 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1274 info.is_optimized = true;
1275 info.is_code_address_text_relative = false;
1276 info.code_address = code_address;
1277 info.code_size = code_allocator.GetSize();
1278 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
1279 info.code_info = stack_map_size == 0 ? nullptr : stack_map_data;
1280 info.cfi = ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data());
Vladimir Marko93205e32016-04-13 11:59:46 +01001281 std::vector<uint8_t> elf_file = debug::WriteDebugElfFileForMethods(
David Srbecky5d811202016-03-08 13:21:22 +00001282 GetCompilerDriver()->GetInstructionSet(),
1283 GetCompilerDriver()->GetInstructionSetFeatures(),
David Srbeckyfe736b72016-03-09 11:44:44 +00001284 ArrayRef<const debug::MethodDebugInfo>(&info, 1));
Vladimir Marko93205e32016-04-13 11:59:46 +01001285 CreateJITCodeEntryForAddress(code_address, std::move(elf_file));
David Srbecky5cc349f2015-12-18 15:04:48 +00001286 }
1287
Nicolas Geoffraya4f81542016-03-08 16:57:48 +00001288 Runtime::Current()->GetJit()->AddMemoryUsage(method, arena.BytesUsed());
1289
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001290 return true;
1291}
1292
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001293} // namespace art