blob: 4974ed0ec5dbcf0088ea15a3a0f3b84b17b3bc38 [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
Vladimir Markob4536b72015-11-24 13:45:23 +000025#ifdef ART_ENABLE_CODEGEN_arm64
Alexandre Rames44b9cf92015-08-19 15:39:06 +010026#include "instruction_simplifier_arm64.h"
27#endif
28
Alexey Frunzee3fb2452016-05-10 16:08:05 -070029#ifdef ART_ENABLE_CODEGEN_mips
Lena Djokica2901602017-09-21 13:50:52 +020030#include "instruction_simplifier_mips.h"
Alexey Frunzee3fb2452016-05-10 16:08:05 -070031#include "pc_relative_fixups_mips.h"
32#endif
33
Mark Mendell0616ae02015-04-17 12:49:27 -040034#ifdef ART_ENABLE_CODEGEN_x86
Vladimir Marko0f7dca42015-11-02 14:36:43 +000035#include "pc_relative_fixups_x86.h"
Mark Mendell0616ae02015-04-17 12:49:27 -040036#endif
37
Mark Mendellee8d9712016-07-12 11:13:15 -040038#if defined(ART_ENABLE_CODEGEN_x86) || defined(ART_ENABLE_CODEGEN_x86_64)
39#include "x86_memory_gen.h"
40#endif
41
Mathieu Chartiere401d142015-04-22 13:56:20 -070042#include "art_method-inl.h"
Mathieu Chartierb666f482015-02-18 14:33:14 -080043#include "base/arena_allocator.h"
Vladimir Markof9f64412015-09-02 14:05:49 +010044#include "base/arena_containers.h"
David Brazdil5e8b1372015-01-23 14:39:08 +000045#include "base/dumpable.h"
Vladimir Markoc90d7c72015-10-06 17:30:45 +000046#include "base/macros.h"
Andreas Gampea0d81af2016-10-27 12:04:57 -070047#include "base/mutex.h"
Vladimir Markoca6fff82017-10-03 14:49:14 +010048#include "base/scoped_arena_allocator.h"
David Brazdil5e8b1372015-01-23 14:39:08 +000049#include "base/timing_logger.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070050#include "bounds_check_elimination.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000051#include "builder.h"
Mingyao Yangb0b051a2016-11-17 09:04:53 -080052#include "cha_guard_optimization.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000053#include "code_generator.h"
Nicolas Geoffrayb813ca12017-02-16 22:08:29 +000054#include "code_sinking.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000055#include "compiled_method.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070056#include "compiler.h"
Roland Levillain75be2832014-10-17 17:02:00 +010057#include "constant_folding.h"
Igor Murashkindd018df2017-08-09 10:38:31 -070058#include "constructor_fence_redundancy_elimination.h"
Roland Levillain75be2832014-10-17 17:02:00 +010059#include "dead_code_elimination.h"
David Srbeckyc5bfa972016-02-05 15:49:10 +000060#include "debug/elf_debug_writer.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000061#include "debug/method_debug_info.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010062#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000063#include "dex/verified_method.h"
Andreas Gampea5b09a62016-11-17 15:21:22 -080064#include "dex_file_types.h"
Nicolas Geoffray9523a3e2015-07-17 11:51:28 +000065#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000066#include "driver/compiler_options.h"
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000067#include "driver/dex_compilation_unit.h"
David Brazdil69ba7b72015-06-23 18:27:30 +010068#include "graph_checker.h"
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010069#include "graph_visualizer.h"
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +010070#include "gvn.h"
Aart Bik22af3be2015-09-10 12:50:58 -070071#include "induction_var_analysis.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000072#include "inliner.h"
Nicolas Geoffray3c049742014-09-24 18:10:46 +010073#include "instruction_simplifier.h"
Artem Udovichenko4a0dad62016-01-26 12:28:31 +030074#include "instruction_simplifier_arm.h"
Andreas Gampe71fb52f2014-12-29 17:43:08 -080075#include "intrinsics.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000076#include "jit/debugger_interface.h"
Nicolas Geoffraya4f81542016-03-08 16:57:48 +000077#include "jit/jit.h"
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +000078#include "jit/jit_code_cache.h"
Nicolas Geoffray01db5f72017-07-19 15:05:49 +010079#include "jit/jit_logger.h"
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +000080#include "jni/quick/jni_compiler.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000081#include "licm.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010082#include "linker/linker_patch.h"
xueliang.zhongc239a2b2017-04-27 15:31:37 +010083#include "load_store_analysis.h"
Mingyao Yang8df69d42015-10-22 15:40:58 -070084#include "load_store_elimination.h"
Aart Bik281c6812016-08-26 11:31:48 -070085#include "loop_optimization.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000086#include "nodes.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000087#include "oat_quick_method_header.h"
Nicolas Geoffray26a25ef2014-09-30 13:54:09 +010088#include "prepare_for_register_allocation.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010089#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070090#include "register_allocator_linear_scan.h"
Alexandre Rames22aa54b2016-10-18 09:32:29 +010091#include "scheduler.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070092#include "select_generator.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010093#include "sharpening.h"
Nicolas Geoffray827eedb2015-01-26 15:18:36 +000094#include "side_effects_analysis.h"
Nicolas Geoffray31596742014-11-24 15:28:45 +000095#include "ssa_builder.h"
Nicolas Geoffray804d0932014-05-02 08:46:00 +010096#include "ssa_liveness_analysis.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000097#include "ssa_phi_elimination.h"
David Srbeckyc6b4dd82015-04-07 20:32:43 +010098#include "utils/assembler.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070099#include "verifier/verifier_compiler_binding.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000100
101namespace art {
102
Vladimir Marko3a40bf22016-03-22 16:26:33 +0000103static constexpr size_t kArenaAllocatorMemoryReportThreshold = 8 * MB;
104
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700105static constexpr const char* kPassNameSeparator = "$";
106
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000107/**
108 * Used by the code generator, to allocate the code in a vector.
109 */
110class CodeVectorAllocator FINAL : public CodeAllocator {
111 public:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100112 explicit CodeVectorAllocator(ArenaAllocator* allocator)
113 : memory_(allocator->Adapter(kArenaAllocCodeBuffer)),
Vladimir Markof9f64412015-09-02 14:05:49 +0100114 size_(0) {}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000115
116 virtual uint8_t* Allocate(size_t size) {
117 size_ = size;
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000118 memory_.resize(size);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000119 return &memory_[0];
120 }
121
122 size_t GetSize() const { return size_; }
Vladimir Markof9f64412015-09-02 14:05:49 +0100123 const ArenaVector<uint8_t>& GetMemory() const { return memory_; }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000124 uint8_t* GetData() { return memory_.data(); }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000125
126 private:
Vladimir Markof9f64412015-09-02 14:05:49 +0100127 ArenaVector<uint8_t> memory_;
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000128 size_t size_;
129
130 DISALLOW_COPY_AND_ASSIGN(CodeVectorAllocator);
131};
132
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100133/**
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100134 * Filter to apply to the visualizer. Methods whose name contain that filter will
David Brazdilee690a32014-12-01 17:04:16 +0000135 * be dumped.
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100136 */
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700137static constexpr const char kStringFilter[] = "";
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100138
David Brazdil69ba7b72015-06-23 18:27:30 +0100139class PassScope;
David Brazdil809658e2015-02-05 11:34:02 +0000140
David Brazdil69ba7b72015-06-23 18:27:30 +0100141class PassObserver : public ValueObject {
David Brazdil5e8b1372015-01-23 14:39:08 +0000142 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100143 PassObserver(HGraph* graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100144 CodeGenerator* codegen,
145 std::ostream* visualizer_output,
Andreas Gampea0d81af2016-10-27 12:04:57 -0700146 CompilerDriver* compiler_driver,
147 Mutex& dump_mutex)
David Brazdil69ba7b72015-06-23 18:27:30 +0100148 : graph_(graph),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000149 cached_method_name_(),
David Brazdil809658e2015-02-05 11:34:02 +0000150 timing_logger_enabled_(compiler_driver->GetDumpPasses()),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000151 timing_logger_(timing_logger_enabled_ ? GetMethodName() : "", true, true),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100152 disasm_info_(graph->GetAllocator()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700153 visualizer_oss_(),
154 visualizer_output_(visualizer_output),
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000155 visualizer_enabled_(!compiler_driver->GetCompilerOptions().GetDumpCfgFileName().empty()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700156 visualizer_(&visualizer_oss_, graph, *codegen),
157 visualizer_dump_mutex_(dump_mutex),
David Brazdil69ba7b72015-06-23 18:27:30 +0100158 graph_in_bad_state_(false) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700159 if (timing_logger_enabled_ || visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000160 if (!IsVerboseMethod(compiler_driver, GetMethodName())) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700161 timing_logger_enabled_ = visualizer_enabled_ = false;
162 }
163 if (visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000164 visualizer_.PrintHeader(GetMethodName());
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700165 codegen->SetDisassemblyInformation(&disasm_info_);
166 }
David Brazdil62e074f2015-04-07 18:09:37 +0100167 }
David Brazdil5e8b1372015-01-23 14:39:08 +0000168 }
169
David Brazdil69ba7b72015-06-23 18:27:30 +0100170 ~PassObserver() {
David Brazdil5e8b1372015-01-23 14:39:08 +0000171 if (timing_logger_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000172 LOG(INFO) << "TIMINGS " << GetMethodName();
David Brazdil5e8b1372015-01-23 14:39:08 +0000173 LOG(INFO) << Dumpable<TimingLogger>(timing_logger_);
174 }
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000175 DCHECK(visualizer_oss_.str().empty());
David Brazdil5e8b1372015-01-23 14:39:08 +0000176 }
177
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000178 void DumpDisassembly() REQUIRES(!visualizer_dump_mutex_) {
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100179 if (visualizer_enabled_) {
180 visualizer_.DumpGraphWithDisassembly();
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000181 FlushVisualizer();
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100182 }
183 }
184
David Brazdil69ba7b72015-06-23 18:27:30 +0100185 void SetGraphInBadState() { graph_in_bad_state_ = true; }
186
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000187 const char* GetMethodName() {
188 // PrettyMethod() is expensive, so we delay calling it until we actually have to.
189 if (cached_method_name_.empty()) {
David Sehr709b0702016-10-13 09:12:37 -0700190 cached_method_name_ = graph_->GetDexFile().PrettyMethod(graph_->GetMethodIdx());
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000191 }
192 return cached_method_name_.c_str();
193 }
194
David Brazdil5e8b1372015-01-23 14:39:08 +0000195 private:
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000196 void StartPass(const char* pass_name) REQUIRES(!visualizer_dump_mutex_) {
Wojciech Staszkiewicze7060702016-08-16 17:31:19 -0700197 VLOG(compiler) << "Starting pass: " << pass_name;
David Brazdil809658e2015-02-05 11:34:02 +0000198 // Dump graph first, then start timer.
199 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100200 visualizer_.DumpGraph(pass_name, /* is_after_pass */ false, graph_in_bad_state_);
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000201 FlushVisualizer();
David Brazdil809658e2015-02-05 11:34:02 +0000202 }
203 if (timing_logger_enabled_) {
204 timing_logger_.StartTiming(pass_name);
205 }
206 }
207
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000208 void FlushVisualizer() REQUIRES(!visualizer_dump_mutex_) {
209 MutexLock mu(Thread::Current(), visualizer_dump_mutex_);
210 *visualizer_output_ << visualizer_oss_.str();
211 visualizer_output_->flush();
212 visualizer_oss_.str("");
213 visualizer_oss_.clear();
214 }
215
216 void EndPass(const char* pass_name) REQUIRES(!visualizer_dump_mutex_) {
David Brazdil809658e2015-02-05 11:34:02 +0000217 // Pause timer first, then dump graph.
218 if (timing_logger_enabled_) {
219 timing_logger_.EndTiming();
220 }
221 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100222 visualizer_.DumpGraph(pass_name, /* is_after_pass */ true, graph_in_bad_state_);
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000223 FlushVisualizer();
David Brazdil809658e2015-02-05 11:34:02 +0000224 }
David Brazdil69ba7b72015-06-23 18:27:30 +0100225
226 // Validate the HGraph if running in debug mode.
227 if (kIsDebugBuild) {
228 if (!graph_in_bad_state_) {
David Brazdilbadd8262016-02-02 16:28:56 +0000229 GraphChecker checker(graph_);
230 checker.Run();
231 if (!checker.IsValid()) {
232 LOG(FATAL) << "Error after " << pass_name << ": " << Dumpable<GraphChecker>(checker);
David Brazdil69ba7b72015-06-23 18:27:30 +0100233 }
234 }
235 }
David Brazdil809658e2015-02-05 11:34:02 +0000236 }
237
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700238 static bool IsVerboseMethod(CompilerDriver* compiler_driver, const char* method_name) {
239 // Test an exact match to --verbose-methods. If verbose-methods is set, this overrides an
240 // empty kStringFilter matching all methods.
241 if (compiler_driver->GetCompilerOptions().HasVerboseMethods()) {
242 return compiler_driver->GetCompilerOptions().IsVerboseMethod(method_name);
243 }
244
245 // Test the kStringFilter sub-string. constexpr helper variable to silence unreachable-code
246 // warning when the string is empty.
247 constexpr bool kStringFilterEmpty = arraysize(kStringFilter) <= 1;
248 if (kStringFilterEmpty || strstr(method_name, kStringFilter) != nullptr) {
249 return true;
250 }
251
252 return false;
253 }
254
David Brazdil69ba7b72015-06-23 18:27:30 +0100255 HGraph* const graph_;
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000256
257 std::string cached_method_name_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000258
259 bool timing_logger_enabled_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000260 TimingLogger timing_logger_;
261
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100262 DisassemblyInformation disasm_info_;
263
Andreas Gampea0d81af2016-10-27 12:04:57 -0700264 std::ostringstream visualizer_oss_;
265 std::ostream* visualizer_output_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000266 bool visualizer_enabled_;
267 HGraphVisualizer visualizer_;
Andreas Gampea0d81af2016-10-27 12:04:57 -0700268 Mutex& visualizer_dump_mutex_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000269
David Brazdil69ba7b72015-06-23 18:27:30 +0100270 // Flag to be set by the compiler if the pass failed and the graph is not
271 // expected to validate.
272 bool graph_in_bad_state_;
David Brazdil809658e2015-02-05 11:34:02 +0000273
David Brazdil69ba7b72015-06-23 18:27:30 +0100274 friend PassScope;
275
276 DISALLOW_COPY_AND_ASSIGN(PassObserver);
David Brazdil5e8b1372015-01-23 14:39:08 +0000277};
278
David Brazdil69ba7b72015-06-23 18:27:30 +0100279class PassScope : public ValueObject {
David Brazdil809658e2015-02-05 11:34:02 +0000280 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100281 PassScope(const char *pass_name, PassObserver* pass_observer)
David Brazdil809658e2015-02-05 11:34:02 +0000282 : pass_name_(pass_name),
David Brazdil69ba7b72015-06-23 18:27:30 +0100283 pass_observer_(pass_observer) {
284 pass_observer_->StartPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000285 }
286
David Brazdil69ba7b72015-06-23 18:27:30 +0100287 ~PassScope() {
288 pass_observer_->EndPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000289 }
290
291 private:
292 const char* const pass_name_;
David Brazdil69ba7b72015-06-23 18:27:30 +0100293 PassObserver* const pass_observer_;
David Brazdil809658e2015-02-05 11:34:02 +0000294};
295
Andreas Gampe53c913b2014-08-12 23:19:23 -0700296class OptimizingCompiler FINAL : public Compiler {
297 public:
298 explicit OptimizingCompiler(CompilerDriver* driver);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700299 ~OptimizingCompiler() OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700300
Vladimir Markodf739842016-03-23 16:59:07 +0000301 bool CanCompileMethod(uint32_t method_idx, const DexFile& dex_file) const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700302
303 CompiledMethod* Compile(const DexFile::CodeItem* code_item,
304 uint32_t access_flags,
305 InvokeType invoke_type,
306 uint16_t class_def_idx,
307 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000308 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700309 const DexFile& dex_file,
310 Handle<mirror::DexCache> dex_cache) const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700311
Andreas Gampe53c913b2014-08-12 23:19:23 -0700312 CompiledMethod* JniCompile(uint32_t access_flags,
313 uint32_t method_idx,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000314 const DexFile& dex_file,
315 Handle<mirror::DexCache> dex_cache) const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700316
Mathieu Chartiere401d142015-04-22 13:56:20 -0700317 uintptr_t GetEntryPointOf(ArtMethod* method) const OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700318 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000319 return reinterpret_cast<uintptr_t>(method->GetEntryPointFromQuickCompiledCodePtrSize(
320 InstructionSetPointerSize(GetCompilerDriver()->GetInstructionSet())));
321 }
Andreas Gampe53c913b2014-08-12 23:19:23 -0700322
David Brazdilee690a32014-12-01 17:04:16 +0000323 void Init() OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700324
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000325 void UnInit() const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700326
Nicolas Geoffray01db5f72017-07-19 15:05:49 +0100327 bool JitCompile(Thread* self,
328 jit::JitCodeCache* code_cache,
329 ArtMethod* method,
330 bool osr,
331 jit::JitLogger* jit_logger)
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000332 OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700333 REQUIRES_SHARED(Locks::mutator_lock_);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000334
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700335 private:
336 void RunOptimizations(HGraph* graph,
337 CodeGenerator* codegen,
338 CompilerDriver* driver,
339 const DexCompilationUnit& dex_compilation_unit,
340 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700341 VariableSizedHandleScope* handles) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700342
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700343 void RunOptimizations(HOptimization* optimizations[],
344 size_t length,
345 PassObserver* pass_observer) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700346
Andreas Gampe53c913b2014-08-12 23:19:23 -0700347 private:
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000348 // Create a 'CompiledMethod' for an optimized graph.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100349 CompiledMethod* Emit(ArenaAllocator* allocator,
David Brazdil58282f42016-01-14 12:45:10 +0000350 CodeVectorAllocator* code_allocator,
351 CodeGenerator* codegen,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000352 CompilerDriver* driver,
353 const DexFile::CodeItem* item) const;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000354
355 // Try compiling a method and return the code generator used for
356 // compiling it.
357 // This method:
358 // 1) Builds the graph. Returns null if it failed to build it.
David Brazdil58282f42016-01-14 12:45:10 +0000359 // 2) Transforms the graph to SSA. Returns null if it failed.
360 // 3) Runs optimizations on the graph, including register allocator.
361 // 4) Generates code with the `code_allocator` provided.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100362 CodeGenerator* TryCompile(ArenaAllocator* allocator,
363 ArenaStack* arena_stack,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000364 CodeVectorAllocator* code_allocator,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000365 const DexCompilationUnit& dex_compilation_unit,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000366 ArtMethod* method,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000367 bool osr,
368 VariableSizedHandleScope* handles) const;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000369
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000370 CodeGenerator* TryCompileIntrinsic(ArenaAllocator* allocator,
371 ArenaStack* arena_stack,
372 CodeVectorAllocator* code_allocator,
373 const DexCompilationUnit& dex_compilation_unit,
374 ArtMethod* method,
375 VariableSizedHandleScope* handles) const;
376
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700377 void MaybeRunInliner(HGraph* graph,
378 CodeGenerator* codegen,
379 CompilerDriver* driver,
380 const DexCompilationUnit& dex_compilation_unit,
381 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700382 VariableSizedHandleScope* handles) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700383
384 void RunArchOptimizations(InstructionSet instruction_set,
385 HGraph* graph,
386 CodeGenerator* codegen,
387 PassObserver* pass_observer) const;
388
Calin Juravle2be39e02015-04-21 13:56:34 +0100389 std::unique_ptr<OptimizingCompilerStats> compilation_stats_;
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100390
Andreas Gampe53c913b2014-08-12 23:19:23 -0700391 std::unique_ptr<std::ostream> visualizer_output_;
392
Andreas Gampea0d81af2016-10-27 12:04:57 -0700393 mutable Mutex dump_mutex_; // To synchronize visualizer writing.
394
Andreas Gampe53c913b2014-08-12 23:19:23 -0700395 DISALLOW_COPY_AND_ASSIGN(OptimizingCompiler);
396};
397
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100398static const int kMaximumCompilationTimeBeforeWarning = 100; /* ms */
399
400OptimizingCompiler::OptimizingCompiler(CompilerDriver* driver)
Andreas Gampea0d81af2016-10-27 12:04:57 -0700401 : Compiler(driver, kMaximumCompilationTimeBeforeWarning),
402 dump_mutex_("Visualizer dump lock") {}
David Brazdilee690a32014-12-01 17:04:16 +0000403
404void OptimizingCompiler::Init() {
405 // Enable C1visualizer output. Must be done in Init() because the compiler
406 // driver is not fully initialized when passed to the compiler's constructor.
407 CompilerDriver* driver = GetCompilerDriver();
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000408 const std::string cfg_file_name = driver->GetCompilerOptions().GetDumpCfgFileName();
David Brazdil866c0312015-01-13 21:21:31 +0000409 if (!cfg_file_name.empty()) {
Calin Juravle87000a92015-08-24 15:34:44 +0100410 std::ios_base::openmode cfg_file_mode =
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000411 driver->GetCompilerOptions().GetDumpCfgAppend() ? std::ofstream::app : std::ofstream::out;
Calin Juravle87000a92015-08-24 15:34:44 +0100412 visualizer_output_.reset(new std::ofstream(cfg_file_name, cfg_file_mode));
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100413 }
Calin Juravle2be39e02015-04-21 13:56:34 +0100414 if (driver->GetDumpStats()) {
415 compilation_stats_.reset(new OptimizingCompilerStats());
416 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100417}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000418
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000419void OptimizingCompiler::UnInit() const {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000420}
421
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100422OptimizingCompiler::~OptimizingCompiler() {
Calin Juravle2be39e02015-04-21 13:56:34 +0100423 if (compilation_stats_.get() != nullptr) {
424 compilation_stats_->Log();
425 }
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100426}
427
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000428bool OptimizingCompiler::CanCompileMethod(uint32_t method_idx ATTRIBUTE_UNUSED,
Vladimir Markodf739842016-03-23 16:59:07 +0000429 const DexFile& dex_file ATTRIBUTE_UNUSED) const {
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000430 return true;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700431}
432
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000433static bool IsInstructionSetSupported(InstructionSet instruction_set) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000434 return instruction_set == InstructionSet::kArm
435 || instruction_set == InstructionSet::kArm64
436 || instruction_set == InstructionSet::kThumb2
437 || instruction_set == InstructionSet::kMips
438 || instruction_set == InstructionSet::kMips64
439 || instruction_set == InstructionSet::kX86
440 || instruction_set == InstructionSet::kX86_64;
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000441}
442
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700443// Strip pass name suffix to get optimization name.
444static std::string ConvertPassNameToOptimizationName(const std::string& pass_name) {
445 size_t pos = pass_name.find(kPassNameSeparator);
446 return pos == std::string::npos ? pass_name : pass_name.substr(0, pos);
447}
448
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700449static HOptimization* BuildOptimization(
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700450 const std::string& pass_name,
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100451 ArenaAllocator* allocator,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700452 HGraph* graph,
453 OptimizingCompilerStats* stats,
454 CodeGenerator* codegen,
455 CompilerDriver* driver,
456 const DexCompilationUnit& dex_compilation_unit,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700457 VariableSizedHandleScope* handles,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700458 SideEffectsAnalysis* most_recent_side_effects,
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100459 HInductionVarAnalysis* most_recent_induction,
460 LoadStoreAnalysis* most_recent_lsa) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700461 std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700462 if (opt_name == BoundsCheckElimination::kBoundsCheckEliminationPassName) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700463 CHECK(most_recent_side_effects != nullptr && most_recent_induction != nullptr);
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100464 return new (allocator) BoundsCheckElimination(graph,
465 *most_recent_side_effects,
466 most_recent_induction);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700467 } else if (opt_name == GVNOptimization::kGlobalValueNumberingPassName) {
468 CHECK(most_recent_side_effects != nullptr);
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100469 return new (allocator) GVNOptimization(graph, *most_recent_side_effects, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700470 } else if (opt_name == HConstantFolding::kConstantFoldingPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100471 return new (allocator) HConstantFolding(graph, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700472 } else if (opt_name == HDeadCodeElimination::kDeadCodeEliminationPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100473 return new (allocator) HDeadCodeElimination(graph, stats, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700474 } else if (opt_name == HInliner::kInlinerPassName) {
475 size_t number_of_dex_registers = dex_compilation_unit.GetCodeItem()->registers_size_;
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100476 return new (allocator) HInliner(graph, // outer_graph
477 graph, // outermost_graph
478 codegen,
479 dex_compilation_unit, // outer_compilation_unit
480 dex_compilation_unit, // outermost_compilation_unit
481 driver,
482 handles,
483 stats,
484 number_of_dex_registers,
485 /* total_number_of_instructions */ 0,
486 /* parent */ nullptr);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700487 } else if (opt_name == HSharpening::kSharpeningPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100488 return new (allocator) HSharpening(graph, codegen, dex_compilation_unit, driver, handles);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700489 } else if (opt_name == HSelectGenerator::kSelectGeneratorPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100490 return new (allocator) HSelectGenerator(graph, handles, stats);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700491 } else if (opt_name == HInductionVarAnalysis::kInductionPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100492 return new (allocator) HInductionVarAnalysis(graph);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700493 } else if (opt_name == InstructionSimplifier::kInstructionSimplifierPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100494 return new (allocator) InstructionSimplifier(graph, codegen, driver, stats, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700495 } else if (opt_name == IntrinsicsRecognizer::kIntrinsicsRecognizerPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100496 return new (allocator) IntrinsicsRecognizer(graph, stats);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700497 } else if (opt_name == LICM::kLoopInvariantCodeMotionPassName) {
498 CHECK(most_recent_side_effects != nullptr);
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100499 return new (allocator) LICM(graph, *most_recent_side_effects, stats);
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100500 } else if (opt_name == LoadStoreAnalysis::kLoadStoreAnalysisPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100501 return new (allocator) LoadStoreAnalysis(graph);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700502 } else if (opt_name == LoadStoreElimination::kLoadStoreEliminationPassName) {
503 CHECK(most_recent_side_effects != nullptr);
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100504 CHECK(most_recent_lsa != nullptr);
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100505 return new (allocator) LoadStoreElimination(graph,
506 *most_recent_side_effects,
507 *most_recent_lsa, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700508 } else if (opt_name == SideEffectsAnalysis::kSideEffectsAnalysisPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100509 return new (allocator) SideEffectsAnalysis(graph);
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100510 } else if (opt_name == HLoopOptimization::kLoopOptimizationPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100511 return new (allocator) HLoopOptimization(graph, driver, most_recent_induction, stats);
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800512 } else if (opt_name == CHAGuardOptimization::kCHAGuardOptimizationPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100513 return new (allocator) CHAGuardOptimization(graph);
Nicolas Geoffrayb813ca12017-02-16 22:08:29 +0000514 } else if (opt_name == CodeSinking::kCodeSinkingPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100515 return new (allocator) CodeSinking(graph, stats);
Igor Murashkindd018df2017-08-09 10:38:31 -0700516 } else if (opt_name == ConstructorFenceRedundancyElimination::kPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100517 return new (allocator) ConstructorFenceRedundancyElimination(graph, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700518#ifdef ART_ENABLE_CODEGEN_arm
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700519 } else if (opt_name == arm::InstructionSimplifierArm::kInstructionSimplifierArmPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100520 return new (allocator) arm::InstructionSimplifierArm(graph, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700521#endif
522#ifdef ART_ENABLE_CODEGEN_arm64
523 } else if (opt_name == arm64::InstructionSimplifierArm64::kInstructionSimplifierArm64PassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100524 return new (allocator) arm64::InstructionSimplifierArm64(graph, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700525#endif
526#ifdef ART_ENABLE_CODEGEN_mips
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700527 } else if (opt_name == mips::PcRelativeFixups::kPcRelativeFixupsMipsPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100528 return new (allocator) mips::PcRelativeFixups(graph, codegen, stats);
Lena Djokica2901602017-09-21 13:50:52 +0200529 } else if (opt_name == mips::InstructionSimplifierMips::kInstructionSimplifierMipsPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100530 return new (allocator) mips::InstructionSimplifierMips(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700531#endif
532#ifdef ART_ENABLE_CODEGEN_x86
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700533 } else if (opt_name == x86::PcRelativeFixups::kPcRelativeFixupsX86PassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100534 return new (allocator) x86::PcRelativeFixups(graph, codegen, stats);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700535 } else if (opt_name == x86::X86MemoryOperandGeneration::kX86MemoryOperandGenerationPassName) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100536 return new (allocator) x86::X86MemoryOperandGeneration(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700537#endif
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700538 }
539 return nullptr;
540}
541
542static ArenaVector<HOptimization*> BuildOptimizations(
543 const std::vector<std::string>& pass_names,
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100544 ArenaAllocator* allocator,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700545 HGraph* graph,
546 OptimizingCompilerStats* stats,
547 CodeGenerator* codegen,
548 CompilerDriver* driver,
549 const DexCompilationUnit& dex_compilation_unit,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700550 VariableSizedHandleScope* handles) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700551 // Few HOptimizations constructors require SideEffectsAnalysis or HInductionVarAnalysis
552 // instances. This method assumes that each of them expects the nearest instance preceeding it
553 // in the pass name list.
554 SideEffectsAnalysis* most_recent_side_effects = nullptr;
555 HInductionVarAnalysis* most_recent_induction = nullptr;
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100556 LoadStoreAnalysis* most_recent_lsa = nullptr;
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100557 ArenaVector<HOptimization*> ret(allocator->Adapter());
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700558 for (const std::string& pass_name : pass_names) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700559 HOptimization* opt = BuildOptimization(
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700560 pass_name,
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100561 allocator,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700562 graph,
563 stats,
564 codegen,
565 driver,
566 dex_compilation_unit,
567 handles,
568 most_recent_side_effects,
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100569 most_recent_induction,
570 most_recent_lsa);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700571 CHECK(opt != nullptr) << "Couldn't build optimization: \"" << pass_name << "\"";
572 ret.push_back(opt);
573
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700574 std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700575 if (opt_name == SideEffectsAnalysis::kSideEffectsAnalysisPassName) {
576 most_recent_side_effects = down_cast<SideEffectsAnalysis*>(opt);
577 } else if (opt_name == HInductionVarAnalysis::kInductionPassName) {
578 most_recent_induction = down_cast<HInductionVarAnalysis*>(opt);
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100579 } else if (opt_name == LoadStoreAnalysis::kLoadStoreAnalysisPassName) {
580 most_recent_lsa = down_cast<LoadStoreAnalysis*>(opt);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700581 }
582 }
583 return ret;
584}
585
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700586void OptimizingCompiler::RunOptimizations(HOptimization* optimizations[],
587 size_t length,
588 PassObserver* pass_observer) const {
Calin Juravle10e244f2015-01-26 18:54:32 +0000589 for (size_t i = 0; i < length; ++i) {
David Brazdil69ba7b72015-06-23 18:27:30 +0100590 PassScope scope(optimizations[i]->GetPassName(), pass_observer);
591 optimizations[i]->Run();
Calin Juravle10e244f2015-01-26 18:54:32 +0000592 }
593}
594
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700595void OptimizingCompiler::MaybeRunInliner(HGraph* graph,
596 CodeGenerator* codegen,
597 CompilerDriver* driver,
598 const DexCompilationUnit& dex_compilation_unit,
599 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700600 VariableSizedHandleScope* handles) const {
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700601 OptimizingCompilerStats* stats = compilation_stats_.get();
Calin Juravleec748352015-07-29 13:52:12 +0100602 const CompilerOptions& compiler_options = driver->GetCompilerOptions();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000603 bool should_inline = (compiler_options.GetInlineMaxCodeUnits() > 0);
Calin Juravleec748352015-07-29 13:52:12 +0100604 if (!should_inline) {
605 return;
606 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000607 size_t number_of_dex_registers = dex_compilation_unit.GetCodeItem()->registers_size_;
Vladimir Markoca6fff82017-10-03 14:49:14 +0100608 HInliner* inliner = new (graph->GetAllocator()) HInliner(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700609 graph, // outer_graph
610 graph, // outermost_graph
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000611 codegen,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700612 dex_compilation_unit, // outer_compilation_unit
613 dex_compilation_unit, // outermost_compilation_unit
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000614 driver,
615 handles,
616 stats,
617 number_of_dex_registers,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000618 /* total_number_of_instructions */ 0,
619 /* parent */ nullptr);
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000620 HOptimization* optimizations[] = { inliner };
Calin Juravleec748352015-07-29 13:52:12 +0100621
622 RunOptimizations(optimizations, arraysize(optimizations), pass_observer);
623}
624
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700625void OptimizingCompiler::RunArchOptimizations(InstructionSet instruction_set,
626 HGraph* graph,
627 CodeGenerator* codegen,
628 PassObserver* pass_observer) const {
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700629 UNUSED(codegen); // To avoid compilation error when compiling for svelte
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700630 OptimizingCompilerStats* stats = compilation_stats_.get();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100631 ArenaAllocator* allocator = graph->GetAllocator();
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100632 switch (instruction_set) {
Artem Serov2bbc9532016-10-21 11:51:50 +0100633#if defined(ART_ENABLE_CODEGEN_arm)
Vladimir Marko33bff252017-11-01 14:35:42 +0000634 case InstructionSet::kThumb2:
635 case InstructionSet::kArm: {
Artem Udovichenko4a0dad62016-01-26 12:28:31 +0300636 arm::InstructionSimplifierArm* simplifier =
Vladimir Markoca6fff82017-10-03 14:49:14 +0100637 new (allocator) arm::InstructionSimplifierArm(graph, stats);
638 SideEffectsAnalysis* side_effects = new (allocator) SideEffectsAnalysis(graph);
639 GVNOptimization* gvn =
640 new (allocator) GVNOptimization(graph, *side_effects, "GVN$after_arch");
xueliang.zhongf7caf682017-03-01 16:07:02 +0000641 HInstructionScheduling* scheduling =
Vladimir Markoca6fff82017-10-03 14:49:14 +0100642 new (allocator) HInstructionScheduling(graph, instruction_set, codegen);
Vladimir Markob4536b72015-11-24 13:45:23 +0000643 HOptimization* arm_optimizations[] = {
Artem Udovichenko4a0dad62016-01-26 12:28:31 +0300644 simplifier,
Artem Serov328429f2016-07-06 16:23:04 +0100645 side_effects,
646 gvn,
xueliang.zhongf7caf682017-03-01 16:07:02 +0000647 scheduling,
Vladimir Markob4536b72015-11-24 13:45:23 +0000648 };
649 RunOptimizations(arm_optimizations, arraysize(arm_optimizations), pass_observer);
650 break;
651 }
652#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100653#ifdef ART_ENABLE_CODEGEN_arm64
Vladimir Marko33bff252017-11-01 14:35:42 +0000654 case InstructionSet::kArm64: {
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100655 arm64::InstructionSimplifierArm64* simplifier =
Vladimir Markoca6fff82017-10-03 14:49:14 +0100656 new (allocator) arm64::InstructionSimplifierArm64(graph, stats);
657 SideEffectsAnalysis* side_effects = new (allocator) SideEffectsAnalysis(graph);
658 GVNOptimization* gvn =
659 new (allocator) GVNOptimization(graph, *side_effects, "GVN$after_arch");
Alexandre Rames22aa54b2016-10-18 09:32:29 +0100660 HInstructionScheduling* scheduling =
Vladimir Markoca6fff82017-10-03 14:49:14 +0100661 new (allocator) HInstructionScheduling(graph, instruction_set);
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100662 HOptimization* arm64_optimizations[] = {
663 simplifier,
664 side_effects,
Alexandre Rames22aa54b2016-10-18 09:32:29 +0100665 gvn,
666 scheduling,
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100667 };
668 RunOptimizations(arm64_optimizations, arraysize(arm64_optimizations), pass_observer);
669 break;
670 }
671#endif
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700672#ifdef ART_ENABLE_CODEGEN_mips
Vladimir Marko33bff252017-11-01 14:35:42 +0000673 case InstructionSet::kMips: {
Lena Djokica2901602017-09-21 13:50:52 +0200674 mips::InstructionSimplifierMips* simplifier =
Vladimir Markoca6fff82017-10-03 14:49:14 +0100675 new (allocator) mips::InstructionSimplifierMips(graph, codegen, stats);
676 SideEffectsAnalysis* side_effects = new (allocator) SideEffectsAnalysis(graph);
677 GVNOptimization* gvn =
678 new (allocator) GVNOptimization(graph, *side_effects, "GVN$after_arch");
Aart Bik9e147872017-09-27 11:25:01 -0700679 mips::PcRelativeFixups* pc_relative_fixups =
Vladimir Markoca6fff82017-10-03 14:49:14 +0100680 new (allocator) mips::PcRelativeFixups(graph, codegen, stats);
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700681 HOptimization* mips_optimizations[] = {
Lena Djokica2901602017-09-21 13:50:52 +0200682 simplifier,
Lena Djokicb8e9c352017-09-20 15:11:13 +0200683 side_effects,
684 gvn,
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700685 pc_relative_fixups,
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700686 };
687 RunOptimizations(mips_optimizations, arraysize(mips_optimizations), pass_observer);
688 break;
689 }
690#endif
Lena Djokicb8e9c352017-09-20 15:11:13 +0200691#ifdef ART_ENABLE_CODEGEN_mips64
Vladimir Marko33bff252017-11-01 14:35:42 +0000692 case InstructionSet::kMips64: {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100693 SideEffectsAnalysis* side_effects = new (allocator) SideEffectsAnalysis(graph);
694 GVNOptimization* gvn =
695 new (allocator) GVNOptimization(graph, *side_effects, "GVN$after_arch");
Lena Djokicb8e9c352017-09-20 15:11:13 +0200696 HOptimization* mips64_optimizations[] = {
697 side_effects,
698 gvn,
699 };
700 RunOptimizations(mips64_optimizations, arraysize(mips64_optimizations), pass_observer);
701 break;
702 }
703#endif
Mark Mendell0616ae02015-04-17 12:49:27 -0400704#ifdef ART_ENABLE_CODEGEN_x86
Vladimir Marko33bff252017-11-01 14:35:42 +0000705 case InstructionSet::kX86: {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100706 SideEffectsAnalysis* side_effects = new (allocator) SideEffectsAnalysis(graph);
707 GVNOptimization* gvn =
708 new (allocator) GVNOptimization(graph, *side_effects, "GVN$after_arch");
Aart Bikd1c40452016-03-02 16:06:13 -0800709 x86::PcRelativeFixups* pc_relative_fixups =
Vladimir Markoca6fff82017-10-03 14:49:14 +0100710 new (allocator) x86::PcRelativeFixups(graph, codegen, stats);
Mark Mendellee8d9712016-07-12 11:13:15 -0400711 x86::X86MemoryOperandGeneration* memory_gen =
Vladimir Markoca6fff82017-10-03 14:49:14 +0100712 new (allocator) x86::X86MemoryOperandGeneration(graph, codegen, stats);
Mark Mendell0616ae02015-04-17 12:49:27 -0400713 HOptimization* x86_optimizations[] = {
Aart Bik9e147872017-09-27 11:25:01 -0700714 side_effects,
715 gvn,
Mark Mendellee8d9712016-07-12 11:13:15 -0400716 pc_relative_fixups,
717 memory_gen
Mark Mendell0616ae02015-04-17 12:49:27 -0400718 };
719 RunOptimizations(x86_optimizations, arraysize(x86_optimizations), pass_observer);
720 break;
721 }
722#endif
Mark Mendellee8d9712016-07-12 11:13:15 -0400723#ifdef ART_ENABLE_CODEGEN_x86_64
Vladimir Marko33bff252017-11-01 14:35:42 +0000724 case InstructionSet::kX86_64: {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100725 SideEffectsAnalysis* side_effects = new (allocator) SideEffectsAnalysis(graph);
726 GVNOptimization* gvn =
727 new (allocator) GVNOptimization(graph, *side_effects, "GVN$after_arch");
Mark Mendellee8d9712016-07-12 11:13:15 -0400728 x86::X86MemoryOperandGeneration* memory_gen =
Vladimir Markoca6fff82017-10-03 14:49:14 +0100729 new (allocator) x86::X86MemoryOperandGeneration(graph, codegen, stats);
Mark Mendellee8d9712016-07-12 11:13:15 -0400730 HOptimization* x86_64_optimizations[] = {
Aart Bik9e147872017-09-27 11:25:01 -0700731 side_effects,
732 gvn,
Mark Mendellee8d9712016-07-12 11:13:15 -0400733 memory_gen
734 };
735 RunOptimizations(x86_64_optimizations, arraysize(x86_64_optimizations), pass_observer);
736 break;
737 }
738#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100739 default:
740 break;
741 }
742}
743
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000744NO_INLINE // Avoid increasing caller's frame size by large stack-allocated objects.
745static void AllocateRegisters(HGraph* graph,
746 CodeGenerator* codegen,
Matthew Gharrity2cd05b72016-08-03 16:57:37 -0700747 PassObserver* pass_observer,
Igor Murashkin6ef45672017-08-08 13:59:55 -0700748 RegisterAllocator::Strategy strategy,
749 OptimizingCompilerStats* stats) {
Mingyao Yang700347e2016-03-02 14:59:32 -0800750 {
751 PassScope scope(PrepareForRegisterAllocation::kPrepareForRegisterAllocationPassName,
752 pass_observer);
Igor Murashkin6ef45672017-08-08 13:59:55 -0700753 PrepareForRegisterAllocation(graph, stats).Run();
Mingyao Yang700347e2016-03-02 14:59:32 -0800754 }
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100755 // Use local allocator shared by SSA liveness analysis and register allocator.
756 // (Register allocator creates new objects in the liveness data.)
757 ScopedArenaAllocator local_allocator(graph->GetArenaStack());
758 SsaLivenessAnalysis liveness(graph, codegen, &local_allocator);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000759 {
760 PassScope scope(SsaLivenessAnalysis::kLivenessPassName, pass_observer);
761 liveness.Analyze();
762 }
763 {
764 PassScope scope(RegisterAllocator::kRegisterAllocatorPassName, pass_observer);
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100765 std::unique_ptr<RegisterAllocator> register_allocator =
766 RegisterAllocator::Create(&local_allocator, codegen, liveness, strategy);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100767 register_allocator->AllocateRegisters();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000768 }
769}
770
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700771void OptimizingCompiler::RunOptimizations(HGraph* graph,
772 CodeGenerator* codegen,
773 CompilerDriver* driver,
774 const DexCompilationUnit& dex_compilation_unit,
775 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700776 VariableSizedHandleScope* handles) const {
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700777 OptimizingCompilerStats* stats = compilation_stats_.get();
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100778 ArenaAllocator* allocator = graph->GetAllocator();
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700779 if (driver->GetCompilerOptions().GetPassesToRun() != nullptr) {
780 ArenaVector<HOptimization*> optimizations = BuildOptimizations(
781 *driver->GetCompilerOptions().GetPassesToRun(),
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100782 allocator,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700783 graph,
784 stats,
785 codegen,
786 driver,
787 dex_compilation_unit,
788 handles);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000789 RunOptimizations(optimizations.data(), optimizations.size(), pass_observer);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700790 return;
791 }
792
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100793 HDeadCodeElimination* dce1 = new (allocator) HDeadCodeElimination(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700794 graph, stats, "dead_code_elimination$initial");
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100795 HDeadCodeElimination* dce2 = new (allocator) HDeadCodeElimination(
Aart Bik2767f4b2016-10-28 15:03:53 -0700796 graph, stats, "dead_code_elimination$after_inlining");
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100797 HDeadCodeElimination* dce3 = new (allocator) HDeadCodeElimination(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700798 graph, stats, "dead_code_elimination$final");
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100799 HConstantFolding* fold1 = new (allocator) HConstantFolding(graph, "constant_folding");
800 InstructionSimplifier* simplify1 = new (allocator) InstructionSimplifier(
Vladimir Marko65979462017-05-19 17:25:12 +0100801 graph, codegen, driver, stats);
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100802 HSelectGenerator* select_generator = new (allocator) HSelectGenerator(graph, handles, stats);
803 HConstantFolding* fold2 = new (allocator) HConstantFolding(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700804 graph, "constant_folding$after_inlining");
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100805 HConstantFolding* fold3 = new (allocator) HConstantFolding(graph, "constant_folding$after_bce");
806 SideEffectsAnalysis* side_effects1 = new (allocator) SideEffectsAnalysis(
Aart Bik92685a82017-03-06 11:13:43 -0800807 graph, "side_effects$before_gvn");
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100808 SideEffectsAnalysis* side_effects2 = new (allocator) SideEffectsAnalysis(
Aart Bik92685a82017-03-06 11:13:43 -0800809 graph, "side_effects$before_lse");
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100810 GVNOptimization* gvn = new (allocator) GVNOptimization(graph, *side_effects1);
811 LICM* licm = new (allocator) LICM(graph, *side_effects1, stats);
812 HInductionVarAnalysis* induction = new (allocator) HInductionVarAnalysis(graph);
813 BoundsCheckElimination* bce =
814 new (allocator) BoundsCheckElimination(graph, *side_effects1, induction);
815 HLoopOptimization* loop = new (allocator) HLoopOptimization(graph, driver, induction, stats);
816 LoadStoreAnalysis* lsa = new (allocator) LoadStoreAnalysis(graph);
817 LoadStoreElimination* lse =
818 new (allocator) LoadStoreElimination(graph, *side_effects2, *lsa, stats);
819 HSharpening* sharpening = new (allocator) HSharpening(
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000820 graph, codegen, dex_compilation_unit, driver, handles);
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100821 InstructionSimplifier* simplify2 = new (allocator) InstructionSimplifier(
Vladimir Marko65979462017-05-19 17:25:12 +0100822 graph, codegen, driver, stats, "instruction_simplifier$after_inlining");
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100823 InstructionSimplifier* simplify3 = new (allocator) InstructionSimplifier(
Vladimir Marko65979462017-05-19 17:25:12 +0100824 graph, codegen, driver, stats, "instruction_simplifier$after_bce");
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100825 InstructionSimplifier* simplify4 = new (allocator) InstructionSimplifier(
Vladimir Marko65979462017-05-19 17:25:12 +0100826 graph, codegen, driver, stats, "instruction_simplifier$before_codegen");
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100827 IntrinsicsRecognizer* intrinsics = new (allocator) IntrinsicsRecognizer(graph, stats);
828 CHAGuardOptimization* cha_guard = new (allocator) CHAGuardOptimization(graph);
829 CodeSinking* code_sinking = new (allocator) CodeSinking(graph, stats);
Igor Murashkindd018df2017-08-09 10:38:31 -0700830 ConstructorFenceRedundancyElimination* cfre =
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100831 new (allocator) ConstructorFenceRedundancyElimination(graph, stats);
Andreas Gampe71fb52f2014-12-29 17:43:08 -0800832
Calin Juravleec748352015-07-29 13:52:12 +0100833 HOptimization* optimizations1[] = {
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100834 intrinsics,
David Brazdil4833f5a2015-12-16 10:37:39 +0000835 sharpening,
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100836 fold1,
837 simplify1,
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100838 dce1,
Calin Juravleec748352015-07-29 13:52:12 +0100839 };
Calin Juravleec748352015-07-29 13:52:12 +0100840 RunOptimizations(optimizations1, arraysize(optimizations1), pass_observer);
841
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700842 MaybeRunInliner(graph, codegen, driver, dex_compilation_unit, pass_observer, handles);
David Brazdil95177982015-10-30 12:56:58 -0500843
David Brazdil8993caf2015-12-07 10:04:40 +0000844 HOptimization* optimizations2[] = {
David Brazdil74eb1b22015-12-14 11:44:01 +0000845 // SelectGenerator depends on the InstructionSimplifier removing
David Brazdil8993caf2015-12-07 10:04:40 +0000846 // redundant suspend checks to recognize empty blocks.
David Brazdil74eb1b22015-12-14 11:44:01 +0000847 select_generator,
David Brazdil8993caf2015-12-07 10:04:40 +0000848 fold2, // TODO: if we don't inline we can also skip fold2.
Aart Bik639cc8c2016-10-18 13:03:31 -0700849 simplify2,
Aart Bik2767f4b2016-10-28 15:03:53 -0700850 dce2,
Aart Bik92685a82017-03-06 11:13:43 -0800851 side_effects1,
David Brazdil8993caf2015-12-07 10:04:40 +0000852 gvn,
853 licm,
854 induction,
855 bce,
Aart Bik281c6812016-08-26 11:31:48 -0700856 loop,
David Brazdil8993caf2015-12-07 10:04:40 +0000857 fold3, // evaluates code generated by dynamic bce
Aart Bik639cc8c2016-10-18 13:03:31 -0700858 simplify3,
Aart Bik92685a82017-03-06 11:13:43 -0800859 side_effects2,
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100860 lsa,
David Brazdil8993caf2015-12-07 10:04:40 +0000861 lse,
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800862 cha_guard,
Aart Bik2767f4b2016-10-28 15:03:53 -0700863 dce3,
Nicolas Geoffrayb813ca12017-02-16 22:08:29 +0000864 code_sinking,
David Brazdil8993caf2015-12-07 10:04:40 +0000865 // The codegen has a few assumptions that only the instruction simplifier
866 // can satisfy. For example, the code generator does not expect to see a
867 // HTypeConversion from a type to the same type.
Aart Bik639cc8c2016-10-18 13:03:31 -0700868 simplify4,
Igor Murashkindd018df2017-08-09 10:38:31 -0700869 cfre, // Eliminate constructor fences after code sinking to avoid
870 // complicated sinking logic to split a fence with many inputs.
David Brazdil8993caf2015-12-07 10:04:40 +0000871 };
872 RunOptimizations(optimizations2, arraysize(optimizations2), pass_observer);
David Brazdilbbd733e2015-08-18 17:48:17 +0100873
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700874 RunArchOptimizations(driver->GetInstructionSet(), graph, codegen, pass_observer);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000875}
876
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100877static ArenaVector<linker::LinkerPatch> EmitAndSortLinkerPatches(CodeGenerator* codegen) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100878 ArenaVector<linker::LinkerPatch> linker_patches(codegen->GetGraph()->GetAllocator()->Adapter());
Vladimir Marko58155012015-08-19 12:49:41 +0000879 codegen->EmitLinkerPatches(&linker_patches);
880
881 // Sort patches by literal offset. Required for .oat_patches encoding.
882 std::sort(linker_patches.begin(), linker_patches.end(),
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100883 [](const linker::LinkerPatch& lhs, const linker::LinkerPatch& rhs) {
Vladimir Marko58155012015-08-19 12:49:41 +0000884 return lhs.LiteralOffset() < rhs.LiteralOffset();
885 });
886
887 return linker_patches;
888}
889
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100890CompiledMethod* OptimizingCompiler::Emit(ArenaAllocator* allocator,
David Brazdil58282f42016-01-14 12:45:10 +0000891 CodeVectorAllocator* code_allocator,
892 CodeGenerator* codegen,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000893 CompilerDriver* compiler_driver,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000894 const DexFile::CodeItem* code_item_for_osr_check) const {
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100895 ArenaVector<linker::LinkerPatch> linker_patches = EmitAndSortLinkerPatches(codegen);
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100896 ArenaVector<uint8_t> stack_map(allocator->Adapter(kArenaAllocStackMaps));
897 ArenaVector<uint8_t> method_info(allocator->Adapter(kArenaAllocStackMaps));
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700898 size_t stack_map_size = 0;
899 size_t method_info_size = 0;
900 codegen->ComputeStackMapAndMethodInfoSize(&stack_map_size, &method_info_size);
901 stack_map.resize(stack_map_size);
902 method_info.resize(method_info_size);
903 codegen->BuildStackMaps(MemoryRegion(stack_map.data(), stack_map.size()),
904 MemoryRegion(method_info.data(), method_info.size()),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000905 code_item_for_osr_check);
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000906
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100907 CompiledMethod* compiled_method = CompiledMethod::SwapAllocCompiledMethod(
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000908 compiler_driver,
909 codegen->GetInstructionSet(),
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000910 ArrayRef<const uint8_t>(code_allocator->GetMemory()),
Roland Levillainaa9b7c42015-02-17 15:40:09 +0000911 // Follow Quick's behavior and set the frame size to zero if it is
912 // considered "empty" (see the definition of
913 // art::CodeGenerator::HasEmptyFrame).
914 codegen->HasEmptyFrame() ? 0 : codegen->GetFrameSize(),
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000915 codegen->GetCoreSpillMask(),
Nicolas Geoffrayd97dc402015-01-22 13:50:01 +0000916 codegen->GetFpuSpillMask(),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700917 ArrayRef<const uint8_t>(method_info),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100918 ArrayRef<const uint8_t>(stack_map),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100919 ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data()),
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100920 ArrayRef<const linker::LinkerPatch>(linker_patches));
Mathieu Chartiered150002015-08-28 11:16:54 -0700921
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100922 return compiled_method;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000923}
924
Vladimir Markoca6fff82017-10-03 14:49:14 +0100925CodeGenerator* OptimizingCompiler::TryCompile(ArenaAllocator* allocator,
926 ArenaStack* arena_stack,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000927 CodeVectorAllocator* code_allocator,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000928 const DexCompilationUnit& dex_compilation_unit,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000929 ArtMethod* method,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000930 bool osr,
931 VariableSizedHandleScope* handles) const {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000932 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kAttemptCompilation);
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000933 CompilerDriver* compiler_driver = GetCompilerDriver();
934 InstructionSet instruction_set = compiler_driver->GetInstructionSet();
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000935 const DexFile& dex_file = *dex_compilation_unit.GetDexFile();
936 uint32_t method_idx = dex_compilation_unit.GetDexMethodIndex();
937 const DexFile::CodeItem* code_item = dex_compilation_unit.GetCodeItem();
Calin Juravlecff8cc72015-10-09 12:03:24 +0100938
Roland Levillain3b359c72015-11-17 19:35:12 +0000939 // Always use the Thumb-2 assembler: some runtime functionality
940 // (like implicit stack overflow checks) assume Thumb-2.
Vladimir Marko33bff252017-11-01 14:35:42 +0000941 DCHECK_NE(instruction_set, InstructionSet::kArm);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100942
943 // Do not attempt to compile on architectures we do not support.
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000944 if (!IsInstructionSetSupported(instruction_set)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700945 MaybeRecordStat(compilation_stats_.get(),
946 MethodCompilationStat::kNotCompiledUnsupportedIsa);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100947 return nullptr;
948 }
949
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000950 if (Compiler::IsPathologicalCase(*code_item, method_idx, dex_file)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700951 MaybeRecordStat(compilation_stats_.get(),
952 MethodCompilationStat::kNotCompiledPathological);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000953 return nullptr;
954 }
955
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000956 // Implementation of the space filter: do not compile a code item whose size in
Nicolas Geoffray432bf3d2015-07-17 11:11:09 +0100957 // code units is bigger than 128.
958 static constexpr size_t kSpaceFilterOptimizingThreshold = 128;
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000959 const CompilerOptions& compiler_options = compiler_driver->GetCompilerOptions();
Andreas Gampe29d38e72016-03-23 15:31:51 +0000960 if ((compiler_options.GetCompilerFilter() == CompilerFilter::kSpace)
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000961 && (code_item->insns_size_in_code_units_ > kSpaceFilterOptimizingThreshold)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700962 MaybeRecordStat(compilation_stats_.get(),
963 MethodCompilationStat::kNotCompiledSpaceFilter);
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000964 return nullptr;
965 }
966
Vladimir Markoca6fff82017-10-03 14:49:14 +0100967 HGraph* graph = new (allocator) HGraph(
968 allocator,
969 arena_stack,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000970 dex_file,
971 method_idx,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000972 compiler_driver->GetInstructionSet(),
973 kInvalidInvokeType,
974 compiler_driver->GetCompilerOptions().GetDebuggable(),
975 osr);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000976
David Brazdilbadd8262016-02-02 16:28:56 +0000977 const uint8_t* interpreter_metadata = nullptr;
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000978 // For AOT compilation, we may not get a method, for example if its class is erroneous.
979 // JIT should always have a method.
980 DCHECK(Runtime::Current()->IsAotCompiler() || method != nullptr);
981 if (method != nullptr) {
982 graph->SetArtMethod(method);
983 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000984 interpreter_metadata = method->GetQuickenedInfo();
David Brazdilbadd8262016-02-02 16:28:56 +0000985 }
986
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000987 std::unique_ptr<CodeGenerator> codegen(
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000988 CodeGenerator::Create(graph,
989 instruction_set,
990 *compiler_driver->GetInstructionSetFeatures(),
Calin Juravle2ae48182016-03-16 14:05:09 +0000991 compiler_driver->GetCompilerOptions(),
992 compilation_stats_.get()));
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000993 if (codegen.get() == nullptr) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700994 MaybeRecordStat(compilation_stats_.get(),
995 MethodCompilationStat::kNotCompiledNoCodegen);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000996 return nullptr;
997 }
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100998 codegen->GetAssembler()->cfi().SetEnabled(
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000999 compiler_driver->GetCompilerOptions().GenerateAnyDebugInfo());
Nicolas Geoffray787c3072014-03-17 10:20:19 +00001000
David Brazdil69ba7b72015-06-23 18:27:30 +01001001 PassObserver pass_observer(graph,
David Brazdil69ba7b72015-06-23 18:27:30 +01001002 codegen.get(),
1003 visualizer_output_.get(),
Andreas Gampea0d81af2016-10-27 12:04:57 -07001004 compiler_driver,
1005 dump_mutex_);
David Brazdil5e8b1372015-01-23 14:39:08 +00001006
David Brazdil809658e2015-02-05 11:34:02 +00001007 {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001008 VLOG(compiler) << "Building " << pass_observer.GetMethodName();
1009 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
1010 HGraphBuilder builder(graph,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001011 code_item,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001012 &dex_compilation_unit,
1013 &dex_compilation_unit,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001014 compiler_driver,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001015 codegen.get(),
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001016 compilation_stats_.get(),
1017 interpreter_metadata,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001018 handles);
1019 GraphAnalysisResult result = builder.BuildGraph();
1020 if (result != kAnalysisSuccess) {
1021 switch (result) {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001022 case kAnalysisSkipped: {
1023 MaybeRecordStat(compilation_stats_.get(),
1024 MethodCompilationStat::kNotCompiledSkipped);
1025 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001026 break;
Igor Murashkin1e065a52017-08-09 13:20:34 -07001027 case kAnalysisInvalidBytecode: {
1028 MaybeRecordStat(compilation_stats_.get(),
1029 MethodCompilationStat::kNotCompiledInvalidBytecode);
1030 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001031 break;
Igor Murashkin1e065a52017-08-09 13:20:34 -07001032 case kAnalysisFailThrowCatchLoop: {
1033 MaybeRecordStat(compilation_stats_.get(),
1034 MethodCompilationStat::kNotCompiledThrowCatchLoop);
1035 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001036 break;
Igor Murashkin1e065a52017-08-09 13:20:34 -07001037 case kAnalysisFailAmbiguousArrayOp: {
1038 MaybeRecordStat(compilation_stats_.get(),
1039 MethodCompilationStat::kNotCompiledAmbiguousArrayOp);
1040 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001041 break;
1042 case kAnalysisSuccess:
1043 UNREACHABLE();
David Brazdil809658e2015-02-05 11:34:02 +00001044 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001045 pass_observer.SetGraphInBadState();
1046 return nullptr;
Nicolas Geoffrayf5370122014-12-02 11:51:19 +00001047 }
David Brazdilbadd8262016-02-02 16:28:56 +00001048 }
Vladimir Markof9f64412015-09-02 14:05:49 +01001049
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001050 RunOptimizations(graph,
1051 codegen.get(),
1052 compiler_driver,
1053 dex_compilation_unit,
1054 &pass_observer,
1055 handles);
1056
1057 RegisterAllocator::Strategy regalloc_strategy =
1058 compiler_options.GetRegisterAllocationStrategy();
Igor Murashkin1e065a52017-08-09 13:20:34 -07001059 AllocateRegisters(graph,
1060 codegen.get(),
1061 &pass_observer,
Igor Murashkin6ef45672017-08-08 13:59:55 -07001062 regalloc_strategy,
1063 compilation_stats_.get());
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001064
1065 codegen->Compile(code_allocator);
1066 pass_observer.DumpDisassembly();
1067
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001068 return codegen.release();
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001069}
1070
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001071CodeGenerator* OptimizingCompiler::TryCompileIntrinsic(
1072 ArenaAllocator* allocator,
1073 ArenaStack* arena_stack,
1074 CodeVectorAllocator* code_allocator,
1075 const DexCompilationUnit& dex_compilation_unit,
1076 ArtMethod* method,
1077 VariableSizedHandleScope* handles) const {
1078 CompilerDriver* compiler_driver = GetCompilerDriver();
1079 InstructionSet instruction_set = compiler_driver->GetInstructionSet();
1080 const DexFile& dex_file = *dex_compilation_unit.GetDexFile();
1081 uint32_t method_idx = dex_compilation_unit.GetDexMethodIndex();
1082
1083 // Always use the Thumb-2 assembler: some runtime functionality
1084 // (like implicit stack overflow checks) assume Thumb-2.
1085 DCHECK_NE(instruction_set, InstructionSet::kArm);
1086
1087 // Do not attempt to compile on architectures we do not support.
1088 if (!IsInstructionSetSupported(instruction_set)) {
1089 MaybeRecordStat(compilation_stats_.get(),
1090 MethodCompilationStat::kNotCompiledUnsupportedIsa);
1091 return nullptr;
1092 }
1093
1094 HGraph* graph = new (allocator) HGraph(
1095 allocator,
1096 arena_stack,
1097 dex_file,
1098 method_idx,
1099 compiler_driver->GetInstructionSet(),
1100 kInvalidInvokeType,
1101 compiler_driver->GetCompilerOptions().GetDebuggable(),
1102 /* osr */ false);
1103
1104 DCHECK(Runtime::Current()->IsAotCompiler());
1105 DCHECK(method != nullptr);
1106 graph->SetArtMethod(method);
1107
1108 std::unique_ptr<CodeGenerator> codegen(
1109 CodeGenerator::Create(graph,
1110 instruction_set,
1111 *compiler_driver->GetInstructionSetFeatures(),
1112 compiler_driver->GetCompilerOptions(),
1113 compilation_stats_.get()));
1114 if (codegen.get() == nullptr) {
1115 MaybeRecordStat(compilation_stats_.get(),
1116 MethodCompilationStat::kNotCompiledNoCodegen);
1117 return nullptr;
1118 }
1119 codegen->GetAssembler()->cfi().SetEnabled(
1120 compiler_driver->GetCompilerOptions().GenerateAnyDebugInfo());
1121
1122 PassObserver pass_observer(graph,
1123 codegen.get(),
1124 visualizer_output_.get(),
1125 compiler_driver,
1126 dump_mutex_);
1127
1128 {
1129 VLOG(compiler) << "Building intrinsic graph " << pass_observer.GetMethodName();
1130 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
1131 HGraphBuilder builder(graph,
1132 /* code_item */ nullptr,
1133 &dex_compilation_unit,
1134 &dex_compilation_unit,
1135 compiler_driver,
1136 codegen.get(),
1137 compilation_stats_.get(),
1138 /* interpreter_metadata */ nullptr,
1139 handles);
1140 builder.BuildIntrinsicGraph(method);
1141 }
1142
1143 OptimizingCompilerStats* stats = compilation_stats_.get();
1144 InstructionSimplifier* simplify = new (allocator) InstructionSimplifier(
1145 graph, codegen.get(), compiler_driver, stats);
1146 IntrinsicsRecognizer* intrinsics = new (allocator) IntrinsicsRecognizer(graph, stats);
1147
1148 HOptimization* optimizations[] = {
1149 intrinsics,
1150 // Some intrinsics are converted to HIR by the simplifier and the codegen also
1151 // has a few assumptions that only the instruction simplifier can satisfy.
1152 simplify,
1153 };
1154 RunOptimizations(optimizations, arraysize(optimizations), &pass_observer);
1155
1156 RunArchOptimizations(compiler_driver->GetInstructionSet(), graph, codegen.get(), &pass_observer);
1157
1158 AllocateRegisters(graph,
1159 codegen.get(),
1160 &pass_observer,
1161 compiler_driver->GetCompilerOptions().GetRegisterAllocationStrategy(),
1162 compilation_stats_.get());
1163 if (!codegen->IsLeafMethod()) {
1164 VLOG(compiler) << "Intrinsic method is not leaf: " << method->GetIntrinsic()
1165 << " " << graph->PrettyMethod();
1166 return nullptr;
1167 }
1168
1169 codegen->Compile(code_allocator);
1170 pass_observer.DumpDisassembly();
1171
1172 VLOG(compiler) << "Compiled intrinsic: " << method->GetIntrinsic()
1173 << " " << graph->PrettyMethod();
1174 return codegen.release();
1175}
1176
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001177CompiledMethod* OptimizingCompiler::Compile(const DexFile::CodeItem* code_item,
1178 uint32_t access_flags,
1179 InvokeType invoke_type,
1180 uint16_t class_def_idx,
1181 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001182 Handle<mirror::ClassLoader> jclass_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -07001183 const DexFile& dex_file,
1184 Handle<mirror::DexCache> dex_cache) const {
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001185 CompilerDriver* compiler_driver = GetCompilerDriver();
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001186 CompiledMethod* compiled_method = nullptr;
1187 Runtime* runtime = Runtime::Current();
1188 DCHECK(runtime->IsAotCompiler());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001189 const VerifiedMethod* verified_method = compiler_driver->GetVerifiedMethod(&dex_file, method_idx);
1190 DCHECK(!verified_method->HasRuntimeThrow());
Vladimir Markoca6fff82017-10-03 14:49:14 +01001191 if (compiler_driver->IsMethodVerifiedWithoutFailures(method_idx, class_def_idx, dex_file) ||
1192 verifier::CanCompilerHandleVerificationFailure(
1193 verified_method->GetEncounteredVerificationFailures())) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001194 ArenaAllocator allocator(runtime->GetArenaPool());
1195 ArenaStack arena_stack(runtime->GetArenaPool());
Vladimir Markoca6fff82017-10-03 14:49:14 +01001196 CodeVectorAllocator code_allocator(&allocator);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001197 std::unique_ptr<CodeGenerator> codegen;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001198 bool compiled_intrinsic = false;
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001199 {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001200 DexCompilationUnit dex_compilation_unit(
1201 jclass_loader,
1202 runtime->GetClassLinker(),
1203 dex_file,
1204 code_item,
1205 class_def_idx,
1206 method_idx,
1207 access_flags,
1208 /* verified_method */ nullptr, // Not needed by the Optimizing compiler.
1209 dex_cache);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001210 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001211 ArtMethod* method = compiler_driver->ResolveMethod(
1212 soa, dex_cache, jclass_loader, &dex_compilation_unit, method_idx, invoke_type);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001213 VariableSizedHandleScope handles(soa.Self());
1214 // Go to native so that we don't block GC during compilation.
1215 ScopedThreadSuspension sts(soa.Self(), kNative);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001216 if (method != nullptr && UNLIKELY(method->IsIntrinsic())) {
1217 DCHECK(compiler_driver->GetCompilerOptions().IsBootImage());
1218 codegen.reset(
1219 TryCompileIntrinsic(&allocator,
1220 &arena_stack,
1221 &code_allocator,
1222 dex_compilation_unit,
1223 method,
1224 &handles));
1225 if (codegen != nullptr) {
1226 compiled_intrinsic = true;
1227 }
1228 }
1229 if (codegen == nullptr) {
1230 codegen.reset(
1231 TryCompile(&allocator,
1232 &arena_stack,
1233 &code_allocator,
1234 dex_compilation_unit,
1235 method,
1236 /* osr */ false,
1237 &handles));
1238 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001239 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001240 if (codegen.get() != nullptr) {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001241 MaybeRecordStat(compilation_stats_.get(),
1242 MethodCompilationStat::kCompiled);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001243 compiled_method = Emit(&allocator,
1244 &code_allocator,
1245 codegen.get(),
1246 compiler_driver,
1247 compiled_intrinsic ? nullptr : code_item);
1248 if (compiled_intrinsic) {
1249 compiled_method->MarkAsIntrinsic();
1250 }
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001251
1252 if (kArenaAllocatorCountAllocations) {
Vladimir Marko174b2e22017-10-12 13:34:49 +01001253 codegen.reset(); // Release codegen's ScopedArenaAllocator for memory accounting.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001254 size_t total_allocated = allocator.BytesAllocated() + arena_stack.PeakBytesAllocated();
1255 if (total_allocated > kArenaAllocatorMemoryReportThreshold) {
1256 MemStats mem_stats(allocator.GetMemStats());
1257 MemStats peak_stats(arena_stack.GetPeakStats());
Vladimir Marko69d310e2017-10-09 14:12:23 +01001258 LOG(INFO) << "Used " << total_allocated << " bytes of arena memory for compiling "
1259 << dex_file.PrettyMethod(method_idx)
Vladimir Markoca6fff82017-10-03 14:49:14 +01001260 << "\n" << Dumpable<MemStats>(mem_stats)
1261 << "\n" << Dumpable<MemStats>(peak_stats);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001262 }
1263 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001264 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001265 } else {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001266 MethodCompilationStat method_stat;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001267 if (compiler_driver->GetCompilerOptions().VerifyAtRuntime()) {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001268 method_stat = MethodCompilationStat::kNotCompiledVerifyAtRuntime;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001269 } else {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001270 method_stat = MethodCompilationStat::kNotCompiledVerificationError;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001271 }
Igor Murashkin1e065a52017-08-09 13:20:34 -07001272 MaybeRecordStat(compilation_stats_.get(), method_stat);
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001273 }
1274
Calin Juravlecff8cc72015-10-09 12:03:24 +01001275 if (kIsDebugBuild &&
1276 IsCompilingWithCoreImage() &&
Goran Jakovljevic9c4f0d8f2017-04-05 16:27:25 +02001277 IsInstructionSetSupported(compiler_driver->GetInstructionSet())) {
Roland Levillain0d5a2812015-11-13 10:07:31 +00001278 // For testing purposes, we put a special marker on method names
Goran Jakovljevic9c4f0d8f2017-04-05 16:27:25 +02001279 // that should be compiled with this compiler (when the
1280 // instruction set is supported). This makes sure we're not
Roland Levillain0d5a2812015-11-13 10:07:31 +00001281 // regressing.
David Sehr709b0702016-10-13 09:12:37 -07001282 std::string method_name = dex_file.PrettyMethod(method_idx);
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001283 bool shouldCompile = method_name.find("$opt$") != std::string::npos;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001284 DCHECK((compiled_method != nullptr) || !shouldCompile) << "Didn't compile " << method_name;
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001285 }
1286
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001287 return compiled_method;
1288}
1289
1290CompiledMethod* OptimizingCompiler::JniCompile(uint32_t access_flags,
1291 uint32_t method_idx,
1292 const DexFile& dex_file,
1293 Handle<mirror::DexCache> dex_cache) const {
1294 if (GetCompilerDriver()->GetCompilerOptions().IsBootImage()) {
1295 ScopedObjectAccess soa(Thread::Current());
1296 Runtime* runtime = Runtime::Current();
1297 ArtMethod* method = runtime->GetClassLinker()->LookupResolvedMethod(
1298 method_idx, dex_cache.Get(), /* class_loader */ nullptr);
1299 if (method != nullptr && UNLIKELY(method->IsIntrinsic())) {
1300 ScopedNullHandle<mirror::ClassLoader> class_loader; // null means boot class path loader.
1301 DexCompilationUnit dex_compilation_unit(
1302 class_loader,
1303 runtime->GetClassLinker(),
1304 dex_file,
1305 /* code_item */ nullptr,
1306 /* class_def_idx */ DexFile::kDexNoIndex16,
1307 method_idx,
1308 access_flags,
1309 /* verified_method */ nullptr,
1310 dex_cache);
1311 ArenaAllocator allocator(runtime->GetArenaPool());
1312 ArenaStack arena_stack(runtime->GetArenaPool());
1313 CodeVectorAllocator code_allocator(&allocator);
1314 VariableSizedHandleScope handles(soa.Self());
1315 // Go to native so that we don't block GC during compilation.
1316 ScopedThreadSuspension sts(soa.Self(), kNative);
1317 std::unique_ptr<CodeGenerator> codegen(
1318 TryCompileIntrinsic(&allocator,
1319 &arena_stack,
1320 &code_allocator,
1321 dex_compilation_unit,
1322 method,
1323 &handles));
1324 if (codegen != nullptr) {
1325 CompiledMethod* compiled_method = Emit(&allocator,
1326 &code_allocator,
1327 codegen.get(),
1328 GetCompilerDriver(),
1329 /* code_item_for_osr_check */ nullptr);
1330 compiled_method->MarkAsIntrinsic();
1331 return compiled_method;
1332 }
1333 }
1334 }
1335
1336 return ArtQuickJniCompileMethod(GetCompilerDriver(),
1337 access_flags,
1338 method_idx,
1339 dex_file);
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001340}
1341
Andreas Gampe53c913b2014-08-12 23:19:23 -07001342Compiler* CreateOptimizingCompiler(CompilerDriver* driver) {
1343 return new OptimizingCompiler(driver);
1344}
1345
Nicolas Geoffray335005e2015-06-25 10:01:47 +01001346bool IsCompilingWithCoreImage() {
1347 const std::string& image = Runtime::Current()->GetImageLocation();
Roland Levillain2b03a1f2017-06-06 16:09:59 +01001348 return CompilerDriver::IsCoreImageFilename(image);
Nicolas Geoffray335005e2015-06-25 10:01:47 +01001349}
1350
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001351bool EncodeArtMethodInInlineInfo(ArtMethod* method ATTRIBUTE_UNUSED) {
1352 // Note: the runtime is null only for unit testing.
1353 return Runtime::Current() == nullptr || !Runtime::Current()->IsAotCompiler();
1354}
1355
1356bool CanEncodeInlinedMethodInStackMap(const DexFile& caller_dex_file, ArtMethod* callee) {
1357 if (!Runtime::Current()->IsAotCompiler()) {
1358 // JIT can always encode methods in stack maps.
1359 return true;
1360 }
1361 if (IsSameDexFile(caller_dex_file, *callee->GetDexFile())) {
1362 return true;
1363 }
1364 // TODO(ngeoffray): Support more AOT cases for inlining:
1365 // - methods in multidex
1366 // - methods in boot image for on-device non-PIC compilation.
1367 return false;
1368}
1369
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001370bool OptimizingCompiler::JitCompile(Thread* self,
1371 jit::JitCodeCache* code_cache,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001372 ArtMethod* method,
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001373 bool osr,
1374 jit::JitLogger* jit_logger) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001375 StackHandleScope<3> hs(self);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001376 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1377 method->GetDeclaringClass()->GetClassLoader()));
1378 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001379 DCHECK(method->IsCompilable());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001380
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001381 const DexFile* dex_file = method->GetDexFile();
1382 const uint16_t class_def_idx = method->GetClassDefIndex();
1383 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
1384 const uint32_t method_idx = method->GetDexMethodIndex();
1385 const uint32_t access_flags = method->GetAccessFlags();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001386
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001387 Runtime* runtime = Runtime::Current();
1388 ArenaAllocator allocator(runtime->GetJitArenaPool());
Vladimir Markoca6fff82017-10-03 14:49:14 +01001389 ArenaStack arena_stack(Runtime::Current()->GetJitArenaPool());
1390 CodeVectorAllocator code_allocator(&allocator);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001391 VariableSizedHandleScope handles(self);
1392
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001393 std::unique_ptr<CodeGenerator> codegen;
1394 {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001395 DexCompilationUnit dex_compilation_unit(
1396 class_loader,
1397 runtime->GetClassLinker(),
1398 *dex_file,
1399 code_item,
1400 class_def_idx,
1401 method_idx,
1402 access_flags,
1403 /* verified_method */ nullptr,
1404 dex_cache);
1405
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001406 // Go to native so that we don't block GC during compilation.
1407 ScopedThreadSuspension sts(self, kNative);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001408 codegen.reset(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001409 TryCompile(&allocator,
1410 &arena_stack,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001411 &code_allocator,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001412 dex_compilation_unit,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +00001413 method,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001414 osr,
1415 &handles));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001416 if (codegen.get() == nullptr) {
1417 return false;
1418 }
1419 }
1420
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001421 size_t stack_map_size = 0;
1422 size_t method_info_size = 0;
1423 codegen->ComputeStackMapAndMethodInfoSize(&stack_map_size, &method_info_size);
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001424 size_t number_of_roots = codegen->GetNumberOfJitRoots();
1425 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1426 // We allocate an object array to ensure the JIT roots that we will collect in EmitJitRoots
1427 // will be visible by the GC between EmitLiterals and CommitCode. Once CommitCode is
1428 // executed, this array is not needed.
1429 Handle<mirror::ObjectArray<mirror::Object>> roots(
1430 hs.NewHandle(mirror::ObjectArray<mirror::Object>::Alloc(
1431 self, class_linker->GetClassRoot(ClassLinker::kObjectArrayClass), number_of_roots)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001432 if (roots == nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001433 // Out of memory, just clear the exception to avoid any Java exception uncaught problems.
1434 DCHECK(self->IsExceptionPending());
1435 self->ClearException();
1436 return false;
1437 }
1438 uint8_t* stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001439 uint8_t* method_info_data = nullptr;
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001440 uint8_t* roots_data = nullptr;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001441 uint32_t data_size = code_cache->ReserveData(self,
1442 stack_map_size,
1443 method_info_size,
1444 number_of_roots,
1445 method,
1446 &stack_map_data,
1447 &method_info_data,
1448 &roots_data);
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001449 if (stack_map_data == nullptr || roots_data == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001450 return false;
1451 }
Igor Murashkin1e065a52017-08-09 13:20:34 -07001452 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiled);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001453 codegen->BuildStackMaps(MemoryRegion(stack_map_data, stack_map_size),
1454 MemoryRegion(method_info_data, method_info_size),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001455 code_item);
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00001456 codegen->EmitJitRoots(code_allocator.GetData(), roots, roots_data);
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001457
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001458 const void* code = code_cache->CommitCode(
1459 self,
1460 method,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001461 stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001462 method_info_data,
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001463 roots_data,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001464 codegen->HasEmptyFrame() ? 0 : codegen->GetFrameSize(),
1465 codegen->GetCoreSpillMask(),
1466 codegen->GetFpuSpillMask(),
1467 code_allocator.GetMemory().data(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001468 code_allocator.GetSize(),
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001469 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001470 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -07001471 roots,
1472 codegen->GetGraph()->HasShouldDeoptimizeFlag(),
1473 codegen->GetGraph()->GetCHASingleImplementationList());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001474
1475 if (code == nullptr) {
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001476 code_cache->ClearData(self, stack_map_data, roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001477 return false;
1478 }
1479
David Srbecky91cc06c2016-03-07 16:13:58 +00001480 const CompilerOptions& compiler_options = GetCompilerDriver()->GetCompilerOptions();
1481 if (compiler_options.GetGenerateDebugInfo()) {
David Srbecky5cc349f2015-12-18 15:04:48 +00001482 const auto* method_header = reinterpret_cast<const OatQuickMethodHeader*>(code);
1483 const uintptr_t code_address = reinterpret_cast<uintptr_t>(method_header->GetCode());
Vladimir Marko1b404a82017-09-01 13:35:26 +01001484 debug::MethodDebugInfo info = {};
1485 DCHECK(info.trampoline_name.empty());
David Srbecky197160d2016-03-07 17:33:57 +00001486 info.dex_file = dex_file;
1487 info.class_def_index = class_def_idx;
1488 info.dex_method_index = method_idx;
1489 info.access_flags = access_flags;
1490 info.code_item = code_item;
1491 info.isa = codegen->GetInstructionSet();
1492 info.deduped = false;
1493 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1494 info.is_optimized = true;
1495 info.is_code_address_text_relative = false;
1496 info.code_address = code_address;
1497 info.code_size = code_allocator.GetSize();
1498 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
1499 info.code_info = stack_map_size == 0 ? nullptr : stack_map_data;
1500 info.cfi = ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data());
Vladimir Marko93205e32016-04-13 11:59:46 +01001501 std::vector<uint8_t> elf_file = debug::WriteDebugElfFileForMethods(
David Srbecky5d811202016-03-08 13:21:22 +00001502 GetCompilerDriver()->GetInstructionSet(),
1503 GetCompilerDriver()->GetInstructionSetFeatures(),
David Srbeckyfe736b72016-03-09 11:44:44 +00001504 ArrayRef<const debug::MethodDebugInfo>(&info, 1));
Vladimir Marko93205e32016-04-13 11:59:46 +01001505 CreateJITCodeEntryForAddress(code_address, std::move(elf_file));
David Srbecky5cc349f2015-12-18 15:04:48 +00001506 }
1507
Vladimir Markoca6fff82017-10-03 14:49:14 +01001508 Runtime::Current()->GetJit()->AddMemoryUsage(method, allocator.BytesUsed());
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001509 if (jit_logger != nullptr) {
1510 jit_logger->WriteLog(code, code_allocator.GetSize(), method);
1511 }
Nicolas Geoffraya4f81542016-03-08 16:57:48 +00001512
Vladimir Marko174b2e22017-10-12 13:34:49 +01001513 if (kArenaAllocatorCountAllocations) {
1514 codegen.reset(); // Release codegen's ScopedArenaAllocator for memory accounting.
1515 size_t total_allocated = allocator.BytesAllocated() + arena_stack.PeakBytesAllocated();
1516 if (total_allocated > kArenaAllocatorMemoryReportThreshold) {
1517 MemStats mem_stats(allocator.GetMemStats());
1518 MemStats peak_stats(arena_stack.GetPeakStats());
1519 LOG(INFO) << "Used " << total_allocated << " bytes of arena memory for compiling "
1520 << dex_file->PrettyMethod(method_idx)
1521 << "\n" << Dumpable<MemStats>(mem_stats)
1522 << "\n" << Dumpable<MemStats>(peak_stats);
1523 }
1524 }
1525
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001526 return true;
1527}
1528
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001529} // namespace art