blob: 16abf9d37dd9832e963c1732879c7e20425eb80d [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"
35#include "code_generator.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000036#include "compiled_method.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070037#include "compiler.h"
David Srbeckyc5bfa972016-02-05 15:49:10 +000038#include "debug/elf_debug_writer.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000039#include "debug/method_debug_info.h"
David Sehr9e734c72018-01-04 17:56:19 -080040#include "dex/dex_file_types.h"
Vladimir Marko038924b2019-02-19 15:09:35 +000041#include "driver/compiled_method_storage.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000042#include "driver/compiler_options.h"
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000043#include "driver/dex_compilation_unit.h"
David Brazdil69ba7b72015-06-23 18:27:30 +010044#include "graph_checker.h"
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010045#include "graph_visualizer.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000046#include "inliner.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000047#include "jit/debugger_interface.h"
Nicolas Geoffraya4f81542016-03-08 16:57:48 +000048#include "jit/jit.h"
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +000049#include "jit/jit_code_cache.h"
Nicolas Geoffray01db5f72017-07-19 15:05:49 +010050#include "jit/jit_logger.h"
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +000051#include "jni/quick/jni_compiler.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010052#include "linker/linker_patch.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000053#include "nodes.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000054#include "oat_quick_method_header.h"
Nicolas Geoffray26a25ef2014-09-30 13:54:09 +010055#include "prepare_for_register_allocation.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010056#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070057#include "register_allocator_linear_scan.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070058#include "select_generator.h"
Nicolas Geoffray31596742014-11-24 15:28:45 +000059#include "ssa_builder.h"
Nicolas Geoffray804d0932014-05-02 08:46:00 +010060#include "ssa_liveness_analysis.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000061#include "ssa_phi_elimination.h"
David Srbeckyafc97bc2018-07-05 08:14:35 +000062#include "stack_map_stream.h"
David Srbeckyc6b4dd82015-04-07 20:32:43 +010063#include "utils/assembler.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000064
Vladimir Marko0a516052019-10-14 13:00:44 +000065namespace art {
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000066
Vladimir Marko3a40bf22016-03-22 16:26:33 +000067static constexpr size_t kArenaAllocatorMemoryReportThreshold = 8 * MB;
68
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -070069static constexpr const char* kPassNameSeparator = "$";
70
Nicolas Geoffray787c3072014-03-17 10:20:19 +000071/**
72 * Used by the code generator, to allocate the code in a vector.
73 */
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010074class CodeVectorAllocator final : public CodeAllocator {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000075 public:
Vladimir Markoe764d2e2017-10-05 14:35:55 +010076 explicit CodeVectorAllocator(ArenaAllocator* allocator)
Vladimir Markoca1e0382018-04-11 09:58:41 +000077 : memory_(allocator->Adapter(kArenaAllocCodeBuffer)) {}
Nicolas Geoffray787c3072014-03-17 10:20:19 +000078
Andreas Gampefa6a1b02018-09-07 08:11:55 -070079 uint8_t* Allocate(size_t size) override {
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000080 memory_.resize(size);
Nicolas Geoffray787c3072014-03-17 10:20:19 +000081 return &memory_[0];
82 }
83
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010084 ArrayRef<const uint8_t> GetMemory() const override { return ArrayRef<const uint8_t>(memory_); }
Nicolas Geoffray132d8362016-11-16 09:19:42 +000085 uint8_t* GetData() { return memory_.data(); }
Nicolas Geoffray787c3072014-03-17 10:20:19 +000086
87 private:
Vladimir Markof9f64412015-09-02 14:05:49 +010088 ArenaVector<uint8_t> memory_;
Nicolas Geoffray787c3072014-03-17 10:20:19 +000089
90 DISALLOW_COPY_AND_ASSIGN(CodeVectorAllocator);
91};
92
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010093/**
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010094 * Filter to apply to the visualizer. Methods whose name contain that filter will
David Brazdilee690a32014-12-01 17:04:16 +000095 * be dumped.
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010096 */
Andreas Gampe53fcd0f2015-07-22 12:10:13 -070097static constexpr const char kStringFilter[] = "";
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010098
David Brazdil69ba7b72015-06-23 18:27:30 +010099class PassScope;
David Brazdil809658e2015-02-05 11:34:02 +0000100
David Brazdil69ba7b72015-06-23 18:27:30 +0100101class PassObserver : public ValueObject {
David Brazdil5e8b1372015-01-23 14:39:08 +0000102 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100103 PassObserver(HGraph* graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100104 CodeGenerator* codegen,
105 std::ostream* visualizer_output,
Vladimir Marko038924b2019-02-19 15:09:35 +0000106 const CompilerOptions& compiler_options,
Andreas Gampea0d81af2016-10-27 12:04:57 -0700107 Mutex& dump_mutex)
David Brazdil69ba7b72015-06-23 18:27:30 +0100108 : graph_(graph),
Aart Bika8360cd2018-05-02 16:07:51 -0700109 last_seen_graph_size_(0),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000110 cached_method_name_(),
Vladimir Marko038924b2019-02-19 15:09:35 +0000111 timing_logger_enabled_(compiler_options.GetDumpPassTimings()),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000112 timing_logger_(timing_logger_enabled_ ? GetMethodName() : "", true, true),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100113 disasm_info_(graph->GetAllocator()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700114 visualizer_oss_(),
115 visualizer_output_(visualizer_output),
Vladimir Marko038924b2019-02-19 15:09:35 +0000116 visualizer_enabled_(!compiler_options.GetDumpCfgFileName().empty()),
Vladimir Markoc9fcfd02021-01-05 16:57:30 +0000117 visualizer_(&visualizer_oss_, graph, codegen),
Artem Serov07718842020-02-24 18:51:42 +0000118 codegen_(codegen),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700119 visualizer_dump_mutex_(dump_mutex),
David Brazdil69ba7b72015-06-23 18:27:30 +0100120 graph_in_bad_state_(false) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700121 if (timing_logger_enabled_ || visualizer_enabled_) {
Vladimir Marko038924b2019-02-19 15:09:35 +0000122 if (!IsVerboseMethod(compiler_options, GetMethodName())) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700123 timing_logger_enabled_ = visualizer_enabled_ = false;
124 }
125 if (visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000126 visualizer_.PrintHeader(GetMethodName());
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700127 codegen->SetDisassemblyInformation(&disasm_info_);
128 }
David Brazdil62e074f2015-04-07 18:09:37 +0100129 }
David Brazdil5e8b1372015-01-23 14:39:08 +0000130 }
131
David Brazdil69ba7b72015-06-23 18:27:30 +0100132 ~PassObserver() {
David Brazdil5e8b1372015-01-23 14:39:08 +0000133 if (timing_logger_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000134 LOG(INFO) << "TIMINGS " << GetMethodName();
David Brazdil5e8b1372015-01-23 14:39:08 +0000135 LOG(INFO) << Dumpable<TimingLogger>(timing_logger_);
136 }
Nicolas Geoffray002eac62020-02-04 10:16:51 +0000137 if (visualizer_enabled_) {
138 FlushVisualizer();
139 }
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000140 DCHECK(visualizer_oss_.str().empty());
David Brazdil5e8b1372015-01-23 14:39:08 +0000141 }
142
Nicolas Geoffray002eac62020-02-04 10:16:51 +0000143 void DumpDisassembly() {
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100144 if (visualizer_enabled_) {
145 visualizer_.DumpGraphWithDisassembly();
146 }
147 }
148
David Brazdil69ba7b72015-06-23 18:27:30 +0100149 void SetGraphInBadState() { graph_in_bad_state_ = true; }
150
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000151 const char* GetMethodName() {
152 // PrettyMethod() is expensive, so we delay calling it until we actually have to.
153 if (cached_method_name_.empty()) {
David Sehr709b0702016-10-13 09:12:37 -0700154 cached_method_name_ = graph_->GetDexFile().PrettyMethod(graph_->GetMethodIdx());
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000155 }
156 return cached_method_name_.c_str();
157 }
158
David Brazdil5e8b1372015-01-23 14:39:08 +0000159 private:
Nicolas Geoffray002eac62020-02-04 10:16:51 +0000160 void StartPass(const char* pass_name) {
Wojciech Staszkiewicze7060702016-08-16 17:31:19 -0700161 VLOG(compiler) << "Starting pass: " << pass_name;
David Brazdil809658e2015-02-05 11:34:02 +0000162 // Dump graph first, then start timer.
163 if (visualizer_enabled_) {
Andreas Gampe3db70682018-12-26 15:12:03 -0800164 visualizer_.DumpGraph(pass_name, /* is_after_pass= */ false, graph_in_bad_state_);
David Brazdil809658e2015-02-05 11:34:02 +0000165 }
166 if (timing_logger_enabled_) {
167 timing_logger_.StartTiming(pass_name);
168 }
169 }
170
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000171 void FlushVisualizer() REQUIRES(!visualizer_dump_mutex_) {
172 MutexLock mu(Thread::Current(), visualizer_dump_mutex_);
173 *visualizer_output_ << visualizer_oss_.str();
174 visualizer_output_->flush();
175 visualizer_oss_.str("");
176 visualizer_oss_.clear();
177 }
178
Nicolas Geoffray002eac62020-02-04 10:16:51 +0000179 void EndPass(const char* pass_name, bool pass_change) {
David Brazdil809658e2015-02-05 11:34:02 +0000180 // Pause timer first, then dump graph.
181 if (timing_logger_enabled_) {
182 timing_logger_.EndTiming();
183 }
184 if (visualizer_enabled_) {
Andreas Gampe3db70682018-12-26 15:12:03 -0800185 visualizer_.DumpGraph(pass_name, /* is_after_pass= */ true, graph_in_bad_state_);
David Brazdil809658e2015-02-05 11:34:02 +0000186 }
David Brazdil69ba7b72015-06-23 18:27:30 +0100187
188 // Validate the HGraph if running in debug mode.
189 if (kIsDebugBuild) {
190 if (!graph_in_bad_state_) {
Artem Serov07718842020-02-24 18:51:42 +0000191 GraphChecker checker(graph_, codegen_);
Aart Bika8360cd2018-05-02 16:07:51 -0700192 last_seen_graph_size_ = checker.Run(pass_change, last_seen_graph_size_);
David Brazdilbadd8262016-02-02 16:28:56 +0000193 if (!checker.IsValid()) {
Alex Light3a73ffb2021-01-25 14:11:05 +0000194 LOG(FATAL_WITHOUT_ABORT) << "Error after " << pass_name << "(" << graph_->PrettyMethod()
195 << "): " << *graph_;
196 LOG(FATAL) << "(" << pass_name << "): " << Dumpable<GraphChecker>(checker);
David Brazdil69ba7b72015-06-23 18:27:30 +0100197 }
198 }
199 }
David Brazdil809658e2015-02-05 11:34:02 +0000200 }
201
Vladimir Marko038924b2019-02-19 15:09:35 +0000202 static bool IsVerboseMethod(const CompilerOptions& compiler_options, const char* method_name) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700203 // Test an exact match to --verbose-methods. If verbose-methods is set, this overrides an
204 // empty kStringFilter matching all methods.
Vladimir Marko038924b2019-02-19 15:09:35 +0000205 if (compiler_options.HasVerboseMethods()) {
206 return compiler_options.IsVerboseMethod(method_name);
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700207 }
208
209 // Test the kStringFilter sub-string. constexpr helper variable to silence unreachable-code
210 // warning when the string is empty.
211 constexpr bool kStringFilterEmpty = arraysize(kStringFilter) <= 1;
212 if (kStringFilterEmpty || strstr(method_name, kStringFilter) != nullptr) {
213 return true;
214 }
215
216 return false;
217 }
218
David Brazdil69ba7b72015-06-23 18:27:30 +0100219 HGraph* const graph_;
Aart Bika8360cd2018-05-02 16:07:51 -0700220 size_t last_seen_graph_size_;
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000221
222 std::string cached_method_name_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000223
224 bool timing_logger_enabled_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000225 TimingLogger timing_logger_;
226
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100227 DisassemblyInformation disasm_info_;
228
Andreas Gampea0d81af2016-10-27 12:04:57 -0700229 std::ostringstream visualizer_oss_;
230 std::ostream* visualizer_output_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000231 bool visualizer_enabled_;
232 HGraphVisualizer visualizer_;
Artem Serov07718842020-02-24 18:51:42 +0000233 CodeGenerator* codegen_;
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:
Vladimir Marko038924b2019-02-19 15:09:35 +0000270 explicit OptimizingCompiler(const CompilerOptions& compiler_options,
271 CompiledMethodStorage* storage);
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100272 ~OptimizingCompiler() override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700273
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100274 bool CanCompileMethod(uint32_t method_idx, const DexFile& dex_file) const override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700275
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800276 CompiledMethod* Compile(const dex::CodeItem* code_item,
Andreas Gampe53c913b2014-08-12 23:19:23 -0700277 uint32_t access_flags,
278 InvokeType invoke_type,
279 uint16_t class_def_idx,
280 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000281 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700282 const DexFile& dex_file,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100283 Handle<mirror::DexCache> dex_cache) const override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700284
Andreas Gampe53c913b2014-08-12 23:19:23 -0700285 CompiledMethod* JniCompile(uint32_t access_flags,
286 uint32_t method_idx,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000287 const DexFile& dex_file,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100288 Handle<mirror::DexCache> dex_cache) const override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700289
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100290 uintptr_t GetEntryPointOf(ArtMethod* method) const override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700291 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000292 return reinterpret_cast<uintptr_t>(method->GetEntryPointFromQuickCompiledCodePtrSize(
Vladimir Marko038924b2019-02-19 15:09:35 +0000293 InstructionSetPointerSize(GetCompilerOptions().GetInstructionSet())));
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000294 }
Andreas Gampe53c913b2014-08-12 23:19:23 -0700295
Nicolas Geoffray01db5f72017-07-19 15:05:49 +0100296 bool JitCompile(Thread* self,
297 jit::JitCodeCache* code_cache,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100298 jit::JitMemoryRegion* region,
Nicolas Geoffray01db5f72017-07-19 15:05:49 +0100299 ArtMethod* method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100300 CompilationKind compilation_kind,
Nicolas Geoffray01db5f72017-07-19 15:05:49 +0100301 jit::JitLogger* jit_logger)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100302 override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700303 REQUIRES_SHARED(Locks::mutator_lock_);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000304
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700305 private:
Aart Bik24773202018-04-26 10:28:51 -0700306 bool RunOptimizations(HGraph* graph,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700307 CodeGenerator* codegen,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800308 const DexCompilationUnit& dex_compilation_unit,
309 PassObserver* pass_observer,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800310 const OptimizationDef definitions[],
311 size_t length) const {
312 // Convert definitions to optimization passes.
313 ArenaVector<HOptimization*> optimizations = ConstructOptimizations(
314 definitions,
315 length,
316 graph->GetAllocator(),
317 graph,
318 compilation_stats_.get(),
319 codegen,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100320 dex_compilation_unit);
Aart Bik2ca10eb2017-11-15 15:17:53 -0800321 DCHECK_EQ(length, optimizations.size());
Aart Bik2e148682018-04-18 16:11:12 -0700322 // Run the optimization passes one by one. Any "depends_on" pass refers back to
323 // the most recent occurrence of that pass, skipped or executed.
324 std::bitset<static_cast<size_t>(OptimizationPass::kLast) + 1u> pass_changes;
325 pass_changes[static_cast<size_t>(OptimizationPass::kNone)] = true;
Aart Bik24773202018-04-26 10:28:51 -0700326 bool change = false;
Aart Bik2ca10eb2017-11-15 15:17:53 -0800327 for (size_t i = 0; i < length; ++i) {
Aart Bik2e148682018-04-18 16:11:12 -0700328 if (pass_changes[static_cast<size_t>(definitions[i].depends_on)]) {
329 // Execute the pass and record whether it changed anything.
330 PassScope scope(optimizations[i]->GetPassName(), pass_observer);
331 bool pass_change = optimizations[i]->Run();
332 pass_changes[static_cast<size_t>(definitions[i].pass)] = pass_change;
Aart Bika8360cd2018-05-02 16:07:51 -0700333 if (pass_change) {
334 change = true;
335 } else {
336 scope.SetPassNotChanged();
337 }
Aart Bik2e148682018-04-18 16:11:12 -0700338 } else {
339 // Skip the pass and record that nothing changed.
340 pass_changes[static_cast<size_t>(definitions[i].pass)] = false;
341 }
Aart Bik2ca10eb2017-11-15 15:17:53 -0800342 }
Aart Bik24773202018-04-26 10:28:51 -0700343 return change;
Aart Bik2ca10eb2017-11-15 15:17:53 -0800344 }
345
Aart Bik24773202018-04-26 10:28:51 -0700346 template <size_t length> bool RunOptimizations(
Aart Bik2ca10eb2017-11-15 15:17:53 -0800347 HGraph* graph,
348 CodeGenerator* codegen,
349 const DexCompilationUnit& dex_compilation_unit,
350 PassObserver* pass_observer,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800351 const OptimizationDef (&definitions)[length]) const {
Aart Bik24773202018-04-26 10:28:51 -0700352 return RunOptimizations(
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100353 graph, codegen, dex_compilation_unit, pass_observer, definitions, length);
Aart Bik2ca10eb2017-11-15 15:17:53 -0800354 }
355
356 void RunOptimizations(HGraph* graph,
357 CodeGenerator* codegen,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700358 const DexCompilationUnit& dex_compilation_unit,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100359 PassObserver* pass_observer) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700360
Andreas Gampe53c913b2014-08-12 23:19:23 -0700361 private:
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000362 // Create a 'CompiledMethod' for an optimized graph.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100363 CompiledMethod* Emit(ArenaAllocator* allocator,
David Brazdil58282f42016-01-14 12:45:10 +0000364 CodeVectorAllocator* code_allocator,
365 CodeGenerator* codegen,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800366 const dex::CodeItem* item) const;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000367
368 // Try compiling a method and return the code generator used for
369 // compiling it.
370 // This method:
371 // 1) Builds the graph. Returns null if it failed to build it.
David Brazdil58282f42016-01-14 12:45:10 +0000372 // 2) Transforms the graph to SSA. Returns null if it failed.
373 // 3) Runs optimizations on the graph, including register allocator.
374 // 4) Generates code with the `code_allocator` provided.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100375 CodeGenerator* TryCompile(ArenaAllocator* allocator,
376 ArenaStack* arena_stack,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000377 CodeVectorAllocator* code_allocator,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000378 const DexCompilationUnit& dex_compilation_unit,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000379 ArtMethod* method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100380 CompilationKind compilation_kind,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000381 VariableSizedHandleScope* handles) const;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000382
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000383 CodeGenerator* TryCompileIntrinsic(ArenaAllocator* allocator,
384 ArenaStack* arena_stack,
385 CodeVectorAllocator* code_allocator,
386 const DexCompilationUnit& dex_compilation_unit,
387 ArtMethod* method,
388 VariableSizedHandleScope* handles) const;
389
Aart Bik24773202018-04-26 10:28:51 -0700390 bool RunArchOptimizations(HGraph* graph,
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700391 CodeGenerator* codegen,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800392 const DexCompilationUnit& dex_compilation_unit,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100393 PassObserver* pass_observer) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700394
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100395 bool RunBaselineOptimizations(HGraph* graph,
396 CodeGenerator* codegen,
397 const DexCompilationUnit& dex_compilation_unit,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100398 PassObserver* pass_observer) const;
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100399
David Srbecky41617b12020-03-18 21:19:06 +0000400 std::vector<uint8_t> GenerateJitDebugInfo(const debug::MethodDebugInfo& method_debug_info);
David Srbeckyc684f332018-01-19 17:38:06 +0000401
Fabio Rinaldi52d53542020-02-10 17:28:06 +0000402 // This must be called before any other function that dumps data to the cfg
403 void DumpInstructionSetFeaturesToCfg() const;
404
Calin Juravle2be39e02015-04-21 13:56:34 +0100405 std::unique_ptr<OptimizingCompilerStats> compilation_stats_;
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100406
Andreas Gampe53c913b2014-08-12 23:19:23 -0700407 std::unique_ptr<std::ostream> visualizer_output_;
408
Andreas Gampea0d81af2016-10-27 12:04:57 -0700409 mutable Mutex dump_mutex_; // To synchronize visualizer writing.
410
Andreas Gampe53c913b2014-08-12 23:19:23 -0700411 DISALLOW_COPY_AND_ASSIGN(OptimizingCompiler);
412};
413
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100414static const int kMaximumCompilationTimeBeforeWarning = 100; /* ms */
415
Vladimir Marko038924b2019-02-19 15:09:35 +0000416OptimizingCompiler::OptimizingCompiler(const CompilerOptions& compiler_options,
417 CompiledMethodStorage* storage)
418 : Compiler(compiler_options, storage, kMaximumCompilationTimeBeforeWarning),
419 dump_mutex_("Visualizer dump lock") {
420 // Enable C1visualizer output.
421 const std::string& cfg_file_name = compiler_options.GetDumpCfgFileName();
David Brazdil866c0312015-01-13 21:21:31 +0000422 if (!cfg_file_name.empty()) {
Calin Juravle87000a92015-08-24 15:34:44 +0100423 std::ios_base::openmode cfg_file_mode =
Vladimir Marko038924b2019-02-19 15:09:35 +0000424 compiler_options.GetDumpCfgAppend() ? std::ofstream::app : std::ofstream::out;
Calin Juravle87000a92015-08-24 15:34:44 +0100425 visualizer_output_.reset(new std::ofstream(cfg_file_name, cfg_file_mode));
Fabio Rinaldi52d53542020-02-10 17:28:06 +0000426 DumpInstructionSetFeaturesToCfg();
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100427 }
Vladimir Marko038924b2019-02-19 15:09:35 +0000428 if (compiler_options.GetDumpStats()) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100429 compilation_stats_.reset(new OptimizingCompilerStats());
430 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100431}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000432
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100433OptimizingCompiler::~OptimizingCompiler() {
Calin Juravle2be39e02015-04-21 13:56:34 +0100434 if (compilation_stats_.get() != nullptr) {
435 compilation_stats_->Log();
436 }
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100437}
438
Fabio Rinaldi52d53542020-02-10 17:28:06 +0000439void OptimizingCompiler::DumpInstructionSetFeaturesToCfg() const {
440 const CompilerOptions& compiler_options = GetCompilerOptions();
441 const InstructionSetFeatures* features = compiler_options.GetInstructionSetFeatures();
Evgeny Astigeevich2446feb2020-07-27 12:25:49 +0100442 std::string isa_string =
443 std::string("isa:") + GetInstructionSetString(features->GetInstructionSet());
Fabio Rinaldi52d53542020-02-10 17:28:06 +0000444 std::string features_string = "isa_features:" + features->GetFeatureString();
445 // It is assumed that visualizer_output_ is empty when calling this function, hence the fake
446 // compilation block containing the ISA features will be printed at the beginning of the .cfg
447 // file.
Evgeny Astigeevich2446feb2020-07-27 12:25:49 +0100448 *visualizer_output_
449 << HGraphVisualizer::InsertMetaDataAsCompilationBlock(isa_string + ' ' + features_string);
Fabio Rinaldi52d53542020-02-10 17:28:06 +0000450}
451
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000452bool OptimizingCompiler::CanCompileMethod(uint32_t method_idx ATTRIBUTE_UNUSED,
Vladimir Markodf739842016-03-23 16:59:07 +0000453 const DexFile& dex_file ATTRIBUTE_UNUSED) const {
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000454 return true;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700455}
456
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000457static bool IsInstructionSetSupported(InstructionSet instruction_set) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000458 return instruction_set == InstructionSet::kArm
459 || instruction_set == InstructionSet::kArm64
460 || instruction_set == InstructionSet::kThumb2
Vladimir Marko33bff252017-11-01 14:35:42 +0000461 || instruction_set == InstructionSet::kX86
462 || instruction_set == InstructionSet::kX86_64;
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000463}
464
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100465bool OptimizingCompiler::RunBaselineOptimizations(HGraph* graph,
466 CodeGenerator* codegen,
467 const DexCompilationUnit& dex_compilation_unit,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100468 PassObserver* pass_observer) const {
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100469 switch (codegen->GetCompilerOptions().GetInstructionSet()) {
Vladimir Markod3e9c622020-08-05 12:20:28 +0100470#if defined(ART_ENABLE_CODEGEN_arm)
471 case InstructionSet::kThumb2:
472 case InstructionSet::kArm: {
473 OptimizationDef arm_optimizations[] = {
474 OptDef(OptimizationPass::kCriticalNativeAbiFixupArm),
475 };
476 return RunOptimizations(graph,
477 codegen,
478 dex_compilation_unit,
479 pass_observer,
480 arm_optimizations);
481 }
482#endif
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100483#ifdef ART_ENABLE_CODEGEN_x86
484 case InstructionSet::kX86: {
485 OptimizationDef x86_optimizations[] = {
486 OptDef(OptimizationPass::kPcRelativeFixupsX86),
487 };
488 return RunOptimizations(graph,
489 codegen,
490 dex_compilation_unit,
491 pass_observer,
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100492 x86_optimizations);
493 }
494#endif
495 default:
496 UNUSED(graph);
497 UNUSED(codegen);
498 UNUSED(dex_compilation_unit);
499 UNUSED(pass_observer);
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100500 return false;
501 }
502}
503
Aart Bik24773202018-04-26 10:28:51 -0700504bool OptimizingCompiler::RunArchOptimizations(HGraph* graph,
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700505 CodeGenerator* codegen,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800506 const DexCompilationUnit& dex_compilation_unit,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100507 PassObserver* pass_observer) const {
Vladimir Markoa0431112018-06-25 09:32:54 +0100508 switch (codegen->GetCompilerOptions().GetInstructionSet()) {
Artem Serov2bbc9532016-10-21 11:51:50 +0100509#if defined(ART_ENABLE_CODEGEN_arm)
Vladimir Marko33bff252017-11-01 14:35:42 +0000510 case InstructionSet::kThumb2:
511 case InstructionSet::kArm: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800512 OptimizationDef arm_optimizations[] = {
513 OptDef(OptimizationPass::kInstructionSimplifierArm),
514 OptDef(OptimizationPass::kSideEffectsAnalysis),
515 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
Vladimir Markod3e9c622020-08-05 12:20:28 +0100516 OptDef(OptimizationPass::kCriticalNativeAbiFixupArm),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800517 OptDef(OptimizationPass::kScheduling)
Vladimir Markob4536b72015-11-24 13:45:23 +0000518 };
Aart Bik24773202018-04-26 10:28:51 -0700519 return RunOptimizations(graph,
520 codegen,
521 dex_compilation_unit,
522 pass_observer,
Aart Bik24773202018-04-26 10:28:51 -0700523 arm_optimizations);
Vladimir Markob4536b72015-11-24 13:45:23 +0000524 }
525#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100526#ifdef ART_ENABLE_CODEGEN_arm64
Vladimir Marko33bff252017-11-01 14:35:42 +0000527 case InstructionSet::kArm64: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800528 OptimizationDef arm64_optimizations[] = {
529 OptDef(OptimizationPass::kInstructionSimplifierArm64),
530 OptDef(OptimizationPass::kSideEffectsAnalysis),
531 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
532 OptDef(OptimizationPass::kScheduling)
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100533 };
Aart Bik24773202018-04-26 10:28:51 -0700534 return RunOptimizations(graph,
535 codegen,
536 dex_compilation_unit,
537 pass_observer,
Aart Bik24773202018-04-26 10:28:51 -0700538 arm64_optimizations);
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100539 }
540#endif
Mark Mendell0616ae02015-04-17 12:49:27 -0400541#ifdef ART_ENABLE_CODEGEN_x86
Vladimir Marko33bff252017-11-01 14:35:42 +0000542 case InstructionSet::kX86: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800543 OptimizationDef x86_optimizations[] = {
Shalini Salomi Bodapatidd121f62018-10-26 15:03:53 +0530544 OptDef(OptimizationPass::kInstructionSimplifierX86),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800545 OptDef(OptimizationPass::kSideEffectsAnalysis),
546 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
547 OptDef(OptimizationPass::kPcRelativeFixupsX86),
Hans Boehmf5f56c72018-07-13 00:05:27 +0000548 OptDef(OptimizationPass::kX86MemoryOperandGeneration)
Mark Mendell0616ae02015-04-17 12:49:27 -0400549 };
Aart Bik24773202018-04-26 10:28:51 -0700550 return RunOptimizations(graph,
551 codegen,
552 dex_compilation_unit,
553 pass_observer,
Aart Bik24773202018-04-26 10:28:51 -0700554 x86_optimizations);
Mark Mendell0616ae02015-04-17 12:49:27 -0400555 }
556#endif
Mark Mendellee8d9712016-07-12 11:13:15 -0400557#ifdef ART_ENABLE_CODEGEN_x86_64
Vladimir Marko33bff252017-11-01 14:35:42 +0000558 case InstructionSet::kX86_64: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800559 OptimizationDef x86_64_optimizations[] = {
Shalini Salomi Bodapatidd121f62018-10-26 15:03:53 +0530560 OptDef(OptimizationPass::kInstructionSimplifierX86_64),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800561 OptDef(OptimizationPass::kSideEffectsAnalysis),
562 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
Hans Boehmf5f56c72018-07-13 00:05:27 +0000563 OptDef(OptimizationPass::kX86MemoryOperandGeneration)
Mark Mendellee8d9712016-07-12 11:13:15 -0400564 };
Aart Bik24773202018-04-26 10:28:51 -0700565 return RunOptimizations(graph,
566 codegen,
567 dex_compilation_unit,
568 pass_observer,
Aart Bik24773202018-04-26 10:28:51 -0700569 x86_64_optimizations);
Mark Mendellee8d9712016-07-12 11:13:15 -0400570 }
571#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100572 default:
Aart Bik24773202018-04-26 10:28:51 -0700573 return false;
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100574 }
575}
576
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000577NO_INLINE // Avoid increasing caller's frame size by large stack-allocated objects.
578static void AllocateRegisters(HGraph* graph,
579 CodeGenerator* codegen,
Matthew Gharrity2cd05b72016-08-03 16:57:37 -0700580 PassObserver* pass_observer,
Igor Murashkin6ef45672017-08-08 13:59:55 -0700581 RegisterAllocator::Strategy strategy,
582 OptimizingCompilerStats* stats) {
Mingyao Yang700347e2016-03-02 14:59:32 -0800583 {
584 PassScope scope(PrepareForRegisterAllocation::kPrepareForRegisterAllocationPassName,
585 pass_observer);
Nicolas Geoffray61ba8d22018-08-07 09:55:57 +0100586 PrepareForRegisterAllocation(graph, codegen->GetCompilerOptions(), stats).Run();
Mingyao Yang700347e2016-03-02 14:59:32 -0800587 }
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100588 // Use local allocator shared by SSA liveness analysis and register allocator.
589 // (Register allocator creates new objects in the liveness data.)
590 ScopedArenaAllocator local_allocator(graph->GetArenaStack());
591 SsaLivenessAnalysis liveness(graph, codegen, &local_allocator);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000592 {
593 PassScope scope(SsaLivenessAnalysis::kLivenessPassName, pass_observer);
594 liveness.Analyze();
595 }
596 {
597 PassScope scope(RegisterAllocator::kRegisterAllocatorPassName, pass_observer);
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100598 std::unique_ptr<RegisterAllocator> register_allocator =
599 RegisterAllocator::Create(&local_allocator, codegen, liveness, strategy);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100600 register_allocator->AllocateRegisters();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000601 }
602}
603
Aart Bik2ca10eb2017-11-15 15:17:53 -0800604// Strip pass name suffix to get optimization name.
605static std::string ConvertPassNameToOptimizationName(const std::string& pass_name) {
606 size_t pos = pass_name.find(kPassNameSeparator);
607 return pos == std::string::npos ? pass_name : pass_name.substr(0, pos);
608}
609
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700610void OptimizingCompiler::RunOptimizations(HGraph* graph,
611 CodeGenerator* codegen,
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700612 const DexCompilationUnit& dex_compilation_unit,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100613 PassObserver* pass_observer) const {
Vladimir Marko038924b2019-02-19 15:09:35 +0000614 const std::vector<std::string>* pass_names = GetCompilerOptions().GetPassesToRun();
Aart Bik2ca10eb2017-11-15 15:17:53 -0800615 if (pass_names != nullptr) {
616 // If passes were defined on command-line, build the optimization
617 // passes and run these instead of the built-in optimizations.
Aart Bik2e148682018-04-18 16:11:12 -0700618 // TODO: a way to define depends_on via command-line?
Aart Bik2ca10eb2017-11-15 15:17:53 -0800619 const size_t length = pass_names->size();
620 std::vector<OptimizationDef> optimizations;
621 for (const std::string& pass_name : *pass_names) {
622 std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
Greg Kaisere7e195d2019-03-26 08:13:00 -0700623 optimizations.push_back(OptDef(OptimizationPassByName(opt_name), pass_name.c_str()));
Aart Bik2ca10eb2017-11-15 15:17:53 -0800624 }
625 RunOptimizations(graph,
626 codegen,
627 dex_compilation_unit,
628 pass_observer,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800629 optimizations.data(),
630 length);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700631 return;
632 }
633
Aart Bik24773202018-04-26 10:28:51 -0700634 OptimizationDef optimizations[] = {
Aart Bik2e148682018-04-18 16:11:12 -0700635 // Initial optimizations.
Aart Bik2ca10eb2017-11-15 15:17:53 -0800636 OptDef(OptimizationPass::kConstantFolding),
637 OptDef(OptimizationPass::kInstructionSimplifier),
Aart Bik2e148682018-04-18 16:11:12 -0700638 OptDef(OptimizationPass::kDeadCodeElimination,
639 "dead_code_elimination$initial"),
640 // Inlining.
Aart Bik24773202018-04-26 10:28:51 -0700641 OptDef(OptimizationPass::kInliner),
Aart Bik2e148682018-04-18 16:11:12 -0700642 // Simplification (only if inlining occurred).
643 OptDef(OptimizationPass::kConstantFolding,
644 "constant_folding$after_inlining",
645 OptimizationPass::kInliner),
646 OptDef(OptimizationPass::kInstructionSimplifier,
647 "instruction_simplifier$after_inlining",
648 OptimizationPass::kInliner),
649 OptDef(OptimizationPass::kDeadCodeElimination,
650 "dead_code_elimination$after_inlining",
651 OptimizationPass::kInliner),
652 // GVN.
653 OptDef(OptimizationPass::kSideEffectsAnalysis,
654 "side_effects$before_gvn"),
Aart Bik6d057002018-04-09 15:39:58 -0700655 OptDef(OptimizationPass::kGlobalValueNumbering),
Aart Bik2e148682018-04-18 16:11:12 -0700656 // Simplification (TODO: only if GVN occurred).
Aart Bik2ca10eb2017-11-15 15:17:53 -0800657 OptDef(OptimizationPass::kSelectGenerator),
Aart Bik2e148682018-04-18 16:11:12 -0700658 OptDef(OptimizationPass::kConstantFolding,
659 "constant_folding$after_gvn"),
660 OptDef(OptimizationPass::kInstructionSimplifier,
661 "instruction_simplifier$after_gvn"),
662 OptDef(OptimizationPass::kDeadCodeElimination,
663 "dead_code_elimination$after_gvn"),
664 // High-level optimizations.
665 OptDef(OptimizationPass::kSideEffectsAnalysis,
666 "side_effects$before_licm"),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800667 OptDef(OptimizationPass::kInvariantCodeMotion),
668 OptDef(OptimizationPass::kInductionVarAnalysis),
669 OptDef(OptimizationPass::kBoundsCheckElimination),
670 OptDef(OptimizationPass::kLoopOptimization),
Aart Bik2e148682018-04-18 16:11:12 -0700671 // Simplification.
672 OptDef(OptimizationPass::kConstantFolding,
673 "constant_folding$after_bce"),
Evgeny Astigeevich6587d912020-06-12 10:51:43 +0100674 OptDef(OptimizationPass::kAggressiveInstructionSimplifier,
Aart Bik2e148682018-04-18 16:11:12 -0700675 "instruction_simplifier$after_bce"),
676 // Other high-level optimizations.
Aart Bik2ca10eb2017-11-15 15:17:53 -0800677 OptDef(OptimizationPass::kLoadStoreElimination),
678 OptDef(OptimizationPass::kCHAGuardOptimization),
Aart Bik2e148682018-04-18 16:11:12 -0700679 OptDef(OptimizationPass::kDeadCodeElimination,
680 "dead_code_elimination$final"),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800681 OptDef(OptimizationPass::kCodeSinking),
David Brazdil8993caf2015-12-07 10:04:40 +0000682 // The codegen has a few assumptions that only the instruction simplifier
683 // can satisfy. For example, the code generator does not expect to see a
684 // HTypeConversion from a type to the same type.
Evgeny Astigeevich6587d912020-06-12 10:51:43 +0100685 OptDef(OptimizationPass::kAggressiveInstructionSimplifier,
Aart Bik2e148682018-04-18 16:11:12 -0700686 "instruction_simplifier$before_codegen"),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800687 // Eliminate constructor fences after code sinking to avoid
688 // complicated sinking logic to split a fence with many inputs.
689 OptDef(OptimizationPass::kConstructorFenceRedundancyElimination)
David Brazdil8993caf2015-12-07 10:04:40 +0000690 };
Aart Bik2ca10eb2017-11-15 15:17:53 -0800691 RunOptimizations(graph,
692 codegen,
693 dex_compilation_unit,
694 pass_observer,
Aart Bik24773202018-04-26 10:28:51 -0700695 optimizations);
David Brazdilbbd733e2015-08-18 17:48:17 +0100696
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100697 RunArchOptimizations(graph, codegen, dex_compilation_unit, pass_observer);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000698}
699
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100700static ArenaVector<linker::LinkerPatch> EmitAndSortLinkerPatches(CodeGenerator* codegen) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100701 ArenaVector<linker::LinkerPatch> linker_patches(codegen->GetGraph()->GetAllocator()->Adapter());
Vladimir Marko58155012015-08-19 12:49:41 +0000702 codegen->EmitLinkerPatches(&linker_patches);
703
704 // Sort patches by literal offset. Required for .oat_patches encoding.
705 std::sort(linker_patches.begin(), linker_patches.end(),
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100706 [](const linker::LinkerPatch& lhs, const linker::LinkerPatch& rhs) {
Vladimir Marko58155012015-08-19 12:49:41 +0000707 return lhs.LiteralOffset() < rhs.LiteralOffset();
708 });
709
710 return linker_patches;
711}
712
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100713CompiledMethod* OptimizingCompiler::Emit(ArenaAllocator* allocator,
David Brazdil58282f42016-01-14 12:45:10 +0000714 CodeVectorAllocator* code_allocator,
715 CodeGenerator* codegen,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800716 const dex::CodeItem* code_item_for_osr_check) const {
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100717 ArenaVector<linker::LinkerPatch> linker_patches = EmitAndSortLinkerPatches(codegen);
David Srbeckye7a91942018-08-01 17:23:53 +0100718 ScopedArenaVector<uint8_t> stack_map = codegen->BuildStackMaps(code_item_for_osr_check);
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000719
Vladimir Marko038924b2019-02-19 15:09:35 +0000720 CompiledMethodStorage* storage = GetCompiledMethodStorage();
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100721 CompiledMethod* compiled_method = CompiledMethod::SwapAllocCompiledMethod(
Vladimir Marko038924b2019-02-19 15:09:35 +0000722 storage,
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000723 codegen->GetInstructionSet(),
Vladimir Markoca1e0382018-04-11 09:58:41 +0000724 code_allocator->GetMemory(),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100725 ArrayRef<const uint8_t>(stack_map),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100726 ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data()),
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100727 ArrayRef<const linker::LinkerPatch>(linker_patches));
Mathieu Chartiered150002015-08-28 11:16:54 -0700728
Vladimir Markoca1e0382018-04-11 09:58:41 +0000729 for (const linker::LinkerPatch& patch : linker_patches) {
730 if (codegen->NeedsThunkCode(patch) && storage->GetThunkCode(patch).empty()) {
731 ArenaVector<uint8_t> code(allocator->Adapter());
732 std::string debug_name;
733 codegen->EmitThunkCode(patch, &code, &debug_name);
734 storage->SetThunkCode(patch, ArrayRef<const uint8_t>(code), debug_name);
735 }
736 }
737
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100738 return compiled_method;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000739}
740
Vladimir Markoca6fff82017-10-03 14:49:14 +0100741CodeGenerator* OptimizingCompiler::TryCompile(ArenaAllocator* allocator,
742 ArenaStack* arena_stack,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000743 CodeVectorAllocator* code_allocator,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000744 const DexCompilationUnit& dex_compilation_unit,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000745 ArtMethod* method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100746 CompilationKind compilation_kind,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000747 VariableSizedHandleScope* handles) const {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000748 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kAttemptBytecodeCompilation);
Vladimir Marko038924b2019-02-19 15:09:35 +0000749 const CompilerOptions& compiler_options = GetCompilerOptions();
Vladimir Markoa0431112018-06-25 09:32:54 +0100750 InstructionSet instruction_set = compiler_options.GetInstructionSet();
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000751 const DexFile& dex_file = *dex_compilation_unit.GetDexFile();
752 uint32_t method_idx = dex_compilation_unit.GetDexMethodIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800753 const dex::CodeItem* code_item = dex_compilation_unit.GetCodeItem();
Calin Juravlecff8cc72015-10-09 12:03:24 +0100754
Roland Levillain3b359c72015-11-17 19:35:12 +0000755 // Always use the Thumb-2 assembler: some runtime functionality
756 // (like implicit stack overflow checks) assume Thumb-2.
Vladimir Marko33bff252017-11-01 14:35:42 +0000757 DCHECK_NE(instruction_set, InstructionSet::kArm);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100758
759 // Do not attempt to compile on architectures we do not support.
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000760 if (!IsInstructionSetSupported(instruction_set)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700761 MaybeRecordStat(compilation_stats_.get(),
762 MethodCompilationStat::kNotCompiledUnsupportedIsa);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100763 return nullptr;
764 }
765
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000766 if (Compiler::IsPathologicalCase(*code_item, method_idx, dex_file)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000767 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledPathological);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000768 return nullptr;
769 }
770
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000771 // Implementation of the space filter: do not compile a code item whose size in
Nicolas Geoffray432bf3d2015-07-17 11:11:09 +0100772 // code units is bigger than 128.
773 static constexpr size_t kSpaceFilterOptimizingThreshold = 128;
Andreas Gampe29d38e72016-03-23 15:31:51 +0000774 if ((compiler_options.GetCompilerFilter() == CompilerFilter::kSpace)
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800775 && (CodeItemInstructionAccessor(dex_file, code_item).InsnsSizeInCodeUnits() >
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800776 kSpaceFilterOptimizingThreshold)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000777 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledSpaceFilter);
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000778 return nullptr;
779 }
780
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800781 CodeItemDebugInfoAccessor code_item_accessor(dex_file, code_item, method_idx);
Hans Boehm206348c2018-12-05 11:11:33 -0800782
783 bool dead_reference_safe;
Hans Boehm206348c2018-12-05 11:11:33 -0800784 // For AOT compilation, we may not get a method, for example if its class is erroneous,
785 // possibly due to an unavailable superclass. JIT should always have a method.
786 DCHECK(Runtime::Current()->IsAotCompiler() || method != nullptr);
787 if (method != nullptr) {
788 const dex::ClassDef* containing_class;
789 {
790 ScopedObjectAccess soa(Thread::Current());
791 containing_class = &method->GetClassDef();
Hans Boehm206348c2018-12-05 11:11:33 -0800792 }
793 // MethodContainsRSensitiveAccess is currently slow, but HasDeadReferenceSafeAnnotation()
794 // is currently rarely true.
795 dead_reference_safe =
796 annotations::HasDeadReferenceSafeAnnotation(dex_file, *containing_class)
797 && !annotations::MethodContainsRSensitiveAccess(dex_file, *containing_class, method_idx);
798 } else {
799 // If we could not resolve the class, conservatively assume it's dead-reference unsafe.
800 dead_reference_safe = false;
801 }
802
Vladimir Markoca6fff82017-10-03 14:49:14 +0100803 HGraph* graph = new (allocator) HGraph(
804 allocator,
805 arena_stack,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100806 handles,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000807 dex_file,
808 method_idx,
Vladimir Markoa0431112018-06-25 09:32:54 +0100809 compiler_options.GetInstructionSet(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000810 kInvalidInvokeType,
Hans Boehm206348c2018-12-05 11:11:33 -0800811 dead_reference_safe,
Vladimir Marko038924b2019-02-19 15:09:35 +0000812 compiler_options.GetDebuggable(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100813 compilation_kind);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000814
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000815 if (method != nullptr) {
816 graph->SetArtMethod(method);
David Brazdilbadd8262016-02-02 16:28:56 +0000817 }
818
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000819 std::unique_ptr<CodeGenerator> codegen(
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000820 CodeGenerator::Create(graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100821 compiler_options,
Calin Juravle2ae48182016-03-16 14:05:09 +0000822 compilation_stats_.get()));
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000823 if (codegen.get() == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000824 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledNoCodegen);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000825 return nullptr;
826 }
Vladimir Marko038924b2019-02-19 15:09:35 +0000827 codegen->GetAssembler()->cfi().SetEnabled(compiler_options.GenerateAnyDebugInfo());
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000828
David Brazdil69ba7b72015-06-23 18:27:30 +0100829 PassObserver pass_observer(graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100830 codegen.get(),
831 visualizer_output_.get(),
Vladimir Marko038924b2019-02-19 15:09:35 +0000832 compiler_options,
Andreas Gampea0d81af2016-10-27 12:04:57 -0700833 dump_mutex_);
David Brazdil5e8b1372015-01-23 14:39:08 +0000834
David Brazdil809658e2015-02-05 11:34:02 +0000835 {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000836 VLOG(compiler) << "Building " << pass_observer.GetMethodName();
837 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
838 HGraphBuilder builder(graph,
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800839 code_item_accessor,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000840 &dex_compilation_unit,
841 &dex_compilation_unit,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000842 codegen.get(),
Nicolas Geoffray4924ea92021-03-23 08:25:31 +0000843 compilation_stats_.get());
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000844 GraphAnalysisResult result = builder.BuildGraph();
845 if (result != kAnalysisSuccess) {
846 switch (result) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700847 case kAnalysisSkipped: {
848 MaybeRecordStat(compilation_stats_.get(),
849 MethodCompilationStat::kNotCompiledSkipped);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000850 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100851 }
Igor Murashkin1e065a52017-08-09 13:20:34 -0700852 case kAnalysisInvalidBytecode: {
853 MaybeRecordStat(compilation_stats_.get(),
854 MethodCompilationStat::kNotCompiledInvalidBytecode);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000855 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100856 }
Igor Murashkin1e065a52017-08-09 13:20:34 -0700857 case kAnalysisFailThrowCatchLoop: {
858 MaybeRecordStat(compilation_stats_.get(),
859 MethodCompilationStat::kNotCompiledThrowCatchLoop);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000860 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100861 }
Igor Murashkin1e065a52017-08-09 13:20:34 -0700862 case kAnalysisFailAmbiguousArrayOp: {
863 MaybeRecordStat(compilation_stats_.get(),
864 MethodCompilationStat::kNotCompiledAmbiguousArrayOp);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000865 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100866 }
Nicolas Geoffray0846a8f2018-09-12 15:21:07 +0100867 case kAnalysisFailIrreducibleLoopAndStringInit: {
868 MaybeRecordStat(compilation_stats_.get(),
869 MethodCompilationStat::kNotCompiledIrreducibleLoopAndStringInit);
870 break;
871 }
Nicolas Geoffray7cfc8f52019-08-07 10:41:09 +0100872 case kAnalysisFailPhiEquivalentInOsr: {
873 MaybeRecordStat(compilation_stats_.get(),
874 MethodCompilationStat::kNotCompiledPhiEquivalentInOsr);
875 break;
876 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000877 case kAnalysisSuccess:
878 UNREACHABLE();
David Brazdil809658e2015-02-05 11:34:02 +0000879 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000880 pass_observer.SetGraphInBadState();
881 return nullptr;
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000882 }
David Brazdilbadd8262016-02-02 16:28:56 +0000883 }
Vladimir Markof9f64412015-09-02 14:05:49 +0100884
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100885 if (compilation_kind == CompilationKind::kBaseline) {
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100886 RunBaselineOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer);
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100887 } else {
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100888 RunOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer);
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100889 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000890
891 RegisterAllocator::Strategy regalloc_strategy =
892 compiler_options.GetRegisterAllocationStrategy();
Igor Murashkin1e065a52017-08-09 13:20:34 -0700893 AllocateRegisters(graph,
894 codegen.get(),
895 &pass_observer,
Igor Murashkin6ef45672017-08-08 13:59:55 -0700896 regalloc_strategy,
897 compilation_stats_.get());
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000898
899 codegen->Compile(code_allocator);
900 pass_observer.DumpDisassembly();
901
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000902 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledBytecode);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000903 return codegen.release();
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000904}
905
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000906CodeGenerator* OptimizingCompiler::TryCompileIntrinsic(
907 ArenaAllocator* allocator,
908 ArenaStack* arena_stack,
909 CodeVectorAllocator* code_allocator,
910 const DexCompilationUnit& dex_compilation_unit,
911 ArtMethod* method,
912 VariableSizedHandleScope* handles) const {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000913 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kAttemptIntrinsicCompilation);
Vladimir Marko038924b2019-02-19 15:09:35 +0000914 const CompilerOptions& compiler_options = GetCompilerOptions();
Vladimir Markoa0431112018-06-25 09:32:54 +0100915 InstructionSet instruction_set = compiler_options.GetInstructionSet();
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000916 const DexFile& dex_file = *dex_compilation_unit.GetDexFile();
917 uint32_t method_idx = dex_compilation_unit.GetDexMethodIndex();
918
919 // Always use the Thumb-2 assembler: some runtime functionality
920 // (like implicit stack overflow checks) assume Thumb-2.
921 DCHECK_NE(instruction_set, InstructionSet::kArm);
922
923 // Do not attempt to compile on architectures we do not support.
924 if (!IsInstructionSetSupported(instruction_set)) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000925 return nullptr;
926 }
927
928 HGraph* graph = new (allocator) HGraph(
929 allocator,
930 arena_stack,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100931 handles,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000932 dex_file,
933 method_idx,
Vladimir Marko2afaff72018-11-30 17:01:50 +0000934 compiler_options.GetInstructionSet(),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000935 kInvalidInvokeType,
Hans Boehm206348c2018-12-05 11:11:33 -0800936 /* dead_reference_safe= */ true, // Intrinsics don't affect dead reference safety.
Vladimir Marko2afaff72018-11-30 17:01:50 +0000937 compiler_options.GetDebuggable(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100938 CompilationKind::kOptimized);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000939
940 DCHECK(Runtime::Current()->IsAotCompiler());
941 DCHECK(method != nullptr);
942 graph->SetArtMethod(method);
943
944 std::unique_ptr<CodeGenerator> codegen(
945 CodeGenerator::Create(graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100946 compiler_options,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000947 compilation_stats_.get()));
948 if (codegen.get() == nullptr) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000949 return nullptr;
950 }
Vladimir Markoa0431112018-06-25 09:32:54 +0100951 codegen->GetAssembler()->cfi().SetEnabled(compiler_options.GenerateAnyDebugInfo());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000952
953 PassObserver pass_observer(graph,
954 codegen.get(),
955 visualizer_output_.get(),
Vladimir Marko038924b2019-02-19 15:09:35 +0000956 compiler_options,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000957 dump_mutex_);
958
959 {
960 VLOG(compiler) << "Building intrinsic graph " << pass_observer.GetMethodName();
961 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
962 HGraphBuilder builder(graph,
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800963 CodeItemDebugInfoAccessor(), // Null code item.
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000964 &dex_compilation_unit,
965 &dex_compilation_unit,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000966 codegen.get(),
Nicolas Geoffray4924ea92021-03-23 08:25:31 +0000967 compilation_stats_.get());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000968 builder.BuildIntrinsicGraph(method);
969 }
970
Aart Bik2ca10eb2017-11-15 15:17:53 -0800971 OptimizationDef optimizations[] = {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +0100972 // The codegen has a few assumptions that only the instruction simplifier
973 // can satisfy.
Aart Bik2ca10eb2017-11-15 15:17:53 -0800974 OptDef(OptimizationPass::kInstructionSimplifier),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000975 };
Aart Bik2ca10eb2017-11-15 15:17:53 -0800976 RunOptimizations(graph,
977 codegen.get(),
978 dex_compilation_unit,
979 &pass_observer,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800980 optimizations);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000981
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100982 RunArchOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000983
984 AllocateRegisters(graph,
985 codegen.get(),
986 &pass_observer,
Vladimir Marko038924b2019-02-19 15:09:35 +0000987 compiler_options.GetRegisterAllocationStrategy(),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000988 compilation_stats_.get());
989 if (!codegen->IsLeafMethod()) {
990 VLOG(compiler) << "Intrinsic method is not leaf: " << method->GetIntrinsic()
991 << " " << graph->PrettyMethod();
992 return nullptr;
993 }
994
995 codegen->Compile(code_allocator);
996 pass_observer.DumpDisassembly();
997
998 VLOG(compiler) << "Compiled intrinsic: " << method->GetIntrinsic()
999 << " " << graph->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001000 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledIntrinsic);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001001 return codegen.release();
1002}
1003
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001004CompiledMethod* OptimizingCompiler::Compile(const dex::CodeItem* code_item,
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001005 uint32_t access_flags,
1006 InvokeType invoke_type,
1007 uint16_t class_def_idx,
1008 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001009 Handle<mirror::ClassLoader> jclass_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -07001010 const DexFile& dex_file,
1011 Handle<mirror::DexCache> dex_cache) const {
Vladimir Marko038924b2019-02-19 15:09:35 +00001012 const CompilerOptions& compiler_options = GetCompilerOptions();
Vladimir Marko695348f2020-05-19 14:42:02 +01001013 DCHECK(compiler_options.IsAotCompiler());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001014 CompiledMethod* compiled_method = nullptr;
1015 Runtime* runtime = Runtime::Current();
1016 DCHECK(runtime->IsAotCompiler());
Nicolas Geoffray9e050ab2021-07-14 14:59:25 +01001017 ArenaAllocator allocator(runtime->GetArenaPool());
1018 ArenaStack arena_stack(runtime->GetArenaPool());
1019 CodeVectorAllocator code_allocator(&allocator);
1020 std::unique_ptr<CodeGenerator> codegen;
1021 bool compiled_intrinsic = false;
1022 {
1023 ScopedObjectAccess soa(Thread::Current());
1024 ArtMethod* method =
1025 runtime->GetClassLinker()->ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
1026 method_idx, dex_cache, jclass_loader, /*referrer=*/ nullptr, invoke_type);
1027 DCHECK_EQ(method == nullptr, soa.Self()->IsExceptionPending());
1028 soa.Self()->ClearException(); // Suppress exception if any.
1029 VariableSizedHandleScope handles(soa.Self());
1030 Handle<mirror::Class> compiling_class =
1031 handles.NewHandle(method != nullptr ? method->GetDeclaringClass() : nullptr);
1032 DexCompilationUnit dex_compilation_unit(
1033 jclass_loader,
1034 runtime->GetClassLinker(),
1035 dex_file,
1036 code_item,
1037 class_def_idx,
1038 method_idx,
1039 access_flags,
1040 /*verified_method=*/ nullptr, // Not needed by the Optimizing compiler.
1041 dex_cache,
1042 compiling_class);
1043 // All signature polymorphic methods are native.
1044 DCHECK(method == nullptr || !method->IsSignaturePolymorphic());
1045 // Go to native so that we don't block GC during compilation.
1046 ScopedThreadSuspension sts(soa.Self(), kNative);
1047 // Try to compile a fully intrinsified implementation.
1048 if (method != nullptr && UNLIKELY(method->IsIntrinsic())) {
1049 DCHECK(compiler_options.IsBootImage());
1050 codegen.reset(
1051 TryCompileIntrinsic(&allocator,
1052 &arena_stack,
1053 &code_allocator,
1054 dex_compilation_unit,
1055 method,
1056 &handles));
1057 if (codegen != nullptr) {
1058 compiled_intrinsic = true;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001059 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001060 }
Nicolas Geoffray9e050ab2021-07-14 14:59:25 +01001061 if (codegen == nullptr) {
1062 codegen.reset(
1063 TryCompile(&allocator,
1064 &arena_stack,
1065 &code_allocator,
1066 dex_compilation_unit,
1067 method,
1068 compiler_options.IsBaseline()
1069 ? CompilationKind::kBaseline
1070 : CompilationKind::kOptimized,
1071 &handles));
1072 }
1073 }
1074 if (codegen.get() != nullptr) {
1075 compiled_method = Emit(&allocator,
1076 &code_allocator,
1077 codegen.get(),
1078 compiled_intrinsic ? nullptr : code_item);
1079 if (compiled_intrinsic) {
1080 compiled_method->MarkAsIntrinsic();
1081 }
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001082
Nicolas Geoffray9e050ab2021-07-14 14:59:25 +01001083 if (kArenaAllocatorCountAllocations) {
1084 codegen.reset(); // Release codegen's ScopedArenaAllocator for memory accounting.
1085 size_t total_allocated = allocator.BytesAllocated() + arena_stack.PeakBytesAllocated();
1086 if (total_allocated > kArenaAllocatorMemoryReportThreshold) {
1087 MemStats mem_stats(allocator.GetMemStats());
1088 MemStats peak_stats(arena_stack.GetPeakStats());
1089 LOG(INFO) << "Used " << total_allocated << " bytes of arena memory for compiling "
1090 << dex_file.PrettyMethod(method_idx)
1091 << "\n" << Dumpable<MemStats>(mem_stats)
1092 << "\n" << Dumpable<MemStats>(peak_stats);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001093 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001094 }
1095 }
1096
Calin Juravlecff8cc72015-10-09 12:03:24 +01001097 if (kIsDebugBuild &&
David Srbecky4fa07a52020-03-31 20:52:09 +01001098 compiler_options.CompileArtTest() &&
Vladimir Marko2afaff72018-11-30 17:01:50 +00001099 IsInstructionSetSupported(compiler_options.GetInstructionSet())) {
Roland Levillain0d5a2812015-11-13 10:07:31 +00001100 // For testing purposes, we put a special marker on method names
Goran Jakovljevic9c4f0d8f2017-04-05 16:27:25 +02001101 // that should be compiled with this compiler (when the
1102 // instruction set is supported). This makes sure we're not
Roland Levillain0d5a2812015-11-13 10:07:31 +00001103 // regressing.
David Sehr709b0702016-10-13 09:12:37 -07001104 std::string method_name = dex_file.PrettyMethod(method_idx);
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001105 bool shouldCompile = method_name.find("$opt$") != std::string::npos;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001106 DCHECK((compiled_method != nullptr) || !shouldCompile) << "Didn't compile " << method_name;
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001107 }
1108
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001109 return compiled_method;
1110}
1111
David Srbeckye7a91942018-08-01 17:23:53 +01001112static ScopedArenaVector<uint8_t> CreateJniStackMap(ScopedArenaAllocator* allocator,
David Srbecky17b4d2b2021-03-02 18:14:31 +00001113 const JniCompiledMethod& jni_compiled_method,
1114 size_t code_size) {
Vladimir Markoced04832018-07-26 14:42:17 +01001115 // StackMapStream is quite large, so allocate it using the ScopedArenaAllocator
1116 // to stay clear of the frame size limit.
1117 std::unique_ptr<StackMapStream> stack_map_stream(
David Srbeckye7a91942018-08-01 17:23:53 +01001118 new (allocator) StackMapStream(allocator, jni_compiled_method.GetInstructionSet()));
Vladimir Markoced04832018-07-26 14:42:17 +01001119 stack_map_stream->BeginMethod(
David Srbeckyafc97bc2018-07-05 08:14:35 +00001120 jni_compiled_method.GetFrameSize(),
1121 jni_compiled_method.GetCoreSpillMask(),
1122 jni_compiled_method.GetFpSpillMask(),
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001123 /* num_dex_registers= */ 0,
1124 /* baseline= */ false);
David Srbecky17b4d2b2021-03-02 18:14:31 +00001125 stack_map_stream->EndMethod(code_size);
David Srbeckye7a91942018-08-01 17:23:53 +01001126 return stack_map_stream->Encode();
David Srbeckyafc97bc2018-07-05 08:14:35 +00001127}
1128
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001129CompiledMethod* OptimizingCompiler::JniCompile(uint32_t access_flags,
1130 uint32_t method_idx,
1131 const DexFile& dex_file,
1132 Handle<mirror::DexCache> dex_cache) const {
David Srbeckyafc97bc2018-07-05 08:14:35 +00001133 Runtime* runtime = Runtime::Current();
1134 ArenaAllocator allocator(runtime->GetArenaPool());
1135 ArenaStack arena_stack(runtime->GetArenaPool());
1136
Vladimir Marko038924b2019-02-19 15:09:35 +00001137 const CompilerOptions& compiler_options = GetCompilerOptions();
Vladimir Markoa0431112018-06-25 09:32:54 +01001138 if (compiler_options.IsBootImage()) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001139 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001140 ArtMethod* method = runtime->GetClassLinker()->LookupResolvedMethod(
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001141 method_idx, dex_cache.Get(), /*class_loader=*/ nullptr);
Vladimir Marko43d57552020-09-07 12:30:17 +00001142 // Try to compile a fully intrinsified implementation. Do not try to do this for
1143 // signature polymorphic methods as the InstructionBuilder cannot handle them;
1144 // and it would be useless as they always have a slow path for type conversions.
1145 if (method != nullptr && UNLIKELY(method->IsIntrinsic()) && !method->IsSignaturePolymorphic()) {
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001146 VariableSizedHandleScope handles(soa.Self());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001147 ScopedNullHandle<mirror::ClassLoader> class_loader; // null means boot class path loader.
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001148 Handle<mirror::Class> compiling_class = handles.NewHandle(method->GetDeclaringClass());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001149 DexCompilationUnit dex_compilation_unit(
1150 class_loader,
1151 runtime->GetClassLinker(),
1152 dex_file,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001153 /*code_item=*/ nullptr,
1154 /*class_def_idx=*/ DexFile::kDexNoIndex16,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001155 method_idx,
1156 access_flags,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001157 /*verified_method=*/ nullptr,
1158 dex_cache,
1159 compiling_class);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001160 CodeVectorAllocator code_allocator(&allocator);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001161 // Go to native so that we don't block GC during compilation.
1162 ScopedThreadSuspension sts(soa.Self(), kNative);
1163 std::unique_ptr<CodeGenerator> codegen(
1164 TryCompileIntrinsic(&allocator,
1165 &arena_stack,
1166 &code_allocator,
1167 dex_compilation_unit,
1168 method,
1169 &handles));
1170 if (codegen != nullptr) {
1171 CompiledMethod* compiled_method = Emit(&allocator,
1172 &code_allocator,
1173 codegen.get(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001174 /* item= */ nullptr);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001175 compiled_method->MarkAsIntrinsic();
1176 return compiled_method;
1177 }
1178 }
1179 }
1180
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001181 JniCompiledMethod jni_compiled_method = ArtQuickJniCompileMethod(
Vladimir Markoa0431112018-06-25 09:32:54 +01001182 compiler_options, access_flags, method_idx, dex_file);
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001183 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledNativeStub);
David Srbeckyafc97bc2018-07-05 08:14:35 +00001184
David Srbeckye7a91942018-08-01 17:23:53 +01001185 ScopedArenaAllocator stack_map_allocator(&arena_stack); // Will hold the stack map.
David Srbecky17b4d2b2021-03-02 18:14:31 +00001186 ScopedArenaVector<uint8_t> stack_map = CreateJniStackMap(
1187 &stack_map_allocator, jni_compiled_method, jni_compiled_method.GetCode().size());
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001188 return CompiledMethod::SwapAllocCompiledMethod(
Vladimir Marko038924b2019-02-19 15:09:35 +00001189 GetCompiledMethodStorage(),
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001190 jni_compiled_method.GetInstructionSet(),
1191 jni_compiled_method.GetCode(),
David Srbeckyafc97bc2018-07-05 08:14:35 +00001192 ArrayRef<const uint8_t>(stack_map),
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001193 jni_compiled_method.GetCfi(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001194 /* patches= */ ArrayRef<const linker::LinkerPatch>());
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001195}
1196
Vladimir Marko038924b2019-02-19 15:09:35 +00001197Compiler* CreateOptimizingCompiler(const CompilerOptions& compiler_options,
1198 CompiledMethodStorage* storage) {
1199 return new OptimizingCompiler(compiler_options, storage);
Andreas Gampe53c913b2014-08-12 23:19:23 -07001200}
1201
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001202bool EncodeArtMethodInInlineInfo(ArtMethod* method ATTRIBUTE_UNUSED) {
1203 // Note: the runtime is null only for unit testing.
1204 return Runtime::Current() == nullptr || !Runtime::Current()->IsAotCompiler();
1205}
1206
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001207bool OptimizingCompiler::JitCompile(Thread* self,
1208 jit::JitCodeCache* code_cache,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +01001209 jit::JitMemoryRegion* region,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001210 ArtMethod* method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001211 CompilationKind compilation_kind,
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001212 jit::JitLogger* jit_logger) {
Vladimir Marko695348f2020-05-19 14:42:02 +01001213 const CompilerOptions& compiler_options = GetCompilerOptions();
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001214 // If the baseline flag was explicitly passed, change the compilation kind
1215 // from optimized to baseline.
1216 if (compiler_options.IsBaseline() && compilation_kind == CompilationKind::kOptimized) {
1217 compilation_kind = CompilationKind::kBaseline;
1218 }
Vladimir Marko695348f2020-05-19 14:42:02 +01001219 DCHECK(compiler_options.IsJitCompiler());
1220 DCHECK_EQ(compiler_options.IsJitCompilerForSharedCode(), code_cache->IsSharedRegion(*region));
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001221 StackHandleScope<3> hs(self);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001222 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1223 method->GetDeclaringClass()->GetClassLoader()));
1224 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001225 DCHECK(method->IsCompilable());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001226
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001227 const DexFile* dex_file = method->GetDexFile();
1228 const uint16_t class_def_idx = method->GetClassDefIndex();
Nicolas Geoffray47171752020-08-31 15:03:20 +01001229 const dex::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001230 const uint32_t method_idx = method->GetDexMethodIndex();
1231 const uint32_t access_flags = method->GetAccessFlags();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001232
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001233 Runtime* runtime = Runtime::Current();
1234 ArenaAllocator allocator(runtime->GetJitArenaPool());
Vladimir Marko2196c652017-11-30 16:16:07 +00001235
1236 if (UNLIKELY(method->IsNative())) {
1237 JniCompiledMethod jni_compiled_method = ArtQuickJniCompileMethod(
Vladimir Markoa0431112018-06-25 09:32:54 +01001238 compiler_options, access_flags, method_idx, *dex_file);
Vladimir Markoac3ac682018-09-20 11:01:43 +01001239 std::vector<Handle<mirror::Object>> roots;
Vladimir Marko2196c652017-11-30 16:16:07 +00001240 ArenaSet<ArtMethod*, std::less<ArtMethod*>> cha_single_implementation_list(
1241 allocator.Adapter(kArenaAllocCHA));
David Srbeckyafc97bc2018-07-05 08:14:35 +00001242 ArenaStack arena_stack(runtime->GetJitArenaPool());
1243 // StackMapStream is large and it does not fit into this frame, so we need helper method.
David Srbeckye7a91942018-08-01 17:23:53 +01001244 ScopedArenaAllocator stack_map_allocator(&arena_stack); // Will hold the stack map.
David Srbecky17b4d2b2021-03-02 18:14:31 +00001245 ScopedArenaVector<uint8_t> stack_map = CreateJniStackMap(
1246 &stack_map_allocator, jni_compiled_method, jni_compiled_method.GetCode().size());
David Srbeckyadb66f92019-10-10 12:59:43 +00001247
1248 ArrayRef<const uint8_t> reserved_code;
1249 ArrayRef<const uint8_t> reserved_data;
1250 if (!code_cache->Reserve(self,
1251 region,
1252 jni_compiled_method.GetCode().size(),
1253 stack_map.size(),
1254 /* number_of_roots= */ 0,
1255 method,
1256 /*out*/ &reserved_code,
1257 /*out*/ &reserved_data)) {
David Srbeckyafc97bc2018-07-05 08:14:35 +00001258 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kJitOutOfMemoryForCommit);
1259 return false;
1260 }
David Srbeckyadb66f92019-10-10 12:59:43 +00001261 const uint8_t* code = reserved_code.data() + OatQuickMethodHeader::InstructionAlignedSize();
David Srbeckyafc97bc2018-07-05 08:14:35 +00001262
David Srbecky444e9982019-10-02 17:59:23 +01001263 // Add debug info after we know the code location but before we update entry-point.
David Srbecky41617b12020-03-18 21:19:06 +00001264 std::vector<uint8_t> debug_info;
David Srbeckyadb66f92019-10-10 12:59:43 +00001265 if (compiler_options.GenerateAnyDebugInfo()) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001266 debug::MethodDebugInfo info = {};
Yabin Cuif3f1c8b2021-01-26 13:44:07 -08001267 // Simpleperf relies on art_jni_trampoline to detect jni methods.
David Srbeckyfe1d9522019-03-25 17:19:11 +00001268 info.custom_name = "art_jni_trampoline";
Vladimir Marko2196c652017-11-30 16:16:07 +00001269 info.dex_file = dex_file;
1270 info.class_def_index = class_def_idx;
1271 info.dex_method_index = method_idx;
1272 info.access_flags = access_flags;
1273 info.code_item = code_item;
1274 info.isa = jni_compiled_method.GetInstructionSet();
1275 info.deduped = false;
1276 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1277 info.is_optimized = true;
1278 info.is_code_address_text_relative = false;
David Srbeckyadb66f92019-10-10 12:59:43 +00001279 info.code_address = reinterpret_cast<uintptr_t>(code);
Vladimir Marko2196c652017-11-30 16:16:07 +00001280 info.code_size = jni_compiled_method.GetCode().size();
David Srbeckyadb66f92019-10-10 12:59:43 +00001281 info.frame_size_in_bytes = jni_compiled_method.GetFrameSize();
Vladimir Marko2196c652017-11-30 16:16:07 +00001282 info.code_info = nullptr;
1283 info.cfi = jni_compiled_method.GetCfi();
David Srbecky41617b12020-03-18 21:19:06 +00001284 debug_info = GenerateJitDebugInfo(info);
David Srbeckyadb66f92019-10-10 12:59:43 +00001285 }
David Srbecky444e9982019-10-02 17:59:23 +01001286
David Srbeckyadb66f92019-10-10 12:59:43 +00001287 if (!code_cache->Commit(self,
1288 region,
1289 method,
1290 reserved_code,
1291 jni_compiled_method.GetCode(),
1292 reserved_data,
1293 roots,
1294 ArrayRef<const uint8_t>(stack_map),
David Srbecky41617b12020-03-18 21:19:06 +00001295 debug_info,
1296 /* is_full_debug_info= */ compiler_options.GetGenerateDebugInfo(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001297 compilation_kind,
David Srbeckyadb66f92019-10-10 12:59:43 +00001298 /* has_should_deoptimize_flag= */ false,
1299 cha_single_implementation_list)) {
1300 code_cache->Free(self, region, reserved_code.data(), reserved_data.data());
David Srbecky444e9982019-10-02 17:59:23 +01001301 return false;
Vladimir Marko2196c652017-11-30 16:16:07 +00001302 }
1303
1304 Runtime::Current()->GetJit()->AddMemoryUsage(method, allocator.BytesUsed());
1305 if (jit_logger != nullptr) {
1306 jit_logger->WriteLog(code, jni_compiled_method.GetCode().size(), method);
1307 }
1308 return true;
1309 }
1310
1311 ArenaStack arena_stack(runtime->GetJitArenaPool());
Vladimir Markoca6fff82017-10-03 14:49:14 +01001312 CodeVectorAllocator code_allocator(&allocator);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001313 VariableSizedHandleScope handles(self);
1314
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001315 std::unique_ptr<CodeGenerator> codegen;
1316 {
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001317 Handle<mirror::Class> compiling_class = handles.NewHandle(method->GetDeclaringClass());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001318 DexCompilationUnit dex_compilation_unit(
1319 class_loader,
1320 runtime->GetClassLinker(),
1321 *dex_file,
1322 code_item,
1323 class_def_idx,
1324 method_idx,
1325 access_flags,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001326 /*verified_method=*/ nullptr,
1327 dex_cache,
1328 compiling_class);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001329
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001330 // Go to native so that we don't block GC during compilation.
1331 ScopedThreadSuspension sts(self, kNative);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001332 codegen.reset(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001333 TryCompile(&allocator,
1334 &arena_stack,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001335 &code_allocator,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001336 dex_compilation_unit,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +00001337 method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001338 compilation_kind,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001339 &handles));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001340 if (codegen.get() == nullptr) {
1341 return false;
1342 }
1343 }
1344
David Srbeckye7a91942018-08-01 17:23:53 +01001345 ScopedArenaVector<uint8_t> stack_map = codegen->BuildStackMaps(code_item);
David Srbeckyadb66f92019-10-10 12:59:43 +00001346
1347 ArrayRef<const uint8_t> reserved_code;
1348 ArrayRef<const uint8_t> reserved_data;
1349 if (!code_cache->Reserve(self,
1350 region,
1351 code_allocator.GetMemory().size(),
1352 stack_map.size(),
1353 /*number_of_roots=*/codegen->GetNumberOfJitRoots(),
1354 method,
1355 /*out*/ &reserved_code,
1356 /*out*/ &reserved_data)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001357 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kJitOutOfMemoryForCommit);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001358 return false;
1359 }
David Srbeckyadb66f92019-10-10 12:59:43 +00001360 const uint8_t* code = reserved_code.data() + OatQuickMethodHeader::InstructionAlignedSize();
1361 const uint8_t* roots_data = reserved_data.data();
1362
Vladimir Markoac3ac682018-09-20 11:01:43 +01001363 std::vector<Handle<mirror::Object>> roots;
1364 codegen->EmitJitRoots(code_allocator.GetData(), roots_data, &roots);
1365 // The root Handle<>s filled by the codegen reference entries in the VariableSizedHandleScope.
1366 DCHECK(std::all_of(roots.begin(),
1367 roots.end(),
1368 [&handles](Handle<mirror::Object> root){
1369 return handles.Contains(root.GetReference());
1370 }));
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001371
David Srbecky444e9982019-10-02 17:59:23 +01001372 // Add debug info after we know the code location but before we update entry-point.
David Srbecky41617b12020-03-18 21:19:06 +00001373 std::vector<uint8_t> debug_info;
David Srbeckyadb66f92019-10-10 12:59:43 +00001374 if (compiler_options.GenerateAnyDebugInfo()) {
Vladimir Marko1b404a82017-09-01 13:35:26 +01001375 debug::MethodDebugInfo info = {};
David Srbeckyc684f332018-01-19 17:38:06 +00001376 DCHECK(info.custom_name.empty());
David Srbecky197160d2016-03-07 17:33:57 +00001377 info.dex_file = dex_file;
1378 info.class_def_index = class_def_idx;
1379 info.dex_method_index = method_idx;
1380 info.access_flags = access_flags;
1381 info.code_item = code_item;
1382 info.isa = codegen->GetInstructionSet();
1383 info.deduped = false;
1384 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1385 info.is_optimized = true;
1386 info.is_code_address_text_relative = false;
David Srbeckyadb66f92019-10-10 12:59:43 +00001387 info.code_address = reinterpret_cast<uintptr_t>(code);
Vladimir Markoca1e0382018-04-11 09:58:41 +00001388 info.code_size = code_allocator.GetMemory().size();
David Srbeckyadb66f92019-10-10 12:59:43 +00001389 info.frame_size_in_bytes = codegen->GetFrameSize();
1390 info.code_info = stack_map.size() == 0 ? nullptr : stack_map.data();
David Srbecky197160d2016-03-07 17:33:57 +00001391 info.cfi = ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data());
David Srbecky41617b12020-03-18 21:19:06 +00001392 debug_info = GenerateJitDebugInfo(info);
David Srbeckyadb66f92019-10-10 12:59:43 +00001393 }
David Srbecky444e9982019-10-02 17:59:23 +01001394
David Srbeckyadb66f92019-10-10 12:59:43 +00001395 if (!code_cache->Commit(self,
1396 region,
1397 method,
1398 reserved_code,
1399 code_allocator.GetMemory(),
1400 reserved_data,
1401 roots,
1402 ArrayRef<const uint8_t>(stack_map),
David Srbecky41617b12020-03-18 21:19:06 +00001403 debug_info,
1404 /* is_full_debug_info= */ compiler_options.GetGenerateDebugInfo(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001405 compilation_kind,
David Srbeckyadb66f92019-10-10 12:59:43 +00001406 codegen->GetGraph()->HasShouldDeoptimizeFlag(),
1407 codegen->GetGraph()->GetCHASingleImplementationList())) {
1408 code_cache->Free(self, region, reserved_code.data(), reserved_data.data());
David Srbecky444e9982019-10-02 17:59:23 +01001409 return false;
David Srbecky5cc349f2015-12-18 15:04:48 +00001410 }
1411
Vladimir Markoca6fff82017-10-03 14:49:14 +01001412 Runtime::Current()->GetJit()->AddMemoryUsage(method, allocator.BytesUsed());
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001413 if (jit_logger != nullptr) {
Vladimir Markoca1e0382018-04-11 09:58:41 +00001414 jit_logger->WriteLog(code, code_allocator.GetMemory().size(), method);
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001415 }
Nicolas Geoffraya4f81542016-03-08 16:57:48 +00001416
Vladimir Marko174b2e22017-10-12 13:34:49 +01001417 if (kArenaAllocatorCountAllocations) {
1418 codegen.reset(); // Release codegen's ScopedArenaAllocator for memory accounting.
1419 size_t total_allocated = allocator.BytesAllocated() + arena_stack.PeakBytesAllocated();
1420 if (total_allocated > kArenaAllocatorMemoryReportThreshold) {
1421 MemStats mem_stats(allocator.GetMemStats());
1422 MemStats peak_stats(arena_stack.GetPeakStats());
1423 LOG(INFO) << "Used " << total_allocated << " bytes of arena memory for compiling "
1424 << dex_file->PrettyMethod(method_idx)
1425 << "\n" << Dumpable<MemStats>(mem_stats)
1426 << "\n" << Dumpable<MemStats>(peak_stats);
1427 }
1428 }
1429
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001430 return true;
1431}
1432
David Srbecky41617b12020-03-18 21:19:06 +00001433std::vector<uint8_t> OptimizingCompiler::GenerateJitDebugInfo(const debug::MethodDebugInfo& info) {
Vladimir Marko038924b2019-02-19 15:09:35 +00001434 const CompilerOptions& compiler_options = GetCompilerOptions();
David Srbecky444e9982019-10-02 17:59:23 +01001435 if (compiler_options.GenerateAnyDebugInfo()) {
David Srbecky43ae7792019-01-09 17:34:01 +00001436 // If both flags are passed, generate full debug info.
1437 const bool mini_debug_info = !compiler_options.GetGenerateDebugInfo();
David Srbeckyc684f332018-01-19 17:38:06 +00001438
David Srbecky43ae7792019-01-09 17:34:01 +00001439 // Create entry for the single method that we just compiled.
David Srbecky8fc2f952019-07-31 18:40:09 +01001440 InstructionSet isa = compiler_options.GetInstructionSet();
1441 const InstructionSetFeatures* features = compiler_options.GetInstructionSetFeatures();
David Srbecky41617b12020-03-18 21:19:06 +00001442 return debug::MakeElfFileForJIT(isa, features, mini_debug_info, info);
David Srbecky43ae7792019-01-09 17:34:01 +00001443 }
David Srbecky41617b12020-03-18 21:19:06 +00001444 return std::vector<uint8_t>();
David Srbeckyc684f332018-01-19 17:38:06 +00001445}
1446
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001447} // namespace art