blob: 065c11eddb59ffd1a0d9238dd57f827bc578beb3 [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"
Mingyao Yang8df69d42015-10-22 15:40:58 -070086#include "load_store_elimination.h"
Aart Bik281c6812016-08-26 11:31:48 -070087#include "loop_optimization.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000088#include "nodes.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000089#include "oat_quick_method_header.h"
Nicolas Geoffray26a25ef2014-09-30 13:54:09 +010090#include "prepare_for_register_allocation.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010091#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070092#include "register_allocator_linear_scan.h"
David Brazdil74eb1b22015-12-14 11:44:01 +000093#include "select_generator.h"
Alexandre Rames22aa54b2016-10-18 09:32:29 +010094#include "scheduler.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010095#include "sharpening.h"
Nicolas Geoffray827eedb2015-01-26 15:18:36 +000096#include "side_effects_analysis.h"
Nicolas Geoffray31596742014-11-24 15:28:45 +000097#include "ssa_builder.h"
Nicolas Geoffray804d0932014-05-02 08:46:00 +010098#include "ssa_liveness_analysis.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000099#include "ssa_phi_elimination.h"
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100100#include "utils/assembler.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -0700101#include "verifier/verifier_compiler_binding.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000102
103namespace art {
104
Vladimir Marko3a40bf22016-03-22 16:26:33 +0000105static constexpr size_t kArenaAllocatorMemoryReportThreshold = 8 * MB;
106
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700107static constexpr const char* kPassNameSeparator = "$";
108
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000109/**
110 * Used by the code generator, to allocate the code in a vector.
111 */
112class CodeVectorAllocator FINAL : public CodeAllocator {
113 public:
Vladimir Markof9f64412015-09-02 14:05:49 +0100114 explicit CodeVectorAllocator(ArenaAllocator* arena)
115 : memory_(arena->Adapter(kArenaAllocCodeBuffer)),
116 size_(0) {}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000117
118 virtual uint8_t* Allocate(size_t size) {
119 size_ = size;
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000120 memory_.resize(size);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000121 return &memory_[0];
122 }
123
124 size_t GetSize() const { return size_; }
Vladimir Markof9f64412015-09-02 14:05:49 +0100125 const ArenaVector<uint8_t>& GetMemory() const { return memory_; }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000126 uint8_t* GetData() { return memory_.data(); }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000127
128 private:
Vladimir Markof9f64412015-09-02 14:05:49 +0100129 ArenaVector<uint8_t> memory_;
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000130 size_t size_;
131
132 DISALLOW_COPY_AND_ASSIGN(CodeVectorAllocator);
133};
134
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100135/**
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100136 * Filter to apply to the visualizer. Methods whose name contain that filter will
David Brazdilee690a32014-12-01 17:04:16 +0000137 * be dumped.
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100138 */
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700139static constexpr const char kStringFilter[] = "";
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100140
David Brazdil69ba7b72015-06-23 18:27:30 +0100141class PassScope;
David Brazdil809658e2015-02-05 11:34:02 +0000142
David Brazdil69ba7b72015-06-23 18:27:30 +0100143class PassObserver : public ValueObject {
David Brazdil5e8b1372015-01-23 14:39:08 +0000144 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100145 PassObserver(HGraph* graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100146 CodeGenerator* codegen,
147 std::ostream* visualizer_output,
Andreas Gampea0d81af2016-10-27 12:04:57 -0700148 CompilerDriver* compiler_driver,
149 Mutex& dump_mutex)
David Brazdil69ba7b72015-06-23 18:27:30 +0100150 : graph_(graph),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000151 cached_method_name_(),
David Brazdil809658e2015-02-05 11:34:02 +0000152 timing_logger_enabled_(compiler_driver->GetDumpPasses()),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000153 timing_logger_(timing_logger_enabled_ ? GetMethodName() : "", true, true),
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100154 disasm_info_(graph->GetArena()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700155 visualizer_oss_(),
156 visualizer_output_(visualizer_output),
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000157 visualizer_enabled_(!compiler_driver->GetCompilerOptions().GetDumpCfgFileName().empty()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700158 visualizer_(&visualizer_oss_, graph, *codegen),
159 visualizer_dump_mutex_(dump_mutex),
David Brazdil69ba7b72015-06-23 18:27:30 +0100160 graph_in_bad_state_(false) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700161 if (timing_logger_enabled_ || visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000162 if (!IsVerboseMethod(compiler_driver, GetMethodName())) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700163 timing_logger_enabled_ = visualizer_enabled_ = false;
164 }
165 if (visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000166 visualizer_.PrintHeader(GetMethodName());
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700167 codegen->SetDisassemblyInformation(&disasm_info_);
168 }
David Brazdil62e074f2015-04-07 18:09:37 +0100169 }
David Brazdil5e8b1372015-01-23 14:39:08 +0000170 }
171
David Brazdil69ba7b72015-06-23 18:27:30 +0100172 ~PassObserver() {
David Brazdil5e8b1372015-01-23 14:39:08 +0000173 if (timing_logger_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000174 LOG(INFO) << "TIMINGS " << GetMethodName();
David Brazdil5e8b1372015-01-23 14:39:08 +0000175 LOG(INFO) << Dumpable<TimingLogger>(timing_logger_);
176 }
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000177 DCHECK(visualizer_oss_.str().empty());
David Brazdil5e8b1372015-01-23 14:39:08 +0000178 }
179
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000180 void DumpDisassembly() REQUIRES(!visualizer_dump_mutex_) {
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100181 if (visualizer_enabled_) {
182 visualizer_.DumpGraphWithDisassembly();
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000183 FlushVisualizer();
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100184 }
185 }
186
David Brazdil69ba7b72015-06-23 18:27:30 +0100187 void SetGraphInBadState() { graph_in_bad_state_ = true; }
188
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000189 const char* GetMethodName() {
190 // PrettyMethod() is expensive, so we delay calling it until we actually have to.
191 if (cached_method_name_.empty()) {
David Sehr709b0702016-10-13 09:12:37 -0700192 cached_method_name_ = graph_->GetDexFile().PrettyMethod(graph_->GetMethodIdx());
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000193 }
194 return cached_method_name_.c_str();
195 }
196
David Brazdil5e8b1372015-01-23 14:39:08 +0000197 private:
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000198 void StartPass(const char* pass_name) REQUIRES(!visualizer_dump_mutex_) {
Wojciech Staszkiewicze7060702016-08-16 17:31:19 -0700199 VLOG(compiler) << "Starting pass: " << pass_name;
David Brazdil809658e2015-02-05 11:34:02 +0000200 // Dump graph first, then start timer.
201 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100202 visualizer_.DumpGraph(pass_name, /* is_after_pass */ false, graph_in_bad_state_);
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000203 FlushVisualizer();
David Brazdil809658e2015-02-05 11:34:02 +0000204 }
205 if (timing_logger_enabled_) {
206 timing_logger_.StartTiming(pass_name);
207 }
208 }
209
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000210 void FlushVisualizer() REQUIRES(!visualizer_dump_mutex_) {
211 MutexLock mu(Thread::Current(), visualizer_dump_mutex_);
212 *visualizer_output_ << visualizer_oss_.str();
213 visualizer_output_->flush();
214 visualizer_oss_.str("");
215 visualizer_oss_.clear();
216 }
217
218 void EndPass(const char* pass_name) REQUIRES(!visualizer_dump_mutex_) {
David Brazdil809658e2015-02-05 11:34:02 +0000219 // Pause timer first, then dump graph.
220 if (timing_logger_enabled_) {
221 timing_logger_.EndTiming();
222 }
223 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100224 visualizer_.DumpGraph(pass_name, /* is_after_pass */ true, graph_in_bad_state_);
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000225 FlushVisualizer();
David Brazdil809658e2015-02-05 11:34:02 +0000226 }
David Brazdil69ba7b72015-06-23 18:27:30 +0100227
228 // Validate the HGraph if running in debug mode.
229 if (kIsDebugBuild) {
230 if (!graph_in_bad_state_) {
David Brazdilbadd8262016-02-02 16:28:56 +0000231 GraphChecker checker(graph_);
232 checker.Run();
233 if (!checker.IsValid()) {
234 LOG(FATAL) << "Error after " << pass_name << ": " << Dumpable<GraphChecker>(checker);
David Brazdil69ba7b72015-06-23 18:27:30 +0100235 }
236 }
237 }
David Brazdil809658e2015-02-05 11:34:02 +0000238 }
239
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700240 static bool IsVerboseMethod(CompilerDriver* compiler_driver, const char* method_name) {
241 // Test an exact match to --verbose-methods. If verbose-methods is set, this overrides an
242 // empty kStringFilter matching all methods.
243 if (compiler_driver->GetCompilerOptions().HasVerboseMethods()) {
244 return compiler_driver->GetCompilerOptions().IsVerboseMethod(method_name);
245 }
246
247 // Test the kStringFilter sub-string. constexpr helper variable to silence unreachable-code
248 // warning when the string is empty.
249 constexpr bool kStringFilterEmpty = arraysize(kStringFilter) <= 1;
250 if (kStringFilterEmpty || strstr(method_name, kStringFilter) != nullptr) {
251 return true;
252 }
253
254 return false;
255 }
256
David Brazdil69ba7b72015-06-23 18:27:30 +0100257 HGraph* const graph_;
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000258
259 std::string cached_method_name_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000260
261 bool timing_logger_enabled_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000262 TimingLogger timing_logger_;
263
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100264 DisassemblyInformation disasm_info_;
265
Andreas Gampea0d81af2016-10-27 12:04:57 -0700266 std::ostringstream visualizer_oss_;
267 std::ostream* visualizer_output_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000268 bool visualizer_enabled_;
269 HGraphVisualizer visualizer_;
Andreas Gampea0d81af2016-10-27 12:04:57 -0700270 Mutex& visualizer_dump_mutex_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000271
David Brazdil69ba7b72015-06-23 18:27:30 +0100272 // Flag to be set by the compiler if the pass failed and the graph is not
273 // expected to validate.
274 bool graph_in_bad_state_;
David Brazdil809658e2015-02-05 11:34:02 +0000275
David Brazdil69ba7b72015-06-23 18:27:30 +0100276 friend PassScope;
277
278 DISALLOW_COPY_AND_ASSIGN(PassObserver);
David Brazdil5e8b1372015-01-23 14:39:08 +0000279};
280
David Brazdil69ba7b72015-06-23 18:27:30 +0100281class PassScope : public ValueObject {
David Brazdil809658e2015-02-05 11:34:02 +0000282 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100283 PassScope(const char *pass_name, PassObserver* pass_observer)
David Brazdil809658e2015-02-05 11:34:02 +0000284 : pass_name_(pass_name),
David Brazdil69ba7b72015-06-23 18:27:30 +0100285 pass_observer_(pass_observer) {
286 pass_observer_->StartPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000287 }
288
David Brazdil69ba7b72015-06-23 18:27:30 +0100289 ~PassScope() {
290 pass_observer_->EndPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000291 }
292
293 private:
294 const char* const pass_name_;
David Brazdil69ba7b72015-06-23 18:27:30 +0100295 PassObserver* const pass_observer_;
David Brazdil809658e2015-02-05 11:34:02 +0000296};
297
Andreas Gampe53c913b2014-08-12 23:19:23 -0700298class OptimizingCompiler FINAL : public Compiler {
299 public:
300 explicit OptimizingCompiler(CompilerDriver* driver);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700301 ~OptimizingCompiler() OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700302
Vladimir Markodf739842016-03-23 16:59:07 +0000303 bool CanCompileMethod(uint32_t method_idx, const DexFile& dex_file) const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700304
305 CompiledMethod* Compile(const DexFile::CodeItem* code_item,
306 uint32_t access_flags,
307 InvokeType invoke_type,
308 uint16_t class_def_idx,
309 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000310 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700311 const DexFile& dex_file,
312 Handle<mirror::DexCache> dex_cache) const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700313
Andreas Gampe53c913b2014-08-12 23:19:23 -0700314 CompiledMethod* JniCompile(uint32_t access_flags,
315 uint32_t method_idx,
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700316 const DexFile& dex_file,
317 JniOptimizationFlags optimization_flags) const OVERRIDE {
318 return ArtQuickJniCompileMethod(GetCompilerDriver(),
319 access_flags,
320 method_idx,
321 dex_file,
322 optimization_flags);
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000323 }
Andreas Gampe53c913b2014-08-12 23:19:23 -0700324
Mathieu Chartiere401d142015-04-22 13:56:20 -0700325 uintptr_t GetEntryPointOf(ArtMethod* method) const OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700326 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000327 return reinterpret_cast<uintptr_t>(method->GetEntryPointFromQuickCompiledCodePtrSize(
328 InstructionSetPointerSize(GetCompilerDriver()->GetInstructionSet())));
329 }
Andreas Gampe53c913b2014-08-12 23:19:23 -0700330
David Brazdilee690a32014-12-01 17:04:16 +0000331 void Init() OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700332
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000333 void UnInit() const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700334
Calin Juravle2be39e02015-04-21 13:56:34 +0100335 void MaybeRecordStat(MethodCompilationStat compilation_stat) const {
336 if (compilation_stats_.get() != nullptr) {
337 compilation_stats_->RecordStat(compilation_stat);
338 }
339 }
340
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000341 bool JitCompile(Thread* self, jit::JitCodeCache* code_cache, ArtMethod* method, bool osr)
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000342 OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700343 REQUIRES_SHARED(Locks::mutator_lock_);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000344
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700345 private:
346 void RunOptimizations(HGraph* graph,
347 CodeGenerator* codegen,
348 CompilerDriver* driver,
349 const DexCompilationUnit& dex_compilation_unit,
350 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700351 VariableSizedHandleScope* handles) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700352
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700353 void RunOptimizations(HOptimization* optimizations[],
354 size_t length,
355 PassObserver* pass_observer) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700356
Andreas Gampe53c913b2014-08-12 23:19:23 -0700357 private:
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000358 // Create a 'CompiledMethod' for an optimized graph.
David Brazdil58282f42016-01-14 12:45:10 +0000359 CompiledMethod* Emit(ArenaAllocator* arena,
360 CodeVectorAllocator* code_allocator,
361 CodeGenerator* codegen,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000362 CompilerDriver* driver,
363 const DexFile::CodeItem* item) const;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000364
365 // Try compiling a method and return the code generator used for
366 // compiling it.
367 // This method:
368 // 1) Builds the graph. Returns null if it failed to build it.
David Brazdil58282f42016-01-14 12:45:10 +0000369 // 2) Transforms the graph to SSA. Returns null if it failed.
370 // 3) Runs optimizations on the graph, including register allocator.
371 // 4) Generates code with the `code_allocator` provided.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000372 CodeGenerator* TryCompile(ArenaAllocator* arena,
373 CodeVectorAllocator* code_allocator,
374 const DexFile::CodeItem* code_item,
375 uint32_t access_flags,
376 InvokeType invoke_type,
377 uint16_t class_def_idx,
378 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000379 Handle<mirror::ClassLoader> class_loader,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000380 const DexFile& dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000381 Handle<mirror::DexCache> dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000382 ArtMethod* method,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000383 bool osr,
384 VariableSizedHandleScope* handles) const;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000385
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700386 void MaybeRunInliner(HGraph* graph,
387 CodeGenerator* codegen,
388 CompilerDriver* driver,
389 const DexCompilationUnit& dex_compilation_unit,
390 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700391 VariableSizedHandleScope* handles) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700392
393 void RunArchOptimizations(InstructionSet instruction_set,
394 HGraph* graph,
395 CodeGenerator* codegen,
396 PassObserver* pass_observer) const;
397
Calin Juravle2be39e02015-04-21 13:56:34 +0100398 std::unique_ptr<OptimizingCompilerStats> compilation_stats_;
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100399
Andreas Gampe53c913b2014-08-12 23:19:23 -0700400 std::unique_ptr<std::ostream> visualizer_output_;
401
Andreas Gampea0d81af2016-10-27 12:04:57 -0700402 mutable Mutex dump_mutex_; // To synchronize visualizer writing.
403
Andreas Gampe53c913b2014-08-12 23:19:23 -0700404 DISALLOW_COPY_AND_ASSIGN(OptimizingCompiler);
405};
406
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100407static const int kMaximumCompilationTimeBeforeWarning = 100; /* ms */
408
409OptimizingCompiler::OptimizingCompiler(CompilerDriver* driver)
Andreas Gampea0d81af2016-10-27 12:04:57 -0700410 : Compiler(driver, kMaximumCompilationTimeBeforeWarning),
411 dump_mutex_("Visualizer dump lock") {}
David Brazdilee690a32014-12-01 17:04:16 +0000412
413void OptimizingCompiler::Init() {
414 // Enable C1visualizer output. Must be done in Init() because the compiler
415 // driver is not fully initialized when passed to the compiler's constructor.
416 CompilerDriver* driver = GetCompilerDriver();
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000417 const std::string cfg_file_name = driver->GetCompilerOptions().GetDumpCfgFileName();
David Brazdil866c0312015-01-13 21:21:31 +0000418 if (!cfg_file_name.empty()) {
Calin Juravle87000a92015-08-24 15:34:44 +0100419 std::ios_base::openmode cfg_file_mode =
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000420 driver->GetCompilerOptions().GetDumpCfgAppend() ? std::ofstream::app : std::ofstream::out;
Calin Juravle87000a92015-08-24 15:34:44 +0100421 visualizer_output_.reset(new std::ofstream(cfg_file_name, cfg_file_mode));
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100422 }
Calin Juravle2be39e02015-04-21 13:56:34 +0100423 if (driver->GetDumpStats()) {
424 compilation_stats_.reset(new OptimizingCompilerStats());
425 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100426}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000427
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000428void OptimizingCompiler::UnInit() const {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000429}
430
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100431OptimizingCompiler::~OptimizingCompiler() {
Calin Juravle2be39e02015-04-21 13:56:34 +0100432 if (compilation_stats_.get() != nullptr) {
433 compilation_stats_->Log();
434 }
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100435}
436
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000437bool OptimizingCompiler::CanCompileMethod(uint32_t method_idx ATTRIBUTE_UNUSED,
Vladimir Markodf739842016-03-23 16:59:07 +0000438 const DexFile& dex_file ATTRIBUTE_UNUSED) const {
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000439 return true;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700440}
441
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000442static bool IsInstructionSetSupported(InstructionSet instruction_set) {
Calin Juravlecff8cc72015-10-09 12:03:24 +0100443 return (instruction_set == kArm && !kArm32QuickCodeUseSoftFloat)
444 || instruction_set == kArm64
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000445 || (instruction_set == kThumb2 && !kArm32QuickCodeUseSoftFloat)
Goran Jakovljevicf652cec2015-08-25 16:11:42 +0200446 || instruction_set == kMips
Alexey Frunze4dda3372015-06-01 18:31:49 -0700447 || instruction_set == kMips64
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000448 || instruction_set == kX86
449 || instruction_set == kX86_64;
450}
451
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700452// Strip pass name suffix to get optimization name.
453static std::string ConvertPassNameToOptimizationName(const std::string& pass_name) {
454 size_t pos = pass_name.find(kPassNameSeparator);
455 return pos == std::string::npos ? pass_name : pass_name.substr(0, pos);
456}
457
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700458static HOptimization* BuildOptimization(
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700459 const std::string& pass_name,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700460 ArenaAllocator* arena,
461 HGraph* graph,
462 OptimizingCompilerStats* stats,
463 CodeGenerator* codegen,
464 CompilerDriver* driver,
465 const DexCompilationUnit& dex_compilation_unit,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700466 VariableSizedHandleScope* handles,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700467 SideEffectsAnalysis* most_recent_side_effects,
468 HInductionVarAnalysis* most_recent_induction) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700469 std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700470 if (opt_name == BoundsCheckElimination::kBoundsCheckEliminationPassName) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700471 CHECK(most_recent_side_effects != nullptr && most_recent_induction != nullptr);
472 return new (arena) BoundsCheckElimination(graph,
473 *most_recent_side_effects,
474 most_recent_induction);
475 } else if (opt_name == GVNOptimization::kGlobalValueNumberingPassName) {
476 CHECK(most_recent_side_effects != nullptr);
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700477 return new (arena) GVNOptimization(graph, *most_recent_side_effects, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700478 } else if (opt_name == HConstantFolding::kConstantFoldingPassName) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700479 return new (arena) HConstantFolding(graph, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700480 } else if (opt_name == HDeadCodeElimination::kDeadCodeEliminationPassName) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700481 return new (arena) HDeadCodeElimination(graph, stats, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700482 } else if (opt_name == HInliner::kInlinerPassName) {
483 size_t number_of_dex_registers = dex_compilation_unit.GetCodeItem()->registers_size_;
484 return new (arena) HInliner(graph, // outer_graph
485 graph, // outermost_graph
486 codegen,
487 dex_compilation_unit, // outer_compilation_unit
488 dex_compilation_unit, // outermost_compilation_unit
489 driver,
490 handles,
491 stats,
492 number_of_dex_registers,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000493 /* total_number_of_instructions */ 0,
494 /* parent */ nullptr);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700495 } else if (opt_name == HSharpening::kSharpeningPassName) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000496 return new (arena) HSharpening(graph, codegen, dex_compilation_unit, driver, handles);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700497 } else if (opt_name == HSelectGenerator::kSelectGeneratorPassName) {
498 return new (arena) HSelectGenerator(graph, stats);
499 } else if (opt_name == HInductionVarAnalysis::kInductionPassName) {
500 return new (arena) HInductionVarAnalysis(graph);
501 } else if (opt_name == InstructionSimplifier::kInstructionSimplifierPassName) {
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000502 return new (arena) InstructionSimplifier(graph, codegen, stats, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700503 } else if (opt_name == IntrinsicsRecognizer::kIntrinsicsRecognizerPassName) {
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100504 return new (arena) IntrinsicsRecognizer(graph, stats);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700505 } else if (opt_name == LICM::kLoopInvariantCodeMotionPassName) {
506 CHECK(most_recent_side_effects != nullptr);
507 return new (arena) LICM(graph, *most_recent_side_effects, stats);
508 } else if (opt_name == LoadStoreElimination::kLoadStoreEliminationPassName) {
509 CHECK(most_recent_side_effects != nullptr);
510 return new (arena) LoadStoreElimination(graph, *most_recent_side_effects);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700511 } else if (opt_name == SideEffectsAnalysis::kSideEffectsAnalysisPassName) {
512 return new (arena) SideEffectsAnalysis(graph);
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100513 } else if (opt_name == HLoopOptimization::kLoopOptimizationPassName) {
Aart Bik92685a82017-03-06 11:13:43 -0800514 return new (arena) HLoopOptimization(graph, driver, most_recent_induction);
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800515 } else if (opt_name == CHAGuardOptimization::kCHAGuardOptimizationPassName) {
516 return new (arena) CHAGuardOptimization(graph);
Nicolas Geoffrayb813ca12017-02-16 22:08:29 +0000517 } else if (opt_name == CodeSinking::kCodeSinkingPassName) {
518 return new (arena) CodeSinking(graph, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700519#ifdef ART_ENABLE_CODEGEN_arm
520 } else if (opt_name == arm::DexCacheArrayFixups::kDexCacheArrayFixupsArmPassName) {
Vladimir Marko68c981f2016-08-26 13:13:33 +0100521 return new (arena) arm::DexCacheArrayFixups(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700522 } else if (opt_name == arm::InstructionSimplifierArm::kInstructionSimplifierArmPassName) {
523 return new (arena) arm::InstructionSimplifierArm(graph, stats);
524#endif
525#ifdef ART_ENABLE_CODEGEN_arm64
526 } else if (opt_name == arm64::InstructionSimplifierArm64::kInstructionSimplifierArm64PassName) {
527 return new (arena) arm64::InstructionSimplifierArm64(graph, stats);
528#endif
529#ifdef ART_ENABLE_CODEGEN_mips
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700530 } else if (opt_name == mips::DexCacheArrayFixups::kDexCacheArrayFixupsMipsPassName) {
531 return new (arena) mips::DexCacheArrayFixups(graph, codegen, stats);
532 } else if (opt_name == mips::PcRelativeFixups::kPcRelativeFixupsMipsPassName) {
533 return new (arena) mips::PcRelativeFixups(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700534#endif
535#ifdef ART_ENABLE_CODEGEN_x86
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700536 } else if (opt_name == x86::PcRelativeFixups::kPcRelativeFixupsX86PassName) {
537 return new (arena) x86::PcRelativeFixups(graph, codegen, stats);
538 } else if (opt_name == x86::X86MemoryOperandGeneration::kX86MemoryOperandGenerationPassName) {
539 return new (arena) x86::X86MemoryOperandGeneration(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700540#endif
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700541 }
542 return nullptr;
543}
544
545static ArenaVector<HOptimization*> BuildOptimizations(
546 const std::vector<std::string>& pass_names,
547 ArenaAllocator* arena,
548 HGraph* graph,
549 OptimizingCompilerStats* stats,
550 CodeGenerator* codegen,
551 CompilerDriver* driver,
552 const DexCompilationUnit& dex_compilation_unit,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700553 VariableSizedHandleScope* handles) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700554 // Few HOptimizations constructors require SideEffectsAnalysis or HInductionVarAnalysis
555 // instances. This method assumes that each of them expects the nearest instance preceeding it
556 // in the pass name list.
557 SideEffectsAnalysis* most_recent_side_effects = nullptr;
558 HInductionVarAnalysis* most_recent_induction = nullptr;
559 ArenaVector<HOptimization*> ret(arena->Adapter());
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700560 for (const std::string& pass_name : pass_names) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700561 HOptimization* opt = BuildOptimization(
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700562 pass_name,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700563 arena,
564 graph,
565 stats,
566 codegen,
567 driver,
568 dex_compilation_unit,
569 handles,
570 most_recent_side_effects,
571 most_recent_induction);
572 CHECK(opt != nullptr) << "Couldn't build optimization: \"" << pass_name << "\"";
573 ret.push_back(opt);
574
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700575 std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700576 if (opt_name == SideEffectsAnalysis::kSideEffectsAnalysisPassName) {
577 most_recent_side_effects = down_cast<SideEffectsAnalysis*>(opt);
578 } else if (opt_name == HInductionVarAnalysis::kInductionPassName) {
579 most_recent_induction = down_cast<HInductionVarAnalysis*>(opt);
580 }
581 }
582 return ret;
583}
584
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700585void OptimizingCompiler::RunOptimizations(HOptimization* optimizations[],
586 size_t length,
587 PassObserver* pass_observer) const {
Calin Juravle10e244f2015-01-26 18:54:32 +0000588 for (size_t i = 0; i < length; ++i) {
David Brazdil69ba7b72015-06-23 18:27:30 +0100589 PassScope scope(optimizations[i]->GetPassName(), pass_observer);
590 optimizations[i]->Run();
Calin Juravle10e244f2015-01-26 18:54:32 +0000591 }
592}
593
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700594void OptimizingCompiler::MaybeRunInliner(HGraph* graph,
595 CodeGenerator* codegen,
596 CompilerDriver* driver,
597 const DexCompilationUnit& dex_compilation_unit,
598 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700599 VariableSizedHandleScope* handles) const {
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700600 OptimizingCompilerStats* stats = compilation_stats_.get();
Calin Juravleec748352015-07-29 13:52:12 +0100601 const CompilerOptions& compiler_options = driver->GetCompilerOptions();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000602 bool should_inline = (compiler_options.GetInlineMaxCodeUnits() > 0);
Calin Juravleec748352015-07-29 13:52:12 +0100603 if (!should_inline) {
604 return;
605 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000606 size_t number_of_dex_registers = dex_compilation_unit.GetCodeItem()->registers_size_;
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000607 HInliner* inliner = new (graph->GetArena()) HInliner(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700608 graph, // outer_graph
609 graph, // outermost_graph
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000610 codegen,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700611 dex_compilation_unit, // outer_compilation_unit
612 dex_compilation_unit, // outermost_compilation_unit
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000613 driver,
614 handles,
615 stats,
616 number_of_dex_registers,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000617 /* total_number_of_instructions */ 0,
618 /* parent */ nullptr);
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000619 HOptimization* optimizations[] = { inliner };
Calin Juravleec748352015-07-29 13:52:12 +0100620
621 RunOptimizations(optimizations, arraysize(optimizations), pass_observer);
622}
623
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700624void OptimizingCompiler::RunArchOptimizations(InstructionSet instruction_set,
625 HGraph* graph,
626 CodeGenerator* codegen,
627 PassObserver* pass_observer) const {
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700628 UNUSED(codegen); // To avoid compilation error when compiling for svelte
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700629 OptimizingCompilerStats* stats = compilation_stats_.get();
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100630 ArenaAllocator* arena = graph->GetArena();
631 switch (instruction_set) {
Artem Serov2bbc9532016-10-21 11:51:50 +0100632#if defined(ART_ENABLE_CODEGEN_arm)
Vladimir Markob4536b72015-11-24 13:45:23 +0000633 case kThumb2:
634 case kArm: {
Vladimir Marko68c981f2016-08-26 13:13:33 +0100635 arm::DexCacheArrayFixups* fixups =
636 new (arena) arm::DexCacheArrayFixups(graph, codegen, stats);
Artem Udovichenko4a0dad62016-01-26 12:28:31 +0300637 arm::InstructionSimplifierArm* simplifier =
638 new (arena) arm::InstructionSimplifierArm(graph, stats);
Artem Serov328429f2016-07-06 16:23:04 +0100639 SideEffectsAnalysis* side_effects = new (arena) SideEffectsAnalysis(graph);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700640 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects, "GVN$after_arch");
Vladimir Markob4536b72015-11-24 13:45:23 +0000641 HOptimization* arm_optimizations[] = {
Artem Udovichenko4a0dad62016-01-26 12:28:31 +0300642 simplifier,
Artem Serov328429f2016-07-06 16:23:04 +0100643 side_effects,
644 gvn,
Nicolas Geoffray6b5afdd2016-01-22 09:31:52 +0000645 fixups
Vladimir Markob4536b72015-11-24 13:45:23 +0000646 };
647 RunOptimizations(arm_optimizations, arraysize(arm_optimizations), pass_observer);
648 break;
649 }
650#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100651#ifdef ART_ENABLE_CODEGEN_arm64
652 case kArm64: {
653 arm64::InstructionSimplifierArm64* simplifier =
654 new (arena) arm64::InstructionSimplifierArm64(graph, stats);
655 SideEffectsAnalysis* side_effects = new (arena) SideEffectsAnalysis(graph);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700656 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects, "GVN$after_arch");
Alexandre Rames22aa54b2016-10-18 09:32:29 +0100657 HInstructionScheduling* scheduling =
658 new (arena) HInstructionScheduling(graph, instruction_set);
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100659 HOptimization* arm64_optimizations[] = {
660 simplifier,
661 side_effects,
Alexandre Rames22aa54b2016-10-18 09:32:29 +0100662 gvn,
663 scheduling,
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100664 };
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");
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000763 InstructionSimplifier* simplify1 = new (arena) InstructionSimplifier(graph, codegen, 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");
Aart Bik92685a82017-03-06 11:13:43 -0800768 SideEffectsAnalysis* side_effects1 = new (arena) SideEffectsAnalysis(
769 graph, "side_effects$before_gvn");
770 SideEffectsAnalysis* side_effects2 = new (arena) SideEffectsAnalysis(
771 graph, "side_effects$before_lse");
772 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects1);
773 LICM* licm = new (arena) LICM(graph, *side_effects1, stats);
Aart Bik22af3be2015-09-10 12:50:58 -0700774 HInductionVarAnalysis* induction = new (arena) HInductionVarAnalysis(graph);
Aart Bik92685a82017-03-06 11:13:43 -0800775 BoundsCheckElimination* bce = new (arena) BoundsCheckElimination(graph, *side_effects1, induction);
776 HLoopOptimization* loop = new (arena) HLoopOptimization(graph, driver, induction);
777 LoadStoreElimination* lse = new (arena) LoadStoreElimination(graph, *side_effects2);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000778 HSharpening* sharpening = new (arena) HSharpening(
779 graph, codegen, dex_compilation_unit, driver, handles);
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100780 InstructionSimplifier* simplify2 = new (arena) InstructionSimplifier(
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000781 graph, codegen, stats, "instruction_simplifier$after_inlining");
David Brazdil4833f5a2015-12-16 10:37:39 +0000782 InstructionSimplifier* simplify3 = new (arena) InstructionSimplifier(
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000783 graph, codegen, stats, "instruction_simplifier$after_bce");
Aart Bik639cc8c2016-10-18 13:03:31 -0700784 InstructionSimplifier* simplify4 = new (arena) InstructionSimplifier(
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000785 graph, codegen, stats, "instruction_simplifier$before_codegen");
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100786 IntrinsicsRecognizer* intrinsics = new (arena) IntrinsicsRecognizer(graph, stats);
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800787 CHAGuardOptimization* cha_guard = new (arena) CHAGuardOptimization(graph);
Nicolas Geoffrayb813ca12017-02-16 22:08:29 +0000788 CodeSinking* code_sinking = new (arena) CodeSinking(graph, stats);
Andreas Gampe71fb52f2014-12-29 17:43:08 -0800789
Calin Juravleec748352015-07-29 13:52:12 +0100790 HOptimization* optimizations1[] = {
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100791 intrinsics,
David Brazdil4833f5a2015-12-16 10:37:39 +0000792 sharpening,
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100793 fold1,
794 simplify1,
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100795 dce1,
Calin Juravleec748352015-07-29 13:52:12 +0100796 };
Calin Juravleec748352015-07-29 13:52:12 +0100797 RunOptimizations(optimizations1, arraysize(optimizations1), pass_observer);
798
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700799 MaybeRunInliner(graph, codegen, driver, dex_compilation_unit, pass_observer, handles);
David Brazdil95177982015-10-30 12:56:58 -0500800
David Brazdil8993caf2015-12-07 10:04:40 +0000801 HOptimization* optimizations2[] = {
David Brazdil74eb1b22015-12-14 11:44:01 +0000802 // SelectGenerator depends on the InstructionSimplifier removing
David Brazdil8993caf2015-12-07 10:04:40 +0000803 // redundant suspend checks to recognize empty blocks.
David Brazdil74eb1b22015-12-14 11:44:01 +0000804 select_generator,
David Brazdil8993caf2015-12-07 10:04:40 +0000805 fold2, // TODO: if we don't inline we can also skip fold2.
Aart Bik639cc8c2016-10-18 13:03:31 -0700806 simplify2,
Aart Bik2767f4b2016-10-28 15:03:53 -0700807 dce2,
Aart Bik92685a82017-03-06 11:13:43 -0800808 side_effects1,
David Brazdil8993caf2015-12-07 10:04:40 +0000809 gvn,
810 licm,
811 induction,
812 bce,
Aart Bik281c6812016-08-26 11:31:48 -0700813 loop,
David Brazdil8993caf2015-12-07 10:04:40 +0000814 fold3, // evaluates code generated by dynamic bce
Aart Bik639cc8c2016-10-18 13:03:31 -0700815 simplify3,
Aart Bik92685a82017-03-06 11:13:43 -0800816 side_effects2,
David Brazdil8993caf2015-12-07 10:04:40 +0000817 lse,
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800818 cha_guard,
Aart Bik2767f4b2016-10-28 15:03:53 -0700819 dce3,
Nicolas Geoffrayb813ca12017-02-16 22:08:29 +0000820 code_sinking,
David Brazdil8993caf2015-12-07 10:04:40 +0000821 // The codegen has a few assumptions that only the instruction simplifier
822 // can satisfy. For example, the code generator does not expect to see a
823 // HTypeConversion from a type to the same type.
Aart Bik639cc8c2016-10-18 13:03:31 -0700824 simplify4,
David Brazdil8993caf2015-12-07 10:04:40 +0000825 };
826 RunOptimizations(optimizations2, arraysize(optimizations2), pass_observer);
David Brazdilbbd733e2015-08-18 17:48:17 +0100827
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700828 RunArchOptimizations(driver->GetInstructionSet(), graph, codegen, pass_observer);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000829}
830
Vladimir Marko58155012015-08-19 12:49:41 +0000831static ArenaVector<LinkerPatch> EmitAndSortLinkerPatches(CodeGenerator* codegen) {
832 ArenaVector<LinkerPatch> linker_patches(codegen->GetGraph()->GetArena()->Adapter());
833 codegen->EmitLinkerPatches(&linker_patches);
834
835 // Sort patches by literal offset. Required for .oat_patches encoding.
836 std::sort(linker_patches.begin(), linker_patches.end(),
837 [](const LinkerPatch& lhs, const LinkerPatch& rhs) {
838 return lhs.LiteralOffset() < rhs.LiteralOffset();
839 });
840
841 return linker_patches;
842}
843
David Brazdil58282f42016-01-14 12:45:10 +0000844CompiledMethod* OptimizingCompiler::Emit(ArenaAllocator* arena,
845 CodeVectorAllocator* code_allocator,
846 CodeGenerator* codegen,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000847 CompilerDriver* compiler_driver,
848 const DexFile::CodeItem* code_item) const {
Vladimir Marko58155012015-08-19 12:49:41 +0000849 ArenaVector<LinkerPatch> linker_patches = EmitAndSortLinkerPatches(codegen);
Vladimir Markof9f64412015-09-02 14:05:49 +0100850 ArenaVector<uint8_t> stack_map(arena->Adapter(kArenaAllocStackMaps));
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700851 ArenaVector<uint8_t> method_info(arena->Adapter(kArenaAllocStackMaps));
852 size_t stack_map_size = 0;
853 size_t method_info_size = 0;
854 codegen->ComputeStackMapAndMethodInfoSize(&stack_map_size, &method_info_size);
855 stack_map.resize(stack_map_size);
856 method_info.resize(method_info_size);
857 codegen->BuildStackMaps(MemoryRegion(stack_map.data(), stack_map.size()),
858 MemoryRegion(method_info.data(), method_info.size()),
859 *code_item);
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000860
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100861 CompiledMethod* compiled_method = CompiledMethod::SwapAllocCompiledMethod(
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000862 compiler_driver,
863 codegen->GetInstructionSet(),
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000864 ArrayRef<const uint8_t>(code_allocator->GetMemory()),
Roland Levillainaa9b7c42015-02-17 15:40:09 +0000865 // Follow Quick's behavior and set the frame size to zero if it is
866 // considered "empty" (see the definition of
867 // art::CodeGenerator::HasEmptyFrame).
868 codegen->HasEmptyFrame() ? 0 : codegen->GetFrameSize(),
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000869 codegen->GetCoreSpillMask(),
Nicolas Geoffrayd97dc402015-01-22 13:50:01 +0000870 codegen->GetFpuSpillMask(),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700871 ArrayRef<const uint8_t>(method_info),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100872 ArrayRef<const uint8_t>(stack_map),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100873 ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data()),
Vladimir Marko58155012015-08-19 12:49:41 +0000874 ArrayRef<const LinkerPatch>(linker_patches));
Mathieu Chartiered150002015-08-28 11:16:54 -0700875
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100876 return compiled_method;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000877}
878
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000879CodeGenerator* OptimizingCompiler::TryCompile(ArenaAllocator* arena,
880 CodeVectorAllocator* code_allocator,
881 const DexFile::CodeItem* code_item,
882 uint32_t access_flags,
883 InvokeType invoke_type,
884 uint16_t class_def_idx,
885 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000886 Handle<mirror::ClassLoader> class_loader,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000887 const DexFile& dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000888 Handle<mirror::DexCache> dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000889 ArtMethod* method,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000890 bool osr,
891 VariableSizedHandleScope* handles) const {
Calin Juravle2be39e02015-04-21 13:56:34 +0100892 MaybeRecordStat(MethodCompilationStat::kAttemptCompilation);
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000893 CompilerDriver* compiler_driver = GetCompilerDriver();
894 InstructionSet instruction_set = compiler_driver->GetInstructionSet();
Calin Juravlecff8cc72015-10-09 12:03:24 +0100895
Roland Levillain3b359c72015-11-17 19:35:12 +0000896 // Always use the Thumb-2 assembler: some runtime functionality
897 // (like implicit stack overflow checks) assume Thumb-2.
Artem Serovba6b6792016-08-15 14:22:07 +0100898 DCHECK_NE(instruction_set, kArm);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100899
900 // Do not attempt to compile on architectures we do not support.
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000901 if (!IsInstructionSetSupported(instruction_set)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100902 MaybeRecordStat(MethodCompilationStat::kNotCompiledUnsupportedIsa);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100903 return nullptr;
904 }
905
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000906 if (Compiler::IsPathologicalCase(*code_item, method_idx, dex_file)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100907 MaybeRecordStat(MethodCompilationStat::kNotCompiledPathological);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000908 return nullptr;
909 }
910
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000911 // Implementation of the space filter: do not compile a code item whose size in
Nicolas Geoffray432bf3d2015-07-17 11:11:09 +0100912 // code units is bigger than 128.
913 static constexpr size_t kSpaceFilterOptimizingThreshold = 128;
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000914 const CompilerOptions& compiler_options = compiler_driver->GetCompilerOptions();
Andreas Gampe29d38e72016-03-23 15:31:51 +0000915 if ((compiler_options.GetCompilerFilter() == CompilerFilter::kSpace)
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000916 && (code_item->insns_size_in_code_units_ > kSpaceFilterOptimizingThreshold)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100917 MaybeRecordStat(MethodCompilationStat::kNotCompiledSpaceFilter);
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000918 return nullptr;
919 }
920
Vladimir Marko97d7e1c2016-10-04 14:44:28 +0100921 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000922 DexCompilationUnit dex_compilation_unit(
Vladimir Markodf739842016-03-23 16:59:07 +0000923 class_loader,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +0100924 class_linker,
Vladimir Markodf739842016-03-23 16:59:07 +0000925 dex_file,
926 code_item,
927 class_def_idx,
928 method_idx,
929 access_flags,
930 /* verified_method */ nullptr,
931 dex_cache);
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000932
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000933 HGraph* graph = new (arena) HGraph(
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000934 arena,
935 dex_file,
936 method_idx,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000937 compiler_driver->GetInstructionSet(),
938 kInvalidInvokeType,
939 compiler_driver->GetCompilerOptions().GetDebuggable(),
940 osr);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000941
David Brazdilbadd8262016-02-02 16:28:56 +0000942 const uint8_t* interpreter_metadata = nullptr;
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000943 if (method == nullptr) {
David Brazdilbadd8262016-02-02 16:28:56 +0000944 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000945 method = compiler_driver->ResolveMethod(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000946 soa, dex_cache, class_loader, &dex_compilation_unit, method_idx, invoke_type);
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000947 }
948 // For AOT compilation, we may not get a method, for example if its class is erroneous.
949 // JIT should always have a method.
950 DCHECK(Runtime::Current()->IsAotCompiler() || method != nullptr);
951 if (method != nullptr) {
952 graph->SetArtMethod(method);
953 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +0100954 interpreter_metadata = method->GetQuickenedInfo(class_linker->GetImagePointerSize());
David Brazdilbadd8262016-02-02 16:28:56 +0000955 }
956
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000957 std::unique_ptr<CodeGenerator> codegen(
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000958 CodeGenerator::Create(graph,
959 instruction_set,
960 *compiler_driver->GetInstructionSetFeatures(),
Calin Juravle2ae48182016-03-16 14:05:09 +0000961 compiler_driver->GetCompilerOptions(),
962 compilation_stats_.get()));
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000963 if (codegen.get() == nullptr) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100964 MaybeRecordStat(MethodCompilationStat::kNotCompiledNoCodegen);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000965 return nullptr;
966 }
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100967 codegen->GetAssembler()->cfi().SetEnabled(
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000968 compiler_driver->GetCompilerOptions().GenerateAnyDebugInfo());
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000969
David Brazdil69ba7b72015-06-23 18:27:30 +0100970 PassObserver pass_observer(graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100971 codegen.get(),
972 visualizer_output_.get(),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700973 compiler_driver,
974 dump_mutex_);
David Brazdil5e8b1372015-01-23 14:39:08 +0000975
David Brazdil809658e2015-02-05 11:34:02 +0000976 {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000977 VLOG(compiler) << "Building " << pass_observer.GetMethodName();
978 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
979 HGraphBuilder builder(graph,
980 &dex_compilation_unit,
981 &dex_compilation_unit,
982 &dex_file,
983 *code_item,
984 compiler_driver,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000985 codegen.get(),
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000986 compilation_stats_.get(),
987 interpreter_metadata,
988 dex_cache,
989 handles);
990 GraphAnalysisResult result = builder.BuildGraph();
991 if (result != kAnalysisSuccess) {
992 switch (result) {
993 case kAnalysisSkipped:
994 MaybeRecordStat(MethodCompilationStat::kNotCompiledSkipped);
995 break;
996 case kAnalysisInvalidBytecode:
997 MaybeRecordStat(MethodCompilationStat::kNotCompiledInvalidBytecode);
998 break;
999 case kAnalysisFailThrowCatchLoop:
1000 MaybeRecordStat(MethodCompilationStat::kNotCompiledThrowCatchLoop);
1001 break;
1002 case kAnalysisFailAmbiguousArrayOp:
1003 MaybeRecordStat(MethodCompilationStat::kNotCompiledAmbiguousArrayOp);
1004 break;
1005 case kAnalysisSuccess:
1006 UNREACHABLE();
David Brazdil809658e2015-02-05 11:34:02 +00001007 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001008 pass_observer.SetGraphInBadState();
1009 return nullptr;
Nicolas Geoffrayf5370122014-12-02 11:51:19 +00001010 }
David Brazdilbadd8262016-02-02 16:28:56 +00001011 }
Vladimir Markof9f64412015-09-02 14:05:49 +01001012
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001013 RunOptimizations(graph,
1014 codegen.get(),
1015 compiler_driver,
1016 dex_compilation_unit,
1017 &pass_observer,
1018 handles);
1019
1020 RegisterAllocator::Strategy regalloc_strategy =
1021 compiler_options.GetRegisterAllocationStrategy();
1022 AllocateRegisters(graph, codegen.get(), &pass_observer, regalloc_strategy);
1023
1024 codegen->Compile(code_allocator);
1025 pass_observer.DumpDisassembly();
1026
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001027 return codegen.release();
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001028}
1029
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001030CompiledMethod* OptimizingCompiler::Compile(const DexFile::CodeItem* code_item,
1031 uint32_t access_flags,
1032 InvokeType invoke_type,
1033 uint16_t class_def_idx,
1034 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001035 Handle<mirror::ClassLoader> jclass_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -07001036 const DexFile& dex_file,
1037 Handle<mirror::DexCache> dex_cache) const {
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001038 CompilerDriver* compiler_driver = GetCompilerDriver();
1039 CompiledMethod* method = nullptr;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001040 DCHECK(Runtime::Current()->IsAotCompiler());
1041 const VerifiedMethod* verified_method = compiler_driver->GetVerifiedMethod(&dex_file, method_idx);
1042 DCHECK(!verified_method->HasRuntimeThrow());
1043 if (compiler_driver->IsMethodVerifiedWithoutFailures(method_idx, class_def_idx, dex_file)
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001044 || verifier::CanCompilerHandleVerificationFailure(
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001045 verified_method->GetEncounteredVerificationFailures())) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001046 ArenaAllocator arena(Runtime::Current()->GetArenaPool());
1047 CodeVectorAllocator code_allocator(&arena);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001048 std::unique_ptr<CodeGenerator> codegen;
1049 {
1050 ScopedObjectAccess soa(Thread::Current());
1051 VariableSizedHandleScope handles(soa.Self());
1052 // Go to native so that we don't block GC during compilation.
1053 ScopedThreadSuspension sts(soa.Self(), kNative);
1054 codegen.reset(
1055 TryCompile(&arena,
1056 &code_allocator,
1057 code_item,
1058 access_flags,
1059 invoke_type,
1060 class_def_idx,
1061 method_idx,
1062 jclass_loader,
1063 dex_file,
1064 dex_cache,
1065 nullptr,
1066 /* osr */ false,
1067 &handles));
1068 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001069 if (codegen.get() != nullptr) {
Calin Juravlead543382015-11-19 17:26:29 +00001070 MaybeRecordStat(MethodCompilationStat::kCompiled);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001071 method = Emit(&arena, &code_allocator, codegen.get(), compiler_driver, code_item);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001072
1073 if (kArenaAllocatorCountAllocations) {
1074 if (arena.BytesAllocated() > kArenaAllocatorMemoryReportThreshold) {
1075 MemStats mem_stats(arena.GetMemStats());
David Sehr709b0702016-10-13 09:12:37 -07001076 LOG(INFO) << dex_file.PrettyMethod(method_idx) << " " << Dumpable<MemStats>(mem_stats);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001077 }
1078 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001079 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001080 } else {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001081 if (compiler_driver->GetCompilerOptions().VerifyAtRuntime()) {
1082 MaybeRecordStat(MethodCompilationStat::kNotCompiledVerifyAtRuntime);
1083 } else {
Calin Juravlead543382015-11-19 17:26:29 +00001084 MaybeRecordStat(MethodCompilationStat::kNotCompiledVerificationError);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001085 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001086 }
1087
Calin Juravlecff8cc72015-10-09 12:03:24 +01001088 if (kIsDebugBuild &&
1089 IsCompilingWithCoreImage() &&
Goran Jakovljevic9c4f0d8f2017-04-05 16:27:25 +02001090 IsInstructionSetSupported(compiler_driver->GetInstructionSet())) {
Roland Levillain0d5a2812015-11-13 10:07:31 +00001091 // For testing purposes, we put a special marker on method names
Goran Jakovljevic9c4f0d8f2017-04-05 16:27:25 +02001092 // that should be compiled with this compiler (when the
1093 // instruction set is supported). This makes sure we're not
Roland Levillain0d5a2812015-11-13 10:07:31 +00001094 // regressing.
David Sehr709b0702016-10-13 09:12:37 -07001095 std::string method_name = dex_file.PrettyMethod(method_idx);
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001096 bool shouldCompile = method_name.find("$opt$") != std::string::npos;
1097 DCHECK((method != nullptr) || !shouldCompile) << "Didn't compile " << method_name;
1098 }
1099
Nicolas Geoffray12be74e2015-03-30 13:29:08 +01001100 return method;
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001101}
1102
Andreas Gampe53c913b2014-08-12 23:19:23 -07001103Compiler* CreateOptimizingCompiler(CompilerDriver* driver) {
1104 return new OptimizingCompiler(driver);
1105}
1106
Nicolas Geoffray335005e2015-06-25 10:01:47 +01001107bool IsCompilingWithCoreImage() {
1108 const std::string& image = Runtime::Current()->GetImageLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001109 // TODO: This is under-approximating...
Andreas Gampe9186ced2016-12-12 14:28:21 -08001110 if (android::base::EndsWith(image, "core.art") ||
1111 android::base::EndsWith(image, "core-optimizing.art")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001112 return true;
1113 }
1114 return false;
Nicolas Geoffray335005e2015-06-25 10:01:47 +01001115}
1116
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001117bool EncodeArtMethodInInlineInfo(ArtMethod* method ATTRIBUTE_UNUSED) {
1118 // Note: the runtime is null only for unit testing.
1119 return Runtime::Current() == nullptr || !Runtime::Current()->IsAotCompiler();
1120}
1121
1122bool CanEncodeInlinedMethodInStackMap(const DexFile& caller_dex_file, ArtMethod* callee) {
1123 if (!Runtime::Current()->IsAotCompiler()) {
1124 // JIT can always encode methods in stack maps.
1125 return true;
1126 }
1127 if (IsSameDexFile(caller_dex_file, *callee->GetDexFile())) {
1128 return true;
1129 }
1130 // TODO(ngeoffray): Support more AOT cases for inlining:
1131 // - methods in multidex
1132 // - methods in boot image for on-device non-PIC compilation.
1133 return false;
1134}
1135
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001136bool OptimizingCompiler::JitCompile(Thread* self,
1137 jit::JitCodeCache* code_cache,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001138 ArtMethod* method,
1139 bool osr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001140 StackHandleScope<3> hs(self);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001141 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1142 method->GetDeclaringClass()->GetClassLoader()));
1143 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001144 DCHECK(method->IsCompilable());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001145
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001146 const DexFile* dex_file = method->GetDexFile();
1147 const uint16_t class_def_idx = method->GetClassDefIndex();
1148 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
1149 const uint32_t method_idx = method->GetDexMethodIndex();
1150 const uint32_t access_flags = method->GetAccessFlags();
1151 const InvokeType invoke_type = method->GetInvokeType();
1152
Nicolas Geoffray25e04562016-03-01 13:17:58 +00001153 ArenaAllocator arena(Runtime::Current()->GetJitArenaPool());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001154 CodeVectorAllocator code_allocator(&arena);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001155 VariableSizedHandleScope handles(self);
1156
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001157 std::unique_ptr<CodeGenerator> codegen;
1158 {
1159 // Go to native so that we don't block GC during compilation.
1160 ScopedThreadSuspension sts(self, kNative);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001161 codegen.reset(
1162 TryCompile(&arena,
1163 &code_allocator,
1164 code_item,
1165 access_flags,
1166 invoke_type,
1167 class_def_idx,
1168 method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001169 class_loader,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001170 *dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001171 dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +00001172 method,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001173 osr,
1174 &handles));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001175 if (codegen.get() == nullptr) {
1176 return false;
1177 }
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001178
1179 if (kArenaAllocatorCountAllocations) {
1180 if (arena.BytesAllocated() > kArenaAllocatorMemoryReportThreshold) {
1181 MemStats mem_stats(arena.GetMemStats());
David Sehr709b0702016-10-13 09:12:37 -07001182 LOG(INFO) << dex_file->PrettyMethod(method_idx) << " " << Dumpable<MemStats>(mem_stats);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001183 }
1184 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001185 }
1186
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001187 size_t stack_map_size = 0;
1188 size_t method_info_size = 0;
1189 codegen->ComputeStackMapAndMethodInfoSize(&stack_map_size, &method_info_size);
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001190 size_t number_of_roots = codegen->GetNumberOfJitRoots();
1191 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1192 // We allocate an object array to ensure the JIT roots that we will collect in EmitJitRoots
1193 // will be visible by the GC between EmitLiterals and CommitCode. Once CommitCode is
1194 // executed, this array is not needed.
1195 Handle<mirror::ObjectArray<mirror::Object>> roots(
1196 hs.NewHandle(mirror::ObjectArray<mirror::Object>::Alloc(
1197 self, class_linker->GetClassRoot(ClassLinker::kObjectArrayClass), number_of_roots)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001198 if (roots == nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001199 // Out of memory, just clear the exception to avoid any Java exception uncaught problems.
1200 DCHECK(self->IsExceptionPending());
1201 self->ClearException();
1202 return false;
1203 }
1204 uint8_t* stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001205 uint8_t* method_info_data = nullptr;
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001206 uint8_t* roots_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001207 uint32_t data_size = code_cache->ReserveData(self,
1208 stack_map_size,
1209 method_info_size,
1210 number_of_roots,
1211 method,
1212 &stack_map_data,
1213 &method_info_data,
1214 &roots_data);
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001215 if (stack_map_data == nullptr || roots_data == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001216 return false;
1217 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001218 MaybeRecordStat(MethodCompilationStat::kCompiled);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001219 codegen->BuildStackMaps(MemoryRegion(stack_map_data, stack_map_size),
1220 MemoryRegion(method_info_data, method_info_size),
1221 *code_item);
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00001222 codegen->EmitJitRoots(code_allocator.GetData(), roots, roots_data);
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001223
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001224 const void* code = code_cache->CommitCode(
1225 self,
1226 method,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001227 stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001228 method_info_data,
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001229 roots_data,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001230 codegen->HasEmptyFrame() ? 0 : codegen->GetFrameSize(),
1231 codegen->GetCoreSpillMask(),
1232 codegen->GetFpuSpillMask(),
1233 code_allocator.GetMemory().data(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001234 code_allocator.GetSize(),
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001235 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001236 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -07001237 roots,
1238 codegen->GetGraph()->HasShouldDeoptimizeFlag(),
1239 codegen->GetGraph()->GetCHASingleImplementationList());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001240
1241 if (code == nullptr) {
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001242 code_cache->ClearData(self, stack_map_data, roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001243 return false;
1244 }
1245
David Srbecky91cc06c2016-03-07 16:13:58 +00001246 const CompilerOptions& compiler_options = GetCompilerDriver()->GetCompilerOptions();
1247 if (compiler_options.GetGenerateDebugInfo()) {
David Srbecky5cc349f2015-12-18 15:04:48 +00001248 const auto* method_header = reinterpret_cast<const OatQuickMethodHeader*>(code);
1249 const uintptr_t code_address = reinterpret_cast<uintptr_t>(method_header->GetCode());
David Srbecky09c2a6b2016-03-11 17:11:44 +00001250 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1251 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +00001252 info.dex_file = dex_file;
1253 info.class_def_index = class_def_idx;
1254 info.dex_method_index = method_idx;
1255 info.access_flags = access_flags;
1256 info.code_item = code_item;
1257 info.isa = codegen->GetInstructionSet();
1258 info.deduped = false;
1259 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1260 info.is_optimized = true;
1261 info.is_code_address_text_relative = false;
1262 info.code_address = code_address;
1263 info.code_size = code_allocator.GetSize();
1264 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
1265 info.code_info = stack_map_size == 0 ? nullptr : stack_map_data;
1266 info.cfi = ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data());
Vladimir Marko93205e32016-04-13 11:59:46 +01001267 std::vector<uint8_t> elf_file = debug::WriteDebugElfFileForMethods(
David Srbecky5d811202016-03-08 13:21:22 +00001268 GetCompilerDriver()->GetInstructionSet(),
1269 GetCompilerDriver()->GetInstructionSetFeatures(),
David Srbeckyfe736b72016-03-09 11:44:44 +00001270 ArrayRef<const debug::MethodDebugInfo>(&info, 1));
Vladimir Marko93205e32016-04-13 11:59:46 +01001271 CreateJITCodeEntryForAddress(code_address, std::move(elf_file));
David Srbecky5cc349f2015-12-18 15:04:48 +00001272 }
1273
Nicolas Geoffraya4f81542016-03-08 16:57:48 +00001274 Runtime::Current()->GetJit()->AddMemoryUsage(method, arena.BytesUsed());
1275
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001276 return true;
1277}
1278
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001279} // namespace art