blob: 1d3fcf30024fddbc7bae4f78e9154a555a10e72f [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
Mathieu Chartiere401d142015-04-22 13:56:20 -070025#include "art_method-inl.h"
Mathieu Chartierb666f482015-02-18 14:33:14 -080026#include "base/arena_allocator.h"
Vladimir Markof9f64412015-09-02 14:05:49 +010027#include "base/arena_containers.h"
David Brazdil5e8b1372015-01-23 14:39:08 +000028#include "base/dumpable.h"
Andreas Gampe85f1c572018-11-21 13:52:48 -080029#include "base/logging.h"
Vladimir Markoc90d7c72015-10-06 17:30:45 +000030#include "base/macros.h"
Andreas Gampea0d81af2016-10-27 12:04:57 -070031#include "base/mutex.h"
Vladimir Markoca6fff82017-10-03 14:49:14 +010032#include "base/scoped_arena_allocator.h"
David Brazdil5e8b1372015-01-23 14:39:08 +000033#include "base/timing_logger.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000034#include "builder.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010035#include "class_root.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000036#include "code_generator.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000037#include "compiled_method.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070038#include "compiler.h"
David Srbeckyc5bfa972016-02-05 15:49:10 +000039#include "debug/elf_debug_writer.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000040#include "debug/method_debug_info.h"
David Sehr9e734c72018-01-04 17:56:19 -080041#include "dex/dex_file_types.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010042#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000043#include "dex/verified_method.h"
Nicolas Geoffray9523a3e2015-07-17 11:51:28 +000044#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000045#include "driver/compiler_options.h"
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000046#include "driver/dex_compilation_unit.h"
David Brazdil69ba7b72015-06-23 18:27:30 +010047#include "graph_checker.h"
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010048#include "graph_visualizer.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000049#include "inliner.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000050#include "jit/debugger_interface.h"
Nicolas Geoffraya4f81542016-03-08 16:57:48 +000051#include "jit/jit.h"
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +000052#include "jit/jit_code_cache.h"
Nicolas Geoffray01db5f72017-07-19 15:05:49 +010053#include "jit/jit_logger.h"
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +000054#include "jni/quick/jni_compiler.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010055#include "linker/linker_patch.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000056#include "nodes.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000057#include "oat_quick_method_header.h"
Nicolas Geoffray26a25ef2014-09-30 13:54:09 +010058#include "prepare_for_register_allocation.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010059#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070060#include "register_allocator_linear_scan.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070061#include "select_generator.h"
Nicolas Geoffray31596742014-11-24 15:28:45 +000062#include "ssa_builder.h"
Nicolas Geoffray804d0932014-05-02 08:46:00 +010063#include "ssa_liveness_analysis.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000064#include "ssa_phi_elimination.h"
David Srbeckyafc97bc2018-07-05 08:14:35 +000065#include "stack_map_stream.h"
David Srbeckyc6b4dd82015-04-07 20:32:43 +010066#include "utils/assembler.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070067#include "verifier/verifier_compiler_binding.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000068
69namespace art {
70
Vladimir Marko3a40bf22016-03-22 16:26:33 +000071static constexpr size_t kArenaAllocatorMemoryReportThreshold = 8 * MB;
72
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -070073static constexpr const char* kPassNameSeparator = "$";
74
Nicolas Geoffray787c3072014-03-17 10:20:19 +000075/**
76 * Used by the code generator, to allocate the code in a vector.
77 */
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010078class CodeVectorAllocator final : public CodeAllocator {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000079 public:
Vladimir Markoe764d2e2017-10-05 14:35:55 +010080 explicit CodeVectorAllocator(ArenaAllocator* allocator)
Vladimir Markoca1e0382018-04-11 09:58:41 +000081 : memory_(allocator->Adapter(kArenaAllocCodeBuffer)) {}
Nicolas Geoffray787c3072014-03-17 10:20:19 +000082
Andreas Gampefa6a1b02018-09-07 08:11:55 -070083 uint8_t* Allocate(size_t size) override {
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000084 memory_.resize(size);
Nicolas Geoffray787c3072014-03-17 10:20:19 +000085 return &memory_[0];
86 }
87
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010088 ArrayRef<const uint8_t> GetMemory() const override { return ArrayRef<const uint8_t>(memory_); }
Nicolas Geoffray132d8362016-11-16 09:19:42 +000089 uint8_t* GetData() { return memory_.data(); }
Nicolas Geoffray787c3072014-03-17 10:20:19 +000090
91 private:
Vladimir Markof9f64412015-09-02 14:05:49 +010092 ArenaVector<uint8_t> memory_;
Nicolas Geoffray787c3072014-03-17 10:20:19 +000093
94 DISALLOW_COPY_AND_ASSIGN(CodeVectorAllocator);
95};
96
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010097/**
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010098 * Filter to apply to the visualizer. Methods whose name contain that filter will
David Brazdilee690a32014-12-01 17:04:16 +000099 * be dumped.
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100100 */
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700101static constexpr const char kStringFilter[] = "";
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100102
David Brazdil69ba7b72015-06-23 18:27:30 +0100103class PassScope;
David Brazdil809658e2015-02-05 11:34:02 +0000104
David Brazdil69ba7b72015-06-23 18:27:30 +0100105class PassObserver : public ValueObject {
David Brazdil5e8b1372015-01-23 14:39:08 +0000106 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100107 PassObserver(HGraph* graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100108 CodeGenerator* codegen,
109 std::ostream* visualizer_output,
Andreas Gampea0d81af2016-10-27 12:04:57 -0700110 CompilerDriver* compiler_driver,
111 Mutex& dump_mutex)
David Brazdil69ba7b72015-06-23 18:27:30 +0100112 : graph_(graph),
Aart Bika8360cd2018-05-02 16:07:51 -0700113 last_seen_graph_size_(0),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000114 cached_method_name_(),
Vladimir Marko2da52b02018-05-08 16:31:34 +0100115 timing_logger_enabled_(compiler_driver->GetCompilerOptions().GetDumpPassTimings()),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000116 timing_logger_(timing_logger_enabled_ ? GetMethodName() : "", true, true),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100117 disasm_info_(graph->GetAllocator()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700118 visualizer_oss_(),
119 visualizer_output_(visualizer_output),
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000120 visualizer_enabled_(!compiler_driver->GetCompilerOptions().GetDumpCfgFileName().empty()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700121 visualizer_(&visualizer_oss_, graph, *codegen),
122 visualizer_dump_mutex_(dump_mutex),
David Brazdil69ba7b72015-06-23 18:27:30 +0100123 graph_in_bad_state_(false) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700124 if (timing_logger_enabled_ || visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000125 if (!IsVerboseMethod(compiler_driver, GetMethodName())) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700126 timing_logger_enabled_ = visualizer_enabled_ = false;
127 }
128 if (visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000129 visualizer_.PrintHeader(GetMethodName());
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700130 codegen->SetDisassemblyInformation(&disasm_info_);
131 }
David Brazdil62e074f2015-04-07 18:09:37 +0100132 }
David Brazdil5e8b1372015-01-23 14:39:08 +0000133 }
134
David Brazdil69ba7b72015-06-23 18:27:30 +0100135 ~PassObserver() {
David Brazdil5e8b1372015-01-23 14:39:08 +0000136 if (timing_logger_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000137 LOG(INFO) << "TIMINGS " << GetMethodName();
David Brazdil5e8b1372015-01-23 14:39:08 +0000138 LOG(INFO) << Dumpable<TimingLogger>(timing_logger_);
139 }
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000140 DCHECK(visualizer_oss_.str().empty());
David Brazdil5e8b1372015-01-23 14:39:08 +0000141 }
142
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000143 void DumpDisassembly() REQUIRES(!visualizer_dump_mutex_) {
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100144 if (visualizer_enabled_) {
145 visualizer_.DumpGraphWithDisassembly();
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000146 FlushVisualizer();
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100147 }
148 }
149
David Brazdil69ba7b72015-06-23 18:27:30 +0100150 void SetGraphInBadState() { graph_in_bad_state_ = true; }
151
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000152 const char* GetMethodName() {
153 // PrettyMethod() is expensive, so we delay calling it until we actually have to.
154 if (cached_method_name_.empty()) {
David Sehr709b0702016-10-13 09:12:37 -0700155 cached_method_name_ = graph_->GetDexFile().PrettyMethod(graph_->GetMethodIdx());
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000156 }
157 return cached_method_name_.c_str();
158 }
159
David Brazdil5e8b1372015-01-23 14:39:08 +0000160 private:
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000161 void StartPass(const char* pass_name) REQUIRES(!visualizer_dump_mutex_) {
Wojciech Staszkiewicze7060702016-08-16 17:31:19 -0700162 VLOG(compiler) << "Starting pass: " << pass_name;
David Brazdil809658e2015-02-05 11:34:02 +0000163 // Dump graph first, then start timer.
164 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100165 visualizer_.DumpGraph(pass_name, /* is_after_pass */ false, graph_in_bad_state_);
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000166 FlushVisualizer();
David Brazdil809658e2015-02-05 11:34:02 +0000167 }
168 if (timing_logger_enabled_) {
169 timing_logger_.StartTiming(pass_name);
170 }
171 }
172
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000173 void FlushVisualizer() REQUIRES(!visualizer_dump_mutex_) {
174 MutexLock mu(Thread::Current(), visualizer_dump_mutex_);
175 *visualizer_output_ << visualizer_oss_.str();
176 visualizer_output_->flush();
177 visualizer_oss_.str("");
178 visualizer_oss_.clear();
179 }
180
Aart Bika8360cd2018-05-02 16:07:51 -0700181 void EndPass(const char* pass_name, bool pass_change) REQUIRES(!visualizer_dump_mutex_) {
David Brazdil809658e2015-02-05 11:34:02 +0000182 // Pause timer first, then dump graph.
183 if (timing_logger_enabled_) {
184 timing_logger_.EndTiming();
185 }
186 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100187 visualizer_.DumpGraph(pass_name, /* is_after_pass */ true, graph_in_bad_state_);
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000188 FlushVisualizer();
David Brazdil809658e2015-02-05 11:34:02 +0000189 }
David Brazdil69ba7b72015-06-23 18:27:30 +0100190
191 // Validate the HGraph if running in debug mode.
192 if (kIsDebugBuild) {
193 if (!graph_in_bad_state_) {
David Brazdilbadd8262016-02-02 16:28:56 +0000194 GraphChecker checker(graph_);
Aart Bika8360cd2018-05-02 16:07:51 -0700195 last_seen_graph_size_ = checker.Run(pass_change, last_seen_graph_size_);
David Brazdilbadd8262016-02-02 16:28:56 +0000196 if (!checker.IsValid()) {
197 LOG(FATAL) << "Error after " << pass_name << ": " << Dumpable<GraphChecker>(checker);
David Brazdil69ba7b72015-06-23 18:27:30 +0100198 }
199 }
200 }
David Brazdil809658e2015-02-05 11:34:02 +0000201 }
202
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700203 static bool IsVerboseMethod(CompilerDriver* compiler_driver, const char* method_name) {
204 // Test an exact match to --verbose-methods. If verbose-methods is set, this overrides an
205 // empty kStringFilter matching all methods.
206 if (compiler_driver->GetCompilerOptions().HasVerboseMethods()) {
207 return compiler_driver->GetCompilerOptions().IsVerboseMethod(method_name);
208 }
209
210 // Test the kStringFilter sub-string. constexpr helper variable to silence unreachable-code
211 // warning when the string is empty.
212 constexpr bool kStringFilterEmpty = arraysize(kStringFilter) <= 1;
213 if (kStringFilterEmpty || strstr(method_name, kStringFilter) != nullptr) {
214 return true;
215 }
216
217 return false;
218 }
219
David Brazdil69ba7b72015-06-23 18:27:30 +0100220 HGraph* const graph_;
Aart Bika8360cd2018-05-02 16:07:51 -0700221 size_t last_seen_graph_size_;
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000222
223 std::string cached_method_name_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000224
225 bool timing_logger_enabled_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000226 TimingLogger timing_logger_;
227
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100228 DisassemblyInformation disasm_info_;
229
Andreas Gampea0d81af2016-10-27 12:04:57 -0700230 std::ostringstream visualizer_oss_;
231 std::ostream* visualizer_output_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000232 bool visualizer_enabled_;
233 HGraphVisualizer visualizer_;
Andreas Gampea0d81af2016-10-27 12:04:57 -0700234 Mutex& visualizer_dump_mutex_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000235
David Brazdil69ba7b72015-06-23 18:27:30 +0100236 // Flag to be set by the compiler if the pass failed and the graph is not
237 // expected to validate.
238 bool graph_in_bad_state_;
David Brazdil809658e2015-02-05 11:34:02 +0000239
David Brazdil69ba7b72015-06-23 18:27:30 +0100240 friend PassScope;
241
242 DISALLOW_COPY_AND_ASSIGN(PassObserver);
David Brazdil5e8b1372015-01-23 14:39:08 +0000243};
244
David Brazdil69ba7b72015-06-23 18:27:30 +0100245class PassScope : public ValueObject {
David Brazdil809658e2015-02-05 11:34:02 +0000246 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100247 PassScope(const char *pass_name, PassObserver* pass_observer)
David Brazdil809658e2015-02-05 11:34:02 +0000248 : pass_name_(pass_name),
Aart Bika8360cd2018-05-02 16:07:51 -0700249 pass_change_(true), // assume change
David Brazdil69ba7b72015-06-23 18:27:30 +0100250 pass_observer_(pass_observer) {
251 pass_observer_->StartPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000252 }
253
Aart Bika8360cd2018-05-02 16:07:51 -0700254 void SetPassNotChanged() {
255 pass_change_ = false;
256 }
257
David Brazdil69ba7b72015-06-23 18:27:30 +0100258 ~PassScope() {
Aart Bika8360cd2018-05-02 16:07:51 -0700259 pass_observer_->EndPass(pass_name_, pass_change_);
David Brazdil809658e2015-02-05 11:34:02 +0000260 }
261
262 private:
263 const char* const pass_name_;
Aart Bika8360cd2018-05-02 16:07:51 -0700264 bool pass_change_;
David Brazdil69ba7b72015-06-23 18:27:30 +0100265 PassObserver* const pass_observer_;
David Brazdil809658e2015-02-05 11:34:02 +0000266};
267
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100268class OptimizingCompiler final : public Compiler {
Andreas Gampe53c913b2014-08-12 23:19:23 -0700269 public:
270 explicit OptimizingCompiler(CompilerDriver* driver);
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100271 ~OptimizingCompiler() override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700272
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100273 bool CanCompileMethod(uint32_t method_idx, const DexFile& dex_file) const override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700274
275 CompiledMethod* Compile(const DexFile::CodeItem* code_item,
276 uint32_t access_flags,
277 InvokeType invoke_type,
278 uint16_t class_def_idx,
279 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000280 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700281 const DexFile& dex_file,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100282 Handle<mirror::DexCache> dex_cache) const override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700283
Andreas Gampe53c913b2014-08-12 23:19:23 -0700284 CompiledMethod* JniCompile(uint32_t access_flags,
285 uint32_t method_idx,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000286 const DexFile& dex_file,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100287 Handle<mirror::DexCache> dex_cache) const override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700288
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100289 uintptr_t GetEntryPointOf(ArtMethod* method) const override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700290 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000291 return reinterpret_cast<uintptr_t>(method->GetEntryPointFromQuickCompiledCodePtrSize(
Vladimir Markoa0431112018-06-25 09:32:54 +0100292 InstructionSetPointerSize(GetCompilerDriver()->GetCompilerOptions().GetInstructionSet())));
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000293 }
Andreas Gampe53c913b2014-08-12 23:19:23 -0700294
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100295 void Init() override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700296
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100297 void UnInit() const override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700298
Nicolas Geoffray01db5f72017-07-19 15:05:49 +0100299 bool JitCompile(Thread* self,
300 jit::JitCodeCache* code_cache,
301 ArtMethod* method,
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100302 bool baseline,
Nicolas Geoffray01db5f72017-07-19 15:05:49 +0100303 bool osr,
304 jit::JitLogger* jit_logger)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100305 override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700306 REQUIRES_SHARED(Locks::mutator_lock_);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000307
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700308 private:
Aart Bik24773202018-04-26 10:28:51 -0700309 bool RunOptimizations(HGraph* graph,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700310 CodeGenerator* codegen,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800311 const DexCompilationUnit& dex_compilation_unit,
312 PassObserver* pass_observer,
313 VariableSizedHandleScope* handles,
314 const OptimizationDef definitions[],
315 size_t length) const {
316 // Convert definitions to optimization passes.
317 ArenaVector<HOptimization*> optimizations = ConstructOptimizations(
318 definitions,
319 length,
320 graph->GetAllocator(),
321 graph,
322 compilation_stats_.get(),
323 codegen,
324 GetCompilerDriver(),
325 dex_compilation_unit,
326 handles);
327 DCHECK_EQ(length, optimizations.size());
Aart Bik2e148682018-04-18 16:11:12 -0700328 // Run the optimization passes one by one. Any "depends_on" pass refers back to
329 // the most recent occurrence of that pass, skipped or executed.
330 std::bitset<static_cast<size_t>(OptimizationPass::kLast) + 1u> pass_changes;
331 pass_changes[static_cast<size_t>(OptimizationPass::kNone)] = true;
Aart Bik24773202018-04-26 10:28:51 -0700332 bool change = false;
Aart Bik2ca10eb2017-11-15 15:17:53 -0800333 for (size_t i = 0; i < length; ++i) {
Aart Bik2e148682018-04-18 16:11:12 -0700334 if (pass_changes[static_cast<size_t>(definitions[i].depends_on)]) {
335 // Execute the pass and record whether it changed anything.
336 PassScope scope(optimizations[i]->GetPassName(), pass_observer);
337 bool pass_change = optimizations[i]->Run();
338 pass_changes[static_cast<size_t>(definitions[i].pass)] = pass_change;
Aart Bika8360cd2018-05-02 16:07:51 -0700339 if (pass_change) {
340 change = true;
341 } else {
342 scope.SetPassNotChanged();
343 }
Aart Bik2e148682018-04-18 16:11:12 -0700344 } else {
345 // Skip the pass and record that nothing changed.
346 pass_changes[static_cast<size_t>(definitions[i].pass)] = false;
347 }
Aart Bik2ca10eb2017-11-15 15:17:53 -0800348 }
Aart Bik24773202018-04-26 10:28:51 -0700349 return change;
Aart Bik2ca10eb2017-11-15 15:17:53 -0800350 }
351
Aart Bik24773202018-04-26 10:28:51 -0700352 template <size_t length> bool RunOptimizations(
Aart Bik2ca10eb2017-11-15 15:17:53 -0800353 HGraph* graph,
354 CodeGenerator* codegen,
355 const DexCompilationUnit& dex_compilation_unit,
356 PassObserver* pass_observer,
357 VariableSizedHandleScope* handles,
358 const OptimizationDef (&definitions)[length]) const {
Aart Bik24773202018-04-26 10:28:51 -0700359 return RunOptimizations(
Aart Bik2ca10eb2017-11-15 15:17:53 -0800360 graph, codegen, dex_compilation_unit, pass_observer, handles, definitions, length);
361 }
362
363 void RunOptimizations(HGraph* graph,
364 CodeGenerator* codegen,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700365 const DexCompilationUnit& dex_compilation_unit,
366 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700367 VariableSizedHandleScope* handles) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700368
Andreas Gampe53c913b2014-08-12 23:19:23 -0700369 private:
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000370 // Create a 'CompiledMethod' for an optimized graph.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100371 CompiledMethod* Emit(ArenaAllocator* allocator,
David Brazdil58282f42016-01-14 12:45:10 +0000372 CodeVectorAllocator* code_allocator,
373 CodeGenerator* codegen,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000374 const DexFile::CodeItem* item) const;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000375
376 // Try compiling a method and return the code generator used for
377 // compiling it.
378 // This method:
379 // 1) Builds the graph. Returns null if it failed to build it.
David Brazdil58282f42016-01-14 12:45:10 +0000380 // 2) Transforms the graph to SSA. Returns null if it failed.
381 // 3) Runs optimizations on the graph, including register allocator.
382 // 4) Generates code with the `code_allocator` provided.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100383 CodeGenerator* TryCompile(ArenaAllocator* allocator,
384 ArenaStack* arena_stack,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000385 CodeVectorAllocator* code_allocator,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000386 const DexCompilationUnit& dex_compilation_unit,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000387 ArtMethod* method,
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100388 bool baseline,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000389 bool osr,
390 VariableSizedHandleScope* handles) const;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000391
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000392 CodeGenerator* TryCompileIntrinsic(ArenaAllocator* allocator,
393 ArenaStack* arena_stack,
394 CodeVectorAllocator* code_allocator,
395 const DexCompilationUnit& dex_compilation_unit,
396 ArtMethod* method,
397 VariableSizedHandleScope* handles) const;
398
Aart Bik24773202018-04-26 10:28:51 -0700399 bool RunArchOptimizations(HGraph* graph,
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700400 CodeGenerator* codegen,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800401 const DexCompilationUnit& dex_compilation_unit,
402 PassObserver* pass_observer,
403 VariableSizedHandleScope* handles) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700404
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100405 bool RunBaselineOptimizations(HGraph* graph,
406 CodeGenerator* codegen,
407 const DexCompilationUnit& dex_compilation_unit,
408 PassObserver* pass_observer,
409 VariableSizedHandleScope* handles) const;
410
Stephen Hines48ba1972018-09-24 13:35:54 -0700411 void GenerateJitDebugInfo(ArtMethod* method,
412 const debug::MethodDebugInfo& method_debug_info)
David Srbeckyc9e02082018-01-24 16:44:02 +0000413 REQUIRES_SHARED(Locks::mutator_lock_);
David Srbeckyc684f332018-01-19 17:38:06 +0000414
Calin Juravle2be39e02015-04-21 13:56:34 +0100415 std::unique_ptr<OptimizingCompilerStats> compilation_stats_;
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100416
Andreas Gampe53c913b2014-08-12 23:19:23 -0700417 std::unique_ptr<std::ostream> visualizer_output_;
418
Andreas Gampea0d81af2016-10-27 12:04:57 -0700419 mutable Mutex dump_mutex_; // To synchronize visualizer writing.
420
Andreas Gampe53c913b2014-08-12 23:19:23 -0700421 DISALLOW_COPY_AND_ASSIGN(OptimizingCompiler);
422};
423
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100424static const int kMaximumCompilationTimeBeforeWarning = 100; /* ms */
425
426OptimizingCompiler::OptimizingCompiler(CompilerDriver* driver)
Andreas Gampea0d81af2016-10-27 12:04:57 -0700427 : Compiler(driver, kMaximumCompilationTimeBeforeWarning),
428 dump_mutex_("Visualizer dump lock") {}
David Brazdilee690a32014-12-01 17:04:16 +0000429
430void OptimizingCompiler::Init() {
431 // Enable C1visualizer output. Must be done in Init() because the compiler
432 // driver is not fully initialized when passed to the compiler's constructor.
433 CompilerDriver* driver = GetCompilerDriver();
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000434 const std::string cfg_file_name = driver->GetCompilerOptions().GetDumpCfgFileName();
David Brazdil866c0312015-01-13 21:21:31 +0000435 if (!cfg_file_name.empty()) {
Calin Juravle87000a92015-08-24 15:34:44 +0100436 std::ios_base::openmode cfg_file_mode =
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000437 driver->GetCompilerOptions().GetDumpCfgAppend() ? std::ofstream::app : std::ofstream::out;
Calin Juravle87000a92015-08-24 15:34:44 +0100438 visualizer_output_.reset(new std::ofstream(cfg_file_name, cfg_file_mode));
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100439 }
Nicolas Geoffray2d8801f2017-11-28 15:50:07 +0000440 if (driver->GetCompilerOptions().GetDumpStats()) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100441 compilation_stats_.reset(new OptimizingCompilerStats());
442 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100443}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000444
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000445void OptimizingCompiler::UnInit() const {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000446}
447
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100448OptimizingCompiler::~OptimizingCompiler() {
Calin Juravle2be39e02015-04-21 13:56:34 +0100449 if (compilation_stats_.get() != nullptr) {
450 compilation_stats_->Log();
451 }
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100452}
453
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000454bool OptimizingCompiler::CanCompileMethod(uint32_t method_idx ATTRIBUTE_UNUSED,
Vladimir Markodf739842016-03-23 16:59:07 +0000455 const DexFile& dex_file ATTRIBUTE_UNUSED) const {
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000456 return true;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700457}
458
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000459static bool IsInstructionSetSupported(InstructionSet instruction_set) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000460 return instruction_set == InstructionSet::kArm
461 || instruction_set == InstructionSet::kArm64
462 || instruction_set == InstructionSet::kThumb2
463 || instruction_set == InstructionSet::kMips
464 || instruction_set == InstructionSet::kMips64
465 || instruction_set == InstructionSet::kX86
466 || instruction_set == InstructionSet::kX86_64;
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000467}
468
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100469bool OptimizingCompiler::RunBaselineOptimizations(HGraph* graph,
470 CodeGenerator* codegen,
471 const DexCompilationUnit& dex_compilation_unit,
472 PassObserver* pass_observer,
473 VariableSizedHandleScope* handles) const {
474 switch (codegen->GetCompilerOptions().GetInstructionSet()) {
475#ifdef ART_ENABLE_CODEGEN_mips
476 case InstructionSet::kMips: {
477 OptimizationDef mips_optimizations[] = {
478 OptDef(OptimizationPass::kPcRelativeFixupsMips)
479 };
480 return RunOptimizations(graph,
481 codegen,
482 dex_compilation_unit,
483 pass_observer,
484 handles,
485 mips_optimizations);
486 }
487#endif
488#ifdef ART_ENABLE_CODEGEN_x86
489 case InstructionSet::kX86: {
490 OptimizationDef x86_optimizations[] = {
491 OptDef(OptimizationPass::kPcRelativeFixupsX86),
492 };
493 return RunOptimizations(graph,
494 codegen,
495 dex_compilation_unit,
496 pass_observer,
497 handles,
498 x86_optimizations);
499 }
500#endif
501 default:
502 UNUSED(graph);
503 UNUSED(codegen);
504 UNUSED(dex_compilation_unit);
505 UNUSED(pass_observer);
506 UNUSED(handles);
507 return false;
508 }
509}
510
Aart Bik24773202018-04-26 10:28:51 -0700511bool OptimizingCompiler::RunArchOptimizations(HGraph* graph,
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700512 CodeGenerator* codegen,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800513 const DexCompilationUnit& dex_compilation_unit,
514 PassObserver* pass_observer,
515 VariableSizedHandleScope* handles) const {
Vladimir Markoa0431112018-06-25 09:32:54 +0100516 switch (codegen->GetCompilerOptions().GetInstructionSet()) {
Artem Serov2bbc9532016-10-21 11:51:50 +0100517#if defined(ART_ENABLE_CODEGEN_arm)
Vladimir Marko33bff252017-11-01 14:35:42 +0000518 case InstructionSet::kThumb2:
519 case InstructionSet::kArm: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800520 OptimizationDef arm_optimizations[] = {
521 OptDef(OptimizationPass::kInstructionSimplifierArm),
522 OptDef(OptimizationPass::kSideEffectsAnalysis),
523 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
524 OptDef(OptimizationPass::kScheduling)
Vladimir Markob4536b72015-11-24 13:45:23 +0000525 };
Aart Bik24773202018-04-26 10:28:51 -0700526 return RunOptimizations(graph,
527 codegen,
528 dex_compilation_unit,
529 pass_observer,
530 handles,
531 arm_optimizations);
Vladimir Markob4536b72015-11-24 13:45:23 +0000532 }
533#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100534#ifdef ART_ENABLE_CODEGEN_arm64
Vladimir Marko33bff252017-11-01 14:35:42 +0000535 case InstructionSet::kArm64: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800536 OptimizationDef arm64_optimizations[] = {
537 OptDef(OptimizationPass::kInstructionSimplifierArm64),
538 OptDef(OptimizationPass::kSideEffectsAnalysis),
539 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
540 OptDef(OptimizationPass::kScheduling)
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100541 };
Aart Bik24773202018-04-26 10:28:51 -0700542 return RunOptimizations(graph,
543 codegen,
544 dex_compilation_unit,
545 pass_observer,
546 handles,
547 arm64_optimizations);
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100548 }
549#endif
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700550#ifdef ART_ENABLE_CODEGEN_mips
Vladimir Marko33bff252017-11-01 14:35:42 +0000551 case InstructionSet::kMips: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800552 OptimizationDef mips_optimizations[] = {
553 OptDef(OptimizationPass::kInstructionSimplifierMips),
554 OptDef(OptimizationPass::kSideEffectsAnalysis),
555 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
556 OptDef(OptimizationPass::kPcRelativeFixupsMips)
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700557 };
Aart Bik24773202018-04-26 10:28:51 -0700558 return RunOptimizations(graph,
559 codegen,
560 dex_compilation_unit,
561 pass_observer,
562 handles,
563 mips_optimizations);
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700564 }
565#endif
Lena Djokicb8e9c352017-09-20 15:11:13 +0200566#ifdef ART_ENABLE_CODEGEN_mips64
Vladimir Marko33bff252017-11-01 14:35:42 +0000567 case InstructionSet::kMips64: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800568 OptimizationDef mips64_optimizations[] = {
569 OptDef(OptimizationPass::kSideEffectsAnalysis),
570 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch")
Lena Djokicb8e9c352017-09-20 15:11:13 +0200571 };
Aart Bik24773202018-04-26 10:28:51 -0700572 return RunOptimizations(graph,
573 codegen,
574 dex_compilation_unit,
575 pass_observer,
576 handles,
577 mips64_optimizations);
Lena Djokicb8e9c352017-09-20 15:11:13 +0200578 }
579#endif
Mark Mendell0616ae02015-04-17 12:49:27 -0400580#ifdef ART_ENABLE_CODEGEN_x86
Vladimir Marko33bff252017-11-01 14:35:42 +0000581 case InstructionSet::kX86: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800582 OptimizationDef x86_optimizations[] = {
Shalini Salomi Bodapatidd121f62018-10-26 15:03:53 +0530583 OptDef(OptimizationPass::kInstructionSimplifierX86),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800584 OptDef(OptimizationPass::kSideEffectsAnalysis),
585 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
586 OptDef(OptimizationPass::kPcRelativeFixupsX86),
Hans Boehmf5f56c72018-07-13 00:05:27 +0000587 OptDef(OptimizationPass::kX86MemoryOperandGeneration)
Mark Mendell0616ae02015-04-17 12:49:27 -0400588 };
Aart Bik24773202018-04-26 10:28:51 -0700589 return RunOptimizations(graph,
590 codegen,
591 dex_compilation_unit,
592 pass_observer,
593 handles,
594 x86_optimizations);
Mark Mendell0616ae02015-04-17 12:49:27 -0400595 }
596#endif
Mark Mendellee8d9712016-07-12 11:13:15 -0400597#ifdef ART_ENABLE_CODEGEN_x86_64
Vladimir Marko33bff252017-11-01 14:35:42 +0000598 case InstructionSet::kX86_64: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800599 OptimizationDef x86_64_optimizations[] = {
Shalini Salomi Bodapatidd121f62018-10-26 15:03:53 +0530600 OptDef(OptimizationPass::kInstructionSimplifierX86_64),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800601 OptDef(OptimizationPass::kSideEffectsAnalysis),
602 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
Hans Boehmf5f56c72018-07-13 00:05:27 +0000603 OptDef(OptimizationPass::kX86MemoryOperandGeneration)
Mark Mendellee8d9712016-07-12 11:13:15 -0400604 };
Aart Bik24773202018-04-26 10:28:51 -0700605 return RunOptimizations(graph,
606 codegen,
607 dex_compilation_unit,
608 pass_observer,
609 handles,
610 x86_64_optimizations);
Mark Mendellee8d9712016-07-12 11:13:15 -0400611 }
612#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100613 default:
Aart Bik24773202018-04-26 10:28:51 -0700614 return false;
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100615 }
616}
617
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000618NO_INLINE // Avoid increasing caller's frame size by large stack-allocated objects.
619static void AllocateRegisters(HGraph* graph,
620 CodeGenerator* codegen,
Matthew Gharrity2cd05b72016-08-03 16:57:37 -0700621 PassObserver* pass_observer,
Igor Murashkin6ef45672017-08-08 13:59:55 -0700622 RegisterAllocator::Strategy strategy,
623 OptimizingCompilerStats* stats) {
Mingyao Yang700347e2016-03-02 14:59:32 -0800624 {
625 PassScope scope(PrepareForRegisterAllocation::kPrepareForRegisterAllocationPassName,
626 pass_observer);
Nicolas Geoffray61ba8d22018-08-07 09:55:57 +0100627 PrepareForRegisterAllocation(graph, codegen->GetCompilerOptions(), stats).Run();
Mingyao Yang700347e2016-03-02 14:59:32 -0800628 }
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100629 // Use local allocator shared by SSA liveness analysis and register allocator.
630 // (Register allocator creates new objects in the liveness data.)
631 ScopedArenaAllocator local_allocator(graph->GetArenaStack());
632 SsaLivenessAnalysis liveness(graph, codegen, &local_allocator);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000633 {
634 PassScope scope(SsaLivenessAnalysis::kLivenessPassName, pass_observer);
635 liveness.Analyze();
636 }
637 {
638 PassScope scope(RegisterAllocator::kRegisterAllocatorPassName, pass_observer);
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100639 std::unique_ptr<RegisterAllocator> register_allocator =
640 RegisterAllocator::Create(&local_allocator, codegen, liveness, strategy);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100641 register_allocator->AllocateRegisters();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000642 }
643}
644
Aart Bik2ca10eb2017-11-15 15:17:53 -0800645// Strip pass name suffix to get optimization name.
646static std::string ConvertPassNameToOptimizationName(const std::string& pass_name) {
647 size_t pos = pass_name.find(kPassNameSeparator);
648 return pos == std::string::npos ? pass_name : pass_name.substr(0, pos);
649}
650
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700651void OptimizingCompiler::RunOptimizations(HGraph* graph,
652 CodeGenerator* codegen,
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700653 const DexCompilationUnit& dex_compilation_unit,
654 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700655 VariableSizedHandleScope* handles) const {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800656 const std::vector<std::string>* pass_names =
657 GetCompilerDriver()->GetCompilerOptions().GetPassesToRun();
658 if (pass_names != nullptr) {
659 // If passes were defined on command-line, build the optimization
660 // passes and run these instead of the built-in optimizations.
Aart Bik2e148682018-04-18 16:11:12 -0700661 // TODO: a way to define depends_on via command-line?
Aart Bik2ca10eb2017-11-15 15:17:53 -0800662 const size_t length = pass_names->size();
663 std::vector<OptimizationDef> optimizations;
664 for (const std::string& pass_name : *pass_names) {
665 std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
666 optimizations.push_back(OptDef(OptimizationPassByName(opt_name.c_str()), pass_name.c_str()));
667 }
668 RunOptimizations(graph,
669 codegen,
670 dex_compilation_unit,
671 pass_observer,
672 handles,
673 optimizations.data(),
674 length);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700675 return;
676 }
677
Aart Bik24773202018-04-26 10:28:51 -0700678 OptimizationDef optimizations[] = {
Aart Bik2e148682018-04-18 16:11:12 -0700679 // Initial optimizations.
Aart Bik2ca10eb2017-11-15 15:17:53 -0800680 OptDef(OptimizationPass::kConstantFolding),
681 OptDef(OptimizationPass::kInstructionSimplifier),
Aart Bik2e148682018-04-18 16:11:12 -0700682 OptDef(OptimizationPass::kDeadCodeElimination,
683 "dead_code_elimination$initial"),
684 // Inlining.
Aart Bik24773202018-04-26 10:28:51 -0700685 OptDef(OptimizationPass::kInliner),
Aart Bik2e148682018-04-18 16:11:12 -0700686 // Simplification (only if inlining occurred).
687 OptDef(OptimizationPass::kConstantFolding,
688 "constant_folding$after_inlining",
689 OptimizationPass::kInliner),
690 OptDef(OptimizationPass::kInstructionSimplifier,
691 "instruction_simplifier$after_inlining",
692 OptimizationPass::kInliner),
693 OptDef(OptimizationPass::kDeadCodeElimination,
694 "dead_code_elimination$after_inlining",
695 OptimizationPass::kInliner),
696 // GVN.
697 OptDef(OptimizationPass::kSideEffectsAnalysis,
698 "side_effects$before_gvn"),
Aart Bik6d057002018-04-09 15:39:58 -0700699 OptDef(OptimizationPass::kGlobalValueNumbering),
Aart Bik2e148682018-04-18 16:11:12 -0700700 // Simplification (TODO: only if GVN occurred).
Aart Bik2ca10eb2017-11-15 15:17:53 -0800701 OptDef(OptimizationPass::kSelectGenerator),
Aart Bik2e148682018-04-18 16:11:12 -0700702 OptDef(OptimizationPass::kConstantFolding,
703 "constant_folding$after_gvn"),
704 OptDef(OptimizationPass::kInstructionSimplifier,
705 "instruction_simplifier$after_gvn"),
706 OptDef(OptimizationPass::kDeadCodeElimination,
707 "dead_code_elimination$after_gvn"),
708 // High-level optimizations.
709 OptDef(OptimizationPass::kSideEffectsAnalysis,
710 "side_effects$before_licm"),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800711 OptDef(OptimizationPass::kInvariantCodeMotion),
712 OptDef(OptimizationPass::kInductionVarAnalysis),
713 OptDef(OptimizationPass::kBoundsCheckElimination),
714 OptDef(OptimizationPass::kLoopOptimization),
Aart Bik2e148682018-04-18 16:11:12 -0700715 // Simplification.
716 OptDef(OptimizationPass::kConstantFolding,
717 "constant_folding$after_bce"),
718 OptDef(OptimizationPass::kInstructionSimplifier,
719 "instruction_simplifier$after_bce"),
720 // Other high-level optimizations.
721 OptDef(OptimizationPass::kSideEffectsAnalysis,
722 "side_effects$before_lse"),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800723 OptDef(OptimizationPass::kLoadStoreAnalysis),
724 OptDef(OptimizationPass::kLoadStoreElimination),
725 OptDef(OptimizationPass::kCHAGuardOptimization),
Aart Bik2e148682018-04-18 16:11:12 -0700726 OptDef(OptimizationPass::kDeadCodeElimination,
727 "dead_code_elimination$final"),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800728 OptDef(OptimizationPass::kCodeSinking),
David Brazdil8993caf2015-12-07 10:04:40 +0000729 // The codegen has a few assumptions that only the instruction simplifier
730 // can satisfy. For example, the code generator does not expect to see a
731 // HTypeConversion from a type to the same type.
Aart Bik2e148682018-04-18 16:11:12 -0700732 OptDef(OptimizationPass::kInstructionSimplifier,
733 "instruction_simplifier$before_codegen"),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800734 // Eliminate constructor fences after code sinking to avoid
735 // complicated sinking logic to split a fence with many inputs.
736 OptDef(OptimizationPass::kConstructorFenceRedundancyElimination)
David Brazdil8993caf2015-12-07 10:04:40 +0000737 };
Aart Bik2ca10eb2017-11-15 15:17:53 -0800738 RunOptimizations(graph,
739 codegen,
740 dex_compilation_unit,
741 pass_observer,
742 handles,
Aart Bik24773202018-04-26 10:28:51 -0700743 optimizations);
David Brazdilbbd733e2015-08-18 17:48:17 +0100744
Aart Bik2ca10eb2017-11-15 15:17:53 -0800745 RunArchOptimizations(graph, codegen, dex_compilation_unit, pass_observer, handles);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000746}
747
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100748static ArenaVector<linker::LinkerPatch> EmitAndSortLinkerPatches(CodeGenerator* codegen) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100749 ArenaVector<linker::LinkerPatch> linker_patches(codegen->GetGraph()->GetAllocator()->Adapter());
Vladimir Marko58155012015-08-19 12:49:41 +0000750 codegen->EmitLinkerPatches(&linker_patches);
751
752 // Sort patches by literal offset. Required for .oat_patches encoding.
753 std::sort(linker_patches.begin(), linker_patches.end(),
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100754 [](const linker::LinkerPatch& lhs, const linker::LinkerPatch& rhs) {
Vladimir Marko58155012015-08-19 12:49:41 +0000755 return lhs.LiteralOffset() < rhs.LiteralOffset();
756 });
757
758 return linker_patches;
759}
760
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100761CompiledMethod* OptimizingCompiler::Emit(ArenaAllocator* allocator,
David Brazdil58282f42016-01-14 12:45:10 +0000762 CodeVectorAllocator* code_allocator,
763 CodeGenerator* codegen,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000764 const DexFile::CodeItem* code_item_for_osr_check) const {
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100765 ArenaVector<linker::LinkerPatch> linker_patches = EmitAndSortLinkerPatches(codegen);
David Srbeckye7a91942018-08-01 17:23:53 +0100766 ScopedArenaVector<uint8_t> stack_map = codegen->BuildStackMaps(code_item_for_osr_check);
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000767
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100768 CompiledMethod* compiled_method = CompiledMethod::SwapAllocCompiledMethod(
Vladimir Marko33f7c8a2018-11-19 10:22:01 +0000769 GetCompilerDriver()->GetCompiledMethodStorage(),
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000770 codegen->GetInstructionSet(),
Vladimir Markoca1e0382018-04-11 09:58:41 +0000771 code_allocator->GetMemory(),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100772 ArrayRef<const uint8_t>(stack_map),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100773 ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data()),
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100774 ArrayRef<const linker::LinkerPatch>(linker_patches));
Mathieu Chartiered150002015-08-28 11:16:54 -0700775
Vladimir Markoca1e0382018-04-11 09:58:41 +0000776 CompiledMethodStorage* storage = GetCompilerDriver()->GetCompiledMethodStorage();
777 for (const linker::LinkerPatch& patch : linker_patches) {
778 if (codegen->NeedsThunkCode(patch) && storage->GetThunkCode(patch).empty()) {
779 ArenaVector<uint8_t> code(allocator->Adapter());
780 std::string debug_name;
781 codegen->EmitThunkCode(patch, &code, &debug_name);
782 storage->SetThunkCode(patch, ArrayRef<const uint8_t>(code), debug_name);
783 }
784 }
785
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100786 return compiled_method;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000787}
788
Vladimir Markoca6fff82017-10-03 14:49:14 +0100789CodeGenerator* OptimizingCompiler::TryCompile(ArenaAllocator* allocator,
790 ArenaStack* arena_stack,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000791 CodeVectorAllocator* code_allocator,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000792 const DexCompilationUnit& dex_compilation_unit,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000793 ArtMethod* method,
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100794 bool baseline,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000795 bool osr,
796 VariableSizedHandleScope* handles) const {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000797 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kAttemptBytecodeCompilation);
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000798 CompilerDriver* compiler_driver = GetCompilerDriver();
Vladimir Markoa0431112018-06-25 09:32:54 +0100799 const CompilerOptions& compiler_options = compiler_driver->GetCompilerOptions();
800 InstructionSet instruction_set = compiler_options.GetInstructionSet();
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000801 const DexFile& dex_file = *dex_compilation_unit.GetDexFile();
802 uint32_t method_idx = dex_compilation_unit.GetDexMethodIndex();
803 const DexFile::CodeItem* code_item = dex_compilation_unit.GetCodeItem();
Calin Juravlecff8cc72015-10-09 12:03:24 +0100804
Roland Levillain3b359c72015-11-17 19:35:12 +0000805 // Always use the Thumb-2 assembler: some runtime functionality
806 // (like implicit stack overflow checks) assume Thumb-2.
Vladimir Marko33bff252017-11-01 14:35:42 +0000807 DCHECK_NE(instruction_set, InstructionSet::kArm);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100808
809 // Do not attempt to compile on architectures we do not support.
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000810 if (!IsInstructionSetSupported(instruction_set)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700811 MaybeRecordStat(compilation_stats_.get(),
812 MethodCompilationStat::kNotCompiledUnsupportedIsa);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100813 return nullptr;
814 }
815
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000816 if (Compiler::IsPathologicalCase(*code_item, method_idx, dex_file)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000817 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledPathological);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000818 return nullptr;
819 }
820
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000821 // Implementation of the space filter: do not compile a code item whose size in
Nicolas Geoffray432bf3d2015-07-17 11:11:09 +0100822 // code units is bigger than 128.
823 static constexpr size_t kSpaceFilterOptimizingThreshold = 128;
Andreas Gampe29d38e72016-03-23 15:31:51 +0000824 if ((compiler_options.GetCompilerFilter() == CompilerFilter::kSpace)
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800825 && (CodeItemInstructionAccessor(dex_file, code_item).InsnsSizeInCodeUnits() >
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800826 kSpaceFilterOptimizingThreshold)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000827 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledSpaceFilter);
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000828 return nullptr;
829 }
830
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800831 CodeItemDebugInfoAccessor code_item_accessor(dex_file, code_item, method_idx);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100832 HGraph* graph = new (allocator) HGraph(
833 allocator,
834 arena_stack,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000835 dex_file,
836 method_idx,
Vladimir Markoa0431112018-06-25 09:32:54 +0100837 compiler_options.GetInstructionSet(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000838 kInvalidInvokeType,
839 compiler_driver->GetCompilerOptions().GetDebuggable(),
840 osr);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000841
Mathieu Chartier210531f2018-01-12 10:15:51 -0800842 ArrayRef<const uint8_t> interpreter_metadata;
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000843 // For AOT compilation, we may not get a method, for example if its class is erroneous.
844 // JIT should always have a method.
845 DCHECK(Runtime::Current()->IsAotCompiler() || method != nullptr);
846 if (method != nullptr) {
847 graph->SetArtMethod(method);
848 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000849 interpreter_metadata = method->GetQuickenedInfo();
David Brazdilbadd8262016-02-02 16:28:56 +0000850 }
851
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000852 std::unique_ptr<CodeGenerator> codegen(
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000853 CodeGenerator::Create(graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100854 compiler_options,
Calin Juravle2ae48182016-03-16 14:05:09 +0000855 compilation_stats_.get()));
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000856 if (codegen.get() == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000857 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledNoCodegen);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000858 return nullptr;
859 }
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100860 codegen->GetAssembler()->cfi().SetEnabled(
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000861 compiler_driver->GetCompilerOptions().GenerateAnyDebugInfo());
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000862
David Brazdil69ba7b72015-06-23 18:27:30 +0100863 PassObserver pass_observer(graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100864 codegen.get(),
865 visualizer_output_.get(),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700866 compiler_driver,
867 dump_mutex_);
David Brazdil5e8b1372015-01-23 14:39:08 +0000868
David Brazdil809658e2015-02-05 11:34:02 +0000869 {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000870 VLOG(compiler) << "Building " << pass_observer.GetMethodName();
871 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
872 HGraphBuilder builder(graph,
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800873 code_item_accessor,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000874 &dex_compilation_unit,
875 &dex_compilation_unit,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000876 codegen.get(),
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000877 compilation_stats_.get(),
878 interpreter_metadata,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000879 handles);
880 GraphAnalysisResult result = builder.BuildGraph();
881 if (result != kAnalysisSuccess) {
882 switch (result) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700883 case kAnalysisSkipped: {
884 MaybeRecordStat(compilation_stats_.get(),
885 MethodCompilationStat::kNotCompiledSkipped);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000886 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100887 }
Igor Murashkin1e065a52017-08-09 13:20:34 -0700888 case kAnalysisInvalidBytecode: {
889 MaybeRecordStat(compilation_stats_.get(),
890 MethodCompilationStat::kNotCompiledInvalidBytecode);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000891 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100892 }
Igor Murashkin1e065a52017-08-09 13:20:34 -0700893 case kAnalysisFailThrowCatchLoop: {
894 MaybeRecordStat(compilation_stats_.get(),
895 MethodCompilationStat::kNotCompiledThrowCatchLoop);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000896 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100897 }
Igor Murashkin1e065a52017-08-09 13:20:34 -0700898 case kAnalysisFailAmbiguousArrayOp: {
899 MaybeRecordStat(compilation_stats_.get(),
900 MethodCompilationStat::kNotCompiledAmbiguousArrayOp);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000901 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100902 }
Nicolas Geoffray0846a8f2018-09-12 15:21:07 +0100903 case kAnalysisFailIrreducibleLoopAndStringInit: {
904 MaybeRecordStat(compilation_stats_.get(),
905 MethodCompilationStat::kNotCompiledIrreducibleLoopAndStringInit);
906 break;
907 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000908 case kAnalysisSuccess:
909 UNREACHABLE();
David Brazdil809658e2015-02-05 11:34:02 +0000910 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000911 pass_observer.SetGraphInBadState();
912 return nullptr;
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000913 }
David Brazdilbadd8262016-02-02 16:28:56 +0000914 }
Vladimir Markof9f64412015-09-02 14:05:49 +0100915
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100916 if (baseline) {
917 RunBaselineOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer, handles);
918 } else {
919 RunOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer, handles);
920 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000921
922 RegisterAllocator::Strategy regalloc_strategy =
923 compiler_options.GetRegisterAllocationStrategy();
Igor Murashkin1e065a52017-08-09 13:20:34 -0700924 AllocateRegisters(graph,
925 codegen.get(),
926 &pass_observer,
Igor Murashkin6ef45672017-08-08 13:59:55 -0700927 regalloc_strategy,
928 compilation_stats_.get());
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000929
930 codegen->Compile(code_allocator);
931 pass_observer.DumpDisassembly();
932
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000933 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledBytecode);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000934 return codegen.release();
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000935}
936
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000937CodeGenerator* OptimizingCompiler::TryCompileIntrinsic(
938 ArenaAllocator* allocator,
939 ArenaStack* arena_stack,
940 CodeVectorAllocator* code_allocator,
941 const DexCompilationUnit& dex_compilation_unit,
942 ArtMethod* method,
943 VariableSizedHandleScope* handles) const {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000944 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kAttemptIntrinsicCompilation);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000945 CompilerDriver* compiler_driver = GetCompilerDriver();
Vladimir Markoa0431112018-06-25 09:32:54 +0100946 const CompilerOptions& compiler_options = compiler_driver->GetCompilerOptions();
947 InstructionSet instruction_set = compiler_options.GetInstructionSet();
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000948 const DexFile& dex_file = *dex_compilation_unit.GetDexFile();
949 uint32_t method_idx = dex_compilation_unit.GetDexMethodIndex();
950
951 // Always use the Thumb-2 assembler: some runtime functionality
952 // (like implicit stack overflow checks) assume Thumb-2.
953 DCHECK_NE(instruction_set, InstructionSet::kArm);
954
955 // Do not attempt to compile on architectures we do not support.
956 if (!IsInstructionSetSupported(instruction_set)) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000957 return nullptr;
958 }
959
960 HGraph* graph = new (allocator) HGraph(
961 allocator,
962 arena_stack,
963 dex_file,
964 method_idx,
Vladimir Markoa0431112018-06-25 09:32:54 +0100965 compiler_driver->GetCompilerOptions().GetInstructionSet(),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000966 kInvalidInvokeType,
967 compiler_driver->GetCompilerOptions().GetDebuggable(),
968 /* osr */ false);
969
970 DCHECK(Runtime::Current()->IsAotCompiler());
971 DCHECK(method != nullptr);
972 graph->SetArtMethod(method);
973
974 std::unique_ptr<CodeGenerator> codegen(
975 CodeGenerator::Create(graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100976 compiler_options,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000977 compilation_stats_.get()));
978 if (codegen.get() == nullptr) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000979 return nullptr;
980 }
Vladimir Markoa0431112018-06-25 09:32:54 +0100981 codegen->GetAssembler()->cfi().SetEnabled(compiler_options.GenerateAnyDebugInfo());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000982
983 PassObserver pass_observer(graph,
984 codegen.get(),
985 visualizer_output_.get(),
986 compiler_driver,
987 dump_mutex_);
988
989 {
990 VLOG(compiler) << "Building intrinsic graph " << pass_observer.GetMethodName();
991 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
992 HGraphBuilder builder(graph,
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800993 CodeItemDebugInfoAccessor(), // Null code item.
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000994 &dex_compilation_unit,
995 &dex_compilation_unit,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000996 codegen.get(),
997 compilation_stats_.get(),
Mathieu Chartier210531f2018-01-12 10:15:51 -0800998 /* interpreter_metadata */ ArrayRef<const uint8_t>(),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000999 handles);
1000 builder.BuildIntrinsicGraph(method);
1001 }
1002
Aart Bik2ca10eb2017-11-15 15:17:53 -08001003 OptimizationDef optimizations[] = {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001004 // The codegen has a few assumptions that only the instruction simplifier
1005 // can satisfy.
Aart Bik2ca10eb2017-11-15 15:17:53 -08001006 OptDef(OptimizationPass::kInstructionSimplifier),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001007 };
Aart Bik2ca10eb2017-11-15 15:17:53 -08001008 RunOptimizations(graph,
1009 codegen.get(),
1010 dex_compilation_unit,
1011 &pass_observer,
1012 handles,
1013 optimizations);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001014
Aart Bik2ca10eb2017-11-15 15:17:53 -08001015 RunArchOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer, handles);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001016
1017 AllocateRegisters(graph,
1018 codegen.get(),
1019 &pass_observer,
1020 compiler_driver->GetCompilerOptions().GetRegisterAllocationStrategy(),
1021 compilation_stats_.get());
1022 if (!codegen->IsLeafMethod()) {
1023 VLOG(compiler) << "Intrinsic method is not leaf: " << method->GetIntrinsic()
1024 << " " << graph->PrettyMethod();
1025 return nullptr;
1026 }
1027
1028 codegen->Compile(code_allocator);
1029 pass_observer.DumpDisassembly();
1030
1031 VLOG(compiler) << "Compiled intrinsic: " << method->GetIntrinsic()
1032 << " " << graph->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001033 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledIntrinsic);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001034 return codegen.release();
1035}
1036
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001037CompiledMethod* OptimizingCompiler::Compile(const DexFile::CodeItem* code_item,
1038 uint32_t access_flags,
1039 InvokeType invoke_type,
1040 uint16_t class_def_idx,
1041 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001042 Handle<mirror::ClassLoader> jclass_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -07001043 const DexFile& dex_file,
1044 Handle<mirror::DexCache> dex_cache) const {
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001045 CompilerDriver* compiler_driver = GetCompilerDriver();
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001046 CompiledMethod* compiled_method = nullptr;
1047 Runtime* runtime = Runtime::Current();
1048 DCHECK(runtime->IsAotCompiler());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001049 const VerifiedMethod* verified_method = compiler_driver->GetVerifiedMethod(&dex_file, method_idx);
1050 DCHECK(!verified_method->HasRuntimeThrow());
Vladimir Markoca6fff82017-10-03 14:49:14 +01001051 if (compiler_driver->IsMethodVerifiedWithoutFailures(method_idx, class_def_idx, dex_file) ||
1052 verifier::CanCompilerHandleVerificationFailure(
1053 verified_method->GetEncounteredVerificationFailures())) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001054 ArenaAllocator allocator(runtime->GetArenaPool());
1055 ArenaStack arena_stack(runtime->GetArenaPool());
Vladimir Markoca6fff82017-10-03 14:49:14 +01001056 CodeVectorAllocator code_allocator(&allocator);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001057 std::unique_ptr<CodeGenerator> codegen;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001058 bool compiled_intrinsic = false;
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001059 {
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001060 ScopedObjectAccess soa(Thread::Current());
1061 ArtMethod* method =
1062 runtime->GetClassLinker()->ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
1063 method_idx, dex_cache, jclass_loader, /*referrer=*/ nullptr, invoke_type);
1064 DCHECK_EQ(method == nullptr, soa.Self()->IsExceptionPending());
1065 soa.Self()->ClearException(); // Suppress exception if any.
1066 VariableSizedHandleScope handles(soa.Self());
1067 Handle<mirror::Class> compiling_class =
1068 handles.NewHandle(method != nullptr ? method->GetDeclaringClass() : nullptr);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001069 DexCompilationUnit dex_compilation_unit(
1070 jclass_loader,
1071 runtime->GetClassLinker(),
1072 dex_file,
1073 code_item,
1074 class_def_idx,
1075 method_idx,
1076 access_flags,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001077 /*verified_method=*/ nullptr, // Not needed by the Optimizing compiler.
1078 dex_cache,
1079 compiling_class);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001080 // Go to native so that we don't block GC during compilation.
1081 ScopedThreadSuspension sts(soa.Self(), kNative);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001082 if (method != nullptr && UNLIKELY(method->IsIntrinsic())) {
1083 DCHECK(compiler_driver->GetCompilerOptions().IsBootImage());
1084 codegen.reset(
1085 TryCompileIntrinsic(&allocator,
1086 &arena_stack,
1087 &code_allocator,
1088 dex_compilation_unit,
1089 method,
1090 &handles));
1091 if (codegen != nullptr) {
1092 compiled_intrinsic = true;
1093 }
1094 }
1095 if (codegen == nullptr) {
1096 codegen.reset(
1097 TryCompile(&allocator,
1098 &arena_stack,
1099 &code_allocator,
1100 dex_compilation_unit,
1101 method,
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +01001102 compiler_driver->GetCompilerOptions().IsBaseline(),
1103 /* osr= */ false,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001104 &handles));
1105 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001106 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001107 if (codegen.get() != nullptr) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001108 compiled_method = Emit(&allocator,
1109 &code_allocator,
1110 codegen.get(),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001111 compiled_intrinsic ? nullptr : code_item);
1112 if (compiled_intrinsic) {
1113 compiled_method->MarkAsIntrinsic();
1114 }
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001115
1116 if (kArenaAllocatorCountAllocations) {
Vladimir Marko174b2e22017-10-12 13:34:49 +01001117 codegen.reset(); // Release codegen's ScopedArenaAllocator for memory accounting.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001118 size_t total_allocated = allocator.BytesAllocated() + arena_stack.PeakBytesAllocated();
1119 if (total_allocated > kArenaAllocatorMemoryReportThreshold) {
1120 MemStats mem_stats(allocator.GetMemStats());
1121 MemStats peak_stats(arena_stack.GetPeakStats());
Vladimir Marko69d310e2017-10-09 14:12:23 +01001122 LOG(INFO) << "Used " << total_allocated << " bytes of arena memory for compiling "
1123 << dex_file.PrettyMethod(method_idx)
Vladimir Markoca6fff82017-10-03 14:49:14 +01001124 << "\n" << Dumpable<MemStats>(mem_stats)
1125 << "\n" << Dumpable<MemStats>(peak_stats);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001126 }
1127 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001128 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001129 } else {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001130 MethodCompilationStat method_stat;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001131 if (compiler_driver->GetCompilerOptions().VerifyAtRuntime()) {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001132 method_stat = MethodCompilationStat::kNotCompiledVerifyAtRuntime;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001133 } else {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001134 method_stat = MethodCompilationStat::kNotCompiledVerificationError;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001135 }
Igor Murashkin1e065a52017-08-09 13:20:34 -07001136 MaybeRecordStat(compilation_stats_.get(), method_stat);
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001137 }
1138
Calin Juravlecff8cc72015-10-09 12:03:24 +01001139 if (kIsDebugBuild &&
Vladimir Marko6be1dbd2018-11-13 13:09:51 +00001140 compiler_driver->GetCompilerOptions().CompilingWithCoreImage() &&
Vladimir Markoa0431112018-06-25 09:32:54 +01001141 IsInstructionSetSupported(compiler_driver->GetCompilerOptions().GetInstructionSet())) {
Roland Levillain0d5a2812015-11-13 10:07:31 +00001142 // For testing purposes, we put a special marker on method names
Goran Jakovljevic9c4f0d8f2017-04-05 16:27:25 +02001143 // that should be compiled with this compiler (when the
1144 // instruction set is supported). This makes sure we're not
Roland Levillain0d5a2812015-11-13 10:07:31 +00001145 // regressing.
David Sehr709b0702016-10-13 09:12:37 -07001146 std::string method_name = dex_file.PrettyMethod(method_idx);
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001147 bool shouldCompile = method_name.find("$opt$") != std::string::npos;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001148 DCHECK((compiled_method != nullptr) || !shouldCompile) << "Didn't compile " << method_name;
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001149 }
1150
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001151 return compiled_method;
1152}
1153
David Srbeckye7a91942018-08-01 17:23:53 +01001154static ScopedArenaVector<uint8_t> CreateJniStackMap(ScopedArenaAllocator* allocator,
1155 const JniCompiledMethod& jni_compiled_method) {
Vladimir Markoced04832018-07-26 14:42:17 +01001156 // StackMapStream is quite large, so allocate it using the ScopedArenaAllocator
1157 // to stay clear of the frame size limit.
1158 std::unique_ptr<StackMapStream> stack_map_stream(
David Srbeckye7a91942018-08-01 17:23:53 +01001159 new (allocator) StackMapStream(allocator, jni_compiled_method.GetInstructionSet()));
Vladimir Markoced04832018-07-26 14:42:17 +01001160 stack_map_stream->BeginMethod(
David Srbeckyafc97bc2018-07-05 08:14:35 +00001161 jni_compiled_method.GetFrameSize(),
1162 jni_compiled_method.GetCoreSpillMask(),
1163 jni_compiled_method.GetFpSpillMask(),
1164 /* num_dex_registers */ 0);
Vladimir Markoced04832018-07-26 14:42:17 +01001165 stack_map_stream->EndMethod();
David Srbeckye7a91942018-08-01 17:23:53 +01001166 return stack_map_stream->Encode();
David Srbeckyafc97bc2018-07-05 08:14:35 +00001167}
1168
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001169CompiledMethod* OptimizingCompiler::JniCompile(uint32_t access_flags,
1170 uint32_t method_idx,
1171 const DexFile& dex_file,
1172 Handle<mirror::DexCache> dex_cache) const {
David Srbeckyafc97bc2018-07-05 08:14:35 +00001173 Runtime* runtime = Runtime::Current();
1174 ArenaAllocator allocator(runtime->GetArenaPool());
1175 ArenaStack arena_stack(runtime->GetArenaPool());
1176
Vladimir Markoa0431112018-06-25 09:32:54 +01001177 const CompilerOptions& compiler_options = GetCompilerDriver()->GetCompilerOptions();
1178 if (compiler_options.IsBootImage()) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001179 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001180 ArtMethod* method = runtime->GetClassLinker()->LookupResolvedMethod(
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001181 method_idx, dex_cache.Get(), /*class_loader=*/ nullptr);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001182 if (method != nullptr && UNLIKELY(method->IsIntrinsic())) {
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001183 VariableSizedHandleScope handles(soa.Self());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001184 ScopedNullHandle<mirror::ClassLoader> class_loader; // null means boot class path loader.
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001185 Handle<mirror::Class> compiling_class = handles.NewHandle(method->GetDeclaringClass());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001186 DexCompilationUnit dex_compilation_unit(
1187 class_loader,
1188 runtime->GetClassLinker(),
1189 dex_file,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001190 /*code_item=*/ nullptr,
1191 /*class_def_idx=*/ DexFile::kDexNoIndex16,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001192 method_idx,
1193 access_flags,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001194 /*verified_method=*/ nullptr,
1195 dex_cache,
1196 compiling_class);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001197 CodeVectorAllocator code_allocator(&allocator);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001198 // Go to native so that we don't block GC during compilation.
1199 ScopedThreadSuspension sts(soa.Self(), kNative);
1200 std::unique_ptr<CodeGenerator> codegen(
1201 TryCompileIntrinsic(&allocator,
1202 &arena_stack,
1203 &code_allocator,
1204 dex_compilation_unit,
1205 method,
1206 &handles));
1207 if (codegen != nullptr) {
1208 CompiledMethod* compiled_method = Emit(&allocator,
1209 &code_allocator,
1210 codegen.get(),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001211 /* code_item_for_osr_check */ nullptr);
1212 compiled_method->MarkAsIntrinsic();
1213 return compiled_method;
1214 }
1215 }
1216 }
1217
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001218 JniCompiledMethod jni_compiled_method = ArtQuickJniCompileMethod(
Vladimir Markoa0431112018-06-25 09:32:54 +01001219 compiler_options, access_flags, method_idx, dex_file);
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001220 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledNativeStub);
David Srbeckyafc97bc2018-07-05 08:14:35 +00001221
David Srbeckye7a91942018-08-01 17:23:53 +01001222 ScopedArenaAllocator stack_map_allocator(&arena_stack); // Will hold the stack map.
1223 ScopedArenaVector<uint8_t> stack_map = CreateJniStackMap(&stack_map_allocator,
1224 jni_compiled_method);
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001225 return CompiledMethod::SwapAllocCompiledMethod(
Vladimir Marko33f7c8a2018-11-19 10:22:01 +00001226 GetCompilerDriver()->GetCompiledMethodStorage(),
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001227 jni_compiled_method.GetInstructionSet(),
1228 jni_compiled_method.GetCode(),
David Srbeckyafc97bc2018-07-05 08:14:35 +00001229 ArrayRef<const uint8_t>(stack_map),
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001230 jni_compiled_method.GetCfi(),
1231 /* patches */ ArrayRef<const linker::LinkerPatch>());
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001232}
1233
Andreas Gampe53c913b2014-08-12 23:19:23 -07001234Compiler* CreateOptimizingCompiler(CompilerDriver* driver) {
1235 return new OptimizingCompiler(driver);
1236}
1237
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001238bool EncodeArtMethodInInlineInfo(ArtMethod* method ATTRIBUTE_UNUSED) {
1239 // Note: the runtime is null only for unit testing.
1240 return Runtime::Current() == nullptr || !Runtime::Current()->IsAotCompiler();
1241}
1242
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001243bool OptimizingCompiler::JitCompile(Thread* self,
1244 jit::JitCodeCache* code_cache,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001245 ArtMethod* method,
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +01001246 bool baseline,
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001247 bool osr,
1248 jit::JitLogger* jit_logger) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001249 StackHandleScope<3> hs(self);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001250 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1251 method->GetDeclaringClass()->GetClassLoader()));
1252 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001253 DCHECK(method->IsCompilable());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001254
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001255 const DexFile* dex_file = method->GetDexFile();
1256 const uint16_t class_def_idx = method->GetClassDefIndex();
1257 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
1258 const uint32_t method_idx = method->GetDexMethodIndex();
1259 const uint32_t access_flags = method->GetAccessFlags();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001260
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001261 Runtime* runtime = Runtime::Current();
1262 ArenaAllocator allocator(runtime->GetJitArenaPool());
Vladimir Marko2196c652017-11-30 16:16:07 +00001263
1264 if (UNLIKELY(method->IsNative())) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001265 const CompilerOptions& compiler_options = GetCompilerDriver()->GetCompilerOptions();
Vladimir Marko2196c652017-11-30 16:16:07 +00001266 JniCompiledMethod jni_compiled_method = ArtQuickJniCompileMethod(
Vladimir Markoa0431112018-06-25 09:32:54 +01001267 compiler_options, access_flags, method_idx, *dex_file);
Vladimir Markoac3ac682018-09-20 11:01:43 +01001268 std::vector<Handle<mirror::Object>> roots;
Vladimir Marko2196c652017-11-30 16:16:07 +00001269 ArenaSet<ArtMethod*, std::less<ArtMethod*>> cha_single_implementation_list(
1270 allocator.Adapter(kArenaAllocCHA));
David Srbeckyafc97bc2018-07-05 08:14:35 +00001271 ArenaStack arena_stack(runtime->GetJitArenaPool());
1272 // StackMapStream is large and it does not fit into this frame, so we need helper method.
David Srbeckye7a91942018-08-01 17:23:53 +01001273 ScopedArenaAllocator stack_map_allocator(&arena_stack); // Will hold the stack map.
1274 ScopedArenaVector<uint8_t> stack_map = CreateJniStackMap(&stack_map_allocator,
1275 jni_compiled_method);
David Srbeckyafc97bc2018-07-05 08:14:35 +00001276 uint8_t* stack_map_data = nullptr;
David Srbeckyafc97bc2018-07-05 08:14:35 +00001277 uint8_t* roots_data = nullptr;
1278 uint32_t data_size = code_cache->ReserveData(self,
1279 stack_map.size(),
David Srbeckyafc97bc2018-07-05 08:14:35 +00001280 /* number_of_roots */ 0,
1281 method,
1282 &stack_map_data,
David Srbeckyafc97bc2018-07-05 08:14:35 +00001283 &roots_data);
1284 if (stack_map_data == nullptr || roots_data == nullptr) {
1285 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kJitOutOfMemoryForCommit);
1286 return false;
1287 }
1288 memcpy(stack_map_data, stack_map.data(), stack_map.size());
David Srbeckyafc97bc2018-07-05 08:14:35 +00001289
Vladimir Marko2196c652017-11-30 16:16:07 +00001290 const void* code = code_cache->CommitCode(
1291 self,
1292 method,
David Srbeckyafc97bc2018-07-05 08:14:35 +00001293 stack_map_data,
David Srbeckyafc97bc2018-07-05 08:14:35 +00001294 roots_data,
Vladimir Marko2196c652017-11-30 16:16:07 +00001295 jni_compiled_method.GetCode().data(),
1296 jni_compiled_method.GetCode().size(),
David Srbeckyafc97bc2018-07-05 08:14:35 +00001297 data_size,
Vladimir Marko2196c652017-11-30 16:16:07 +00001298 osr,
1299 roots,
1300 /* has_should_deoptimize_flag */ false,
1301 cha_single_implementation_list);
1302 if (code == nullptr) {
1303 return false;
1304 }
1305
David Srbeckyf4886df2017-12-11 16:06:29 +00001306 if (compiler_options.GenerateAnyDebugInfo()) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001307 const auto* method_header = reinterpret_cast<const OatQuickMethodHeader*>(code);
1308 const uintptr_t code_address = reinterpret_cast<uintptr_t>(method_header->GetCode());
1309 debug::MethodDebugInfo info = {};
David Srbeckyc684f332018-01-19 17:38:06 +00001310 DCHECK(info.custom_name.empty());
Vladimir Marko2196c652017-11-30 16:16:07 +00001311 info.dex_file = dex_file;
1312 info.class_def_index = class_def_idx;
1313 info.dex_method_index = method_idx;
1314 info.access_flags = access_flags;
1315 info.code_item = code_item;
1316 info.isa = jni_compiled_method.GetInstructionSet();
1317 info.deduped = false;
1318 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1319 info.is_optimized = true;
1320 info.is_code_address_text_relative = false;
1321 info.code_address = code_address;
1322 info.code_size = jni_compiled_method.GetCode().size();
1323 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
1324 info.code_info = nullptr;
1325 info.cfi = jni_compiled_method.GetCfi();
David Srbeckyc9e02082018-01-24 16:44:02 +00001326 GenerateJitDebugInfo(method, info);
Vladimir Marko2196c652017-11-30 16:16:07 +00001327 }
1328
1329 Runtime::Current()->GetJit()->AddMemoryUsage(method, allocator.BytesUsed());
1330 if (jit_logger != nullptr) {
1331 jit_logger->WriteLog(code, jni_compiled_method.GetCode().size(), method);
1332 }
1333 return true;
1334 }
1335
1336 ArenaStack arena_stack(runtime->GetJitArenaPool());
Vladimir Markoca6fff82017-10-03 14:49:14 +01001337 CodeVectorAllocator code_allocator(&allocator);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001338 VariableSizedHandleScope handles(self);
1339
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001340 std::unique_ptr<CodeGenerator> codegen;
1341 {
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001342 Handle<mirror::Class> compiling_class = handles.NewHandle(method->GetDeclaringClass());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001343 DexCompilationUnit dex_compilation_unit(
1344 class_loader,
1345 runtime->GetClassLinker(),
1346 *dex_file,
1347 code_item,
1348 class_def_idx,
1349 method_idx,
1350 access_flags,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001351 /*verified_method=*/ nullptr,
1352 dex_cache,
1353 compiling_class);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001354
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001355 // Go to native so that we don't block GC during compilation.
1356 ScopedThreadSuspension sts(self, kNative);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001357 codegen.reset(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001358 TryCompile(&allocator,
1359 &arena_stack,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001360 &code_allocator,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001361 dex_compilation_unit,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +00001362 method,
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +01001363 baseline,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001364 osr,
1365 &handles));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001366 if (codegen.get() == nullptr) {
1367 return false;
1368 }
1369 }
1370
David Srbeckye7a91942018-08-01 17:23:53 +01001371 ScopedArenaVector<uint8_t> stack_map = codegen->BuildStackMaps(code_item);
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001372 size_t number_of_roots = codegen->GetNumberOfJitRoots();
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001373 uint8_t* stack_map_data = nullptr;
1374 uint8_t* roots_data = nullptr;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001375 uint32_t data_size = code_cache->ReserveData(self,
David Srbeckye7a91942018-08-01 17:23:53 +01001376 stack_map.size(),
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001377 number_of_roots,
1378 method,
1379 &stack_map_data,
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001380 &roots_data);
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001381 if (stack_map_data == nullptr || roots_data == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001382 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kJitOutOfMemoryForCommit);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001383 return false;
1384 }
David Srbeckye7a91942018-08-01 17:23:53 +01001385 memcpy(stack_map_data, stack_map.data(), stack_map.size());
Vladimir Markoac3ac682018-09-20 11:01:43 +01001386 std::vector<Handle<mirror::Object>> roots;
1387 codegen->EmitJitRoots(code_allocator.GetData(), roots_data, &roots);
1388 // The root Handle<>s filled by the codegen reference entries in the VariableSizedHandleScope.
1389 DCHECK(std::all_of(roots.begin(),
1390 roots.end(),
1391 [&handles](Handle<mirror::Object> root){
1392 return handles.Contains(root.GetReference());
1393 }));
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001394
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001395 const void* code = code_cache->CommitCode(
1396 self,
1397 method,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001398 stack_map_data,
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001399 roots_data,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001400 code_allocator.GetMemory().data(),
Vladimir Markoca1e0382018-04-11 09:58:41 +00001401 code_allocator.GetMemory().size(),
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001402 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001403 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -07001404 roots,
1405 codegen->GetGraph()->HasShouldDeoptimizeFlag(),
1406 codegen->GetGraph()->GetCHASingleImplementationList());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001407
1408 if (code == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001409 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kJitOutOfMemoryForCommit);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001410 code_cache->ClearData(self, stack_map_data, roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001411 return false;
1412 }
1413
David Srbecky91cc06c2016-03-07 16:13:58 +00001414 const CompilerOptions& compiler_options = GetCompilerDriver()->GetCompilerOptions();
David Srbeckyf4886df2017-12-11 16:06:29 +00001415 if (compiler_options.GenerateAnyDebugInfo()) {
David Srbecky5cc349f2015-12-18 15:04:48 +00001416 const auto* method_header = reinterpret_cast<const OatQuickMethodHeader*>(code);
1417 const uintptr_t code_address = reinterpret_cast<uintptr_t>(method_header->GetCode());
Vladimir Marko1b404a82017-09-01 13:35:26 +01001418 debug::MethodDebugInfo info = {};
David Srbeckyc684f332018-01-19 17:38:06 +00001419 DCHECK(info.custom_name.empty());
David Srbecky197160d2016-03-07 17:33:57 +00001420 info.dex_file = dex_file;
1421 info.class_def_index = class_def_idx;
1422 info.dex_method_index = method_idx;
1423 info.access_flags = access_flags;
1424 info.code_item = code_item;
1425 info.isa = codegen->GetInstructionSet();
1426 info.deduped = false;
1427 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1428 info.is_optimized = true;
1429 info.is_code_address_text_relative = false;
1430 info.code_address = code_address;
Vladimir Markoca1e0382018-04-11 09:58:41 +00001431 info.code_size = code_allocator.GetMemory().size();
David Srbecky197160d2016-03-07 17:33:57 +00001432 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
David Srbeckye7a91942018-08-01 17:23:53 +01001433 info.code_info = stack_map.size() == 0 ? nullptr : stack_map_data;
David Srbecky197160d2016-03-07 17:33:57 +00001434 info.cfi = ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data());
David Srbeckyc9e02082018-01-24 16:44:02 +00001435 GenerateJitDebugInfo(method, info);
David Srbecky5cc349f2015-12-18 15:04:48 +00001436 }
1437
Vladimir Markoca6fff82017-10-03 14:49:14 +01001438 Runtime::Current()->GetJit()->AddMemoryUsage(method, allocator.BytesUsed());
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001439 if (jit_logger != nullptr) {
Vladimir Markoca1e0382018-04-11 09:58:41 +00001440 jit_logger->WriteLog(code, code_allocator.GetMemory().size(), method);
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001441 }
Nicolas Geoffraya4f81542016-03-08 16:57:48 +00001442
Vladimir Marko174b2e22017-10-12 13:34:49 +01001443 if (kArenaAllocatorCountAllocations) {
1444 codegen.reset(); // Release codegen's ScopedArenaAllocator for memory accounting.
1445 size_t total_allocated = allocator.BytesAllocated() + arena_stack.PeakBytesAllocated();
1446 if (total_allocated > kArenaAllocatorMemoryReportThreshold) {
1447 MemStats mem_stats(allocator.GetMemStats());
1448 MemStats peak_stats(arena_stack.GetPeakStats());
1449 LOG(INFO) << "Used " << total_allocated << " bytes of arena memory for compiling "
1450 << dex_file->PrettyMethod(method_idx)
1451 << "\n" << Dumpable<MemStats>(mem_stats)
1452 << "\n" << Dumpable<MemStats>(peak_stats);
1453 }
1454 }
1455
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001456 return true;
1457}
1458
Stephen Hines48ba1972018-09-24 13:35:54 -07001459void OptimizingCompiler::GenerateJitDebugInfo(
1460 ArtMethod* method, const debug::MethodDebugInfo& info) {
David Srbeckyc684f332018-01-19 17:38:06 +00001461 const CompilerOptions& compiler_options = GetCompilerDriver()->GetCompilerOptions();
1462 DCHECK(compiler_options.GenerateAnyDebugInfo());
1463
1464 // If both flags are passed, generate full debug info.
1465 const bool mini_debug_info = !compiler_options.GetGenerateDebugInfo();
1466
1467 // Create entry for the single method that we just compiled.
1468 std::vector<uint8_t> elf_file = debug::MakeElfFileForJIT(
Vladimir Markoa0431112018-06-25 09:32:54 +01001469 compiler_options.GetInstructionSet(),
1470 compiler_options.GetInstructionSetFeatures(),
David Srbeckyc684f332018-01-19 17:38:06 +00001471 mini_debug_info,
1472 ArrayRef<const debug::MethodDebugInfo>(&info, 1));
David Srbeckyfb3de3d2018-01-29 16:11:49 +00001473 MutexLock mu(Thread::Current(), *Locks::native_debug_interface_lock_);
David Srbecky440a9b32018-02-15 17:47:29 +00001474 AddNativeDebugInfoForJit(reinterpret_cast<const void*>(info.code_address), elf_file);
David Srbeckyc9e02082018-01-24 16:44:02 +00001475
1476 VLOG(jit)
1477 << "JIT mini-debug-info added for " << ArtMethod::PrettyMethod(method)
1478 << " size=" << PrettySize(elf_file.size())
David Srbecky440a9b32018-02-15 17:47:29 +00001479 << " total_size=" << PrettySize(GetJitNativeDebugInfoMemUsage());
David Srbeckyc684f332018-01-19 17:38:06 +00001480}
1481
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001482} // namespace art