blob: b6ab9fb1b594654c42c862a7b7377ff961922679 [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"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010041#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000042#include "dex/verified_method.h"
Vladimir Marko038924b2019-02-19 15:09:35 +000043#include "driver/compiled_method_storage.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000044#include "driver/compiler_options.h"
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000045#include "driver/dex_compilation_unit.h"
David Brazdil69ba7b72015-06-23 18:27:30 +010046#include "graph_checker.h"
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010047#include "graph_visualizer.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000048#include "inliner.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000049#include "jit/debugger_interface.h"
Nicolas Geoffraya4f81542016-03-08 16:57:48 +000050#include "jit/jit.h"
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +000051#include "jit/jit_code_cache.h"
Nicolas Geoffray01db5f72017-07-19 15:05:49 +010052#include "jit/jit_logger.h"
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +000053#include "jni/quick/jni_compiler.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010054#include "linker/linker_patch.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000055#include "nodes.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000056#include "oat_quick_method_header.h"
Nicolas Geoffray26a25ef2014-09-30 13:54:09 +010057#include "prepare_for_register_allocation.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010058#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070059#include "register_allocator_linear_scan.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070060#include "select_generator.h"
Nicolas Geoffray31596742014-11-24 15:28:45 +000061#include "ssa_builder.h"
Nicolas Geoffray804d0932014-05-02 08:46:00 +010062#include "ssa_liveness_analysis.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000063#include "ssa_phi_elimination.h"
David Srbeckyafc97bc2018-07-05 08:14:35 +000064#include "stack_map_stream.h"
David Srbeckyc6b4dd82015-04-07 20:32:43 +010065#include "utils/assembler.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070066#include "verifier/verifier_compiler_binding.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000067
Vladimir Marko0a516052019-10-14 13:00:44 +000068namespace art {
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000069
Vladimir Marko3a40bf22016-03-22 16:26:33 +000070static constexpr size_t kArenaAllocatorMemoryReportThreshold = 8 * MB;
71
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -070072static constexpr const char* kPassNameSeparator = "$";
73
Nicolas Geoffray787c3072014-03-17 10:20:19 +000074/**
75 * Used by the code generator, to allocate the code in a vector.
76 */
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010077class CodeVectorAllocator final : public CodeAllocator {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000078 public:
Vladimir Markoe764d2e2017-10-05 14:35:55 +010079 explicit CodeVectorAllocator(ArenaAllocator* allocator)
Vladimir Markoca1e0382018-04-11 09:58:41 +000080 : memory_(allocator->Adapter(kArenaAllocCodeBuffer)) {}
Nicolas Geoffray787c3072014-03-17 10:20:19 +000081
Andreas Gampefa6a1b02018-09-07 08:11:55 -070082 uint8_t* Allocate(size_t size) override {
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000083 memory_.resize(size);
Nicolas Geoffray787c3072014-03-17 10:20:19 +000084 return &memory_[0];
85 }
86
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010087 ArrayRef<const uint8_t> GetMemory() const override { return ArrayRef<const uint8_t>(memory_); }
Nicolas Geoffray132d8362016-11-16 09:19:42 +000088 uint8_t* GetData() { return memory_.data(); }
Nicolas Geoffray787c3072014-03-17 10:20:19 +000089
90 private:
Vladimir Markof9f64412015-09-02 14:05:49 +010091 ArenaVector<uint8_t> memory_;
Nicolas Geoffray787c3072014-03-17 10:20:19 +000092
93 DISALLOW_COPY_AND_ASSIGN(CodeVectorAllocator);
94};
95
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010096/**
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010097 * Filter to apply to the visualizer. Methods whose name contain that filter will
David Brazdilee690a32014-12-01 17:04:16 +000098 * be dumped.
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010099 */
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700100static constexpr const char kStringFilter[] = "";
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100101
David Brazdil69ba7b72015-06-23 18:27:30 +0100102class PassScope;
David Brazdil809658e2015-02-05 11:34:02 +0000103
David Brazdil69ba7b72015-06-23 18:27:30 +0100104class PassObserver : public ValueObject {
David Brazdil5e8b1372015-01-23 14:39:08 +0000105 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100106 PassObserver(HGraph* graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100107 CodeGenerator* codegen,
108 std::ostream* visualizer_output,
Vladimir Marko038924b2019-02-19 15:09:35 +0000109 const CompilerOptions& compiler_options,
Andreas Gampea0d81af2016-10-27 12:04:57 -0700110 Mutex& dump_mutex)
David Brazdil69ba7b72015-06-23 18:27:30 +0100111 : graph_(graph),
Aart Bika8360cd2018-05-02 16:07:51 -0700112 last_seen_graph_size_(0),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000113 cached_method_name_(),
Vladimir Marko038924b2019-02-19 15:09:35 +0000114 timing_logger_enabled_(compiler_options.GetDumpPassTimings()),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000115 timing_logger_(timing_logger_enabled_ ? GetMethodName() : "", true, true),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100116 disasm_info_(graph->GetAllocator()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700117 visualizer_oss_(),
118 visualizer_output_(visualizer_output),
Vladimir Marko038924b2019-02-19 15:09:35 +0000119 visualizer_enabled_(!compiler_options.GetDumpCfgFileName().empty()),
Vladimir Markoc9fcfd02021-01-05 16:57:30 +0000120 visualizer_(&visualizer_oss_, graph, codegen),
Artem Serov07718842020-02-24 18:51:42 +0000121 codegen_(codegen),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700122 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 Marko038924b2019-02-19 15:09:35 +0000125 if (!IsVerboseMethod(compiler_options, 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 Geoffray002eac62020-02-04 10:16:51 +0000140 if (visualizer_enabled_) {
141 FlushVisualizer();
142 }
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000143 DCHECK(visualizer_oss_.str().empty());
David Brazdil5e8b1372015-01-23 14:39:08 +0000144 }
145
Nicolas Geoffray002eac62020-02-04 10:16:51 +0000146 void DumpDisassembly() {
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100147 if (visualizer_enabled_) {
148 visualizer_.DumpGraphWithDisassembly();
149 }
150 }
151
David Brazdil69ba7b72015-06-23 18:27:30 +0100152 void SetGraphInBadState() { graph_in_bad_state_ = true; }
153
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000154 const char* GetMethodName() {
155 // PrettyMethod() is expensive, so we delay calling it until we actually have to.
156 if (cached_method_name_.empty()) {
David Sehr709b0702016-10-13 09:12:37 -0700157 cached_method_name_ = graph_->GetDexFile().PrettyMethod(graph_->GetMethodIdx());
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000158 }
159 return cached_method_name_.c_str();
160 }
161
David Brazdil5e8b1372015-01-23 14:39:08 +0000162 private:
Nicolas Geoffray002eac62020-02-04 10:16:51 +0000163 void StartPass(const char* pass_name) {
Wojciech Staszkiewicze7060702016-08-16 17:31:19 -0700164 VLOG(compiler) << "Starting pass: " << pass_name;
David Brazdil809658e2015-02-05 11:34:02 +0000165 // Dump graph first, then start timer.
166 if (visualizer_enabled_) {
Andreas Gampe3db70682018-12-26 15:12:03 -0800167 visualizer_.DumpGraph(pass_name, /* is_after_pass= */ false, graph_in_bad_state_);
David Brazdil809658e2015-02-05 11:34:02 +0000168 }
169 if (timing_logger_enabled_) {
170 timing_logger_.StartTiming(pass_name);
171 }
172 }
173
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000174 void FlushVisualizer() REQUIRES(!visualizer_dump_mutex_) {
175 MutexLock mu(Thread::Current(), visualizer_dump_mutex_);
176 *visualizer_output_ << visualizer_oss_.str();
177 visualizer_output_->flush();
178 visualizer_oss_.str("");
179 visualizer_oss_.clear();
180 }
181
Nicolas Geoffray002eac62020-02-04 10:16:51 +0000182 void EndPass(const char* pass_name, bool pass_change) {
David Brazdil809658e2015-02-05 11:34:02 +0000183 // Pause timer first, then dump graph.
184 if (timing_logger_enabled_) {
185 timing_logger_.EndTiming();
186 }
187 if (visualizer_enabled_) {
Andreas Gampe3db70682018-12-26 15:12:03 -0800188 visualizer_.DumpGraph(pass_name, /* is_after_pass= */ true, graph_in_bad_state_);
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_) {
Artem Serov07718842020-02-24 18:51:42 +0000194 GraphChecker checker(graph_, codegen_);
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()) {
Alex Light3a73ffb2021-01-25 14:11:05 +0000197 LOG(FATAL_WITHOUT_ABORT) << "Error after " << pass_name << "(" << graph_->PrettyMethod()
198 << "): " << *graph_;
199 LOG(FATAL) << "(" << pass_name << "): " << Dumpable<GraphChecker>(checker);
David Brazdil69ba7b72015-06-23 18:27:30 +0100200 }
201 }
202 }
David Brazdil809658e2015-02-05 11:34:02 +0000203 }
204
Vladimir Marko038924b2019-02-19 15:09:35 +0000205 static bool IsVerboseMethod(const CompilerOptions& compiler_options, const char* method_name) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700206 // Test an exact match to --verbose-methods. If verbose-methods is set, this overrides an
207 // empty kStringFilter matching all methods.
Vladimir Marko038924b2019-02-19 15:09:35 +0000208 if (compiler_options.HasVerboseMethods()) {
209 return compiler_options.IsVerboseMethod(method_name);
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700210 }
211
212 // Test the kStringFilter sub-string. constexpr helper variable to silence unreachable-code
213 // warning when the string is empty.
214 constexpr bool kStringFilterEmpty = arraysize(kStringFilter) <= 1;
215 if (kStringFilterEmpty || strstr(method_name, kStringFilter) != nullptr) {
216 return true;
217 }
218
219 return false;
220 }
221
David Brazdil69ba7b72015-06-23 18:27:30 +0100222 HGraph* const graph_;
Aart Bika8360cd2018-05-02 16:07:51 -0700223 size_t last_seen_graph_size_;
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000224
225 std::string cached_method_name_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000226
227 bool timing_logger_enabled_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000228 TimingLogger timing_logger_;
229
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100230 DisassemblyInformation disasm_info_;
231
Andreas Gampea0d81af2016-10-27 12:04:57 -0700232 std::ostringstream visualizer_oss_;
233 std::ostream* visualizer_output_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000234 bool visualizer_enabled_;
235 HGraphVisualizer visualizer_;
Artem Serov07718842020-02-24 18:51:42 +0000236 CodeGenerator* codegen_;
Andreas Gampea0d81af2016-10-27 12:04:57 -0700237 Mutex& visualizer_dump_mutex_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000238
David Brazdil69ba7b72015-06-23 18:27:30 +0100239 // Flag to be set by the compiler if the pass failed and the graph is not
240 // expected to validate.
241 bool graph_in_bad_state_;
David Brazdil809658e2015-02-05 11:34:02 +0000242
David Brazdil69ba7b72015-06-23 18:27:30 +0100243 friend PassScope;
244
245 DISALLOW_COPY_AND_ASSIGN(PassObserver);
David Brazdil5e8b1372015-01-23 14:39:08 +0000246};
247
David Brazdil69ba7b72015-06-23 18:27:30 +0100248class PassScope : public ValueObject {
David Brazdil809658e2015-02-05 11:34:02 +0000249 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100250 PassScope(const char *pass_name, PassObserver* pass_observer)
David Brazdil809658e2015-02-05 11:34:02 +0000251 : pass_name_(pass_name),
Aart Bika8360cd2018-05-02 16:07:51 -0700252 pass_change_(true), // assume change
David Brazdil69ba7b72015-06-23 18:27:30 +0100253 pass_observer_(pass_observer) {
254 pass_observer_->StartPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000255 }
256
Aart Bika8360cd2018-05-02 16:07:51 -0700257 void SetPassNotChanged() {
258 pass_change_ = false;
259 }
260
David Brazdil69ba7b72015-06-23 18:27:30 +0100261 ~PassScope() {
Aart Bika8360cd2018-05-02 16:07:51 -0700262 pass_observer_->EndPass(pass_name_, pass_change_);
David Brazdil809658e2015-02-05 11:34:02 +0000263 }
264
265 private:
266 const char* const pass_name_;
Aart Bika8360cd2018-05-02 16:07:51 -0700267 bool pass_change_;
David Brazdil69ba7b72015-06-23 18:27:30 +0100268 PassObserver* const pass_observer_;
David Brazdil809658e2015-02-05 11:34:02 +0000269};
270
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100271class OptimizingCompiler final : public Compiler {
Andreas Gampe53c913b2014-08-12 23:19:23 -0700272 public:
Vladimir Marko038924b2019-02-19 15:09:35 +0000273 explicit OptimizingCompiler(const CompilerOptions& compiler_options,
274 CompiledMethodStorage* storage);
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100275 ~OptimizingCompiler() override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700276
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100277 bool CanCompileMethod(uint32_t method_idx, const DexFile& dex_file) const override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700278
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800279 CompiledMethod* Compile(const dex::CodeItem* code_item,
Andreas Gampe53c913b2014-08-12 23:19:23 -0700280 uint32_t access_flags,
281 InvokeType invoke_type,
282 uint16_t class_def_idx,
283 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000284 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700285 const DexFile& dex_file,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100286 Handle<mirror::DexCache> dex_cache) const override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700287
Andreas Gampe53c913b2014-08-12 23:19:23 -0700288 CompiledMethod* JniCompile(uint32_t access_flags,
289 uint32_t method_idx,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000290 const DexFile& dex_file,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100291 Handle<mirror::DexCache> dex_cache) const override;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700292
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100293 uintptr_t GetEntryPointOf(ArtMethod* method) const override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700294 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000295 return reinterpret_cast<uintptr_t>(method->GetEntryPointFromQuickCompiledCodePtrSize(
Vladimir Marko038924b2019-02-19 15:09:35 +0000296 InstructionSetPointerSize(GetCompilerOptions().GetInstructionSet())));
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000297 }
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,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100301 jit::JitMemoryRegion* region,
Nicolas Geoffray01db5f72017-07-19 15:05:49 +0100302 ArtMethod* method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100303 CompilationKind compilation_kind,
Nicolas Geoffray01db5f72017-07-19 15:05:49 +0100304 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,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800313 const OptimizationDef definitions[],
314 size_t length) const {
315 // Convert definitions to optimization passes.
316 ArenaVector<HOptimization*> optimizations = ConstructOptimizations(
317 definitions,
318 length,
319 graph->GetAllocator(),
320 graph,
321 compilation_stats_.get(),
322 codegen,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100323 dex_compilation_unit);
Aart Bik2ca10eb2017-11-15 15:17:53 -0800324 DCHECK_EQ(length, optimizations.size());
Aart Bik2e148682018-04-18 16:11:12 -0700325 // Run the optimization passes one by one. Any "depends_on" pass refers back to
326 // the most recent occurrence of that pass, skipped or executed.
327 std::bitset<static_cast<size_t>(OptimizationPass::kLast) + 1u> pass_changes;
328 pass_changes[static_cast<size_t>(OptimizationPass::kNone)] = true;
Aart Bik24773202018-04-26 10:28:51 -0700329 bool change = false;
Aart Bik2ca10eb2017-11-15 15:17:53 -0800330 for (size_t i = 0; i < length; ++i) {
Aart Bik2e148682018-04-18 16:11:12 -0700331 if (pass_changes[static_cast<size_t>(definitions[i].depends_on)]) {
332 // Execute the pass and record whether it changed anything.
333 PassScope scope(optimizations[i]->GetPassName(), pass_observer);
334 bool pass_change = optimizations[i]->Run();
335 pass_changes[static_cast<size_t>(definitions[i].pass)] = pass_change;
Aart Bika8360cd2018-05-02 16:07:51 -0700336 if (pass_change) {
337 change = true;
338 } else {
339 scope.SetPassNotChanged();
340 }
Aart Bik2e148682018-04-18 16:11:12 -0700341 } else {
342 // Skip the pass and record that nothing changed.
343 pass_changes[static_cast<size_t>(definitions[i].pass)] = false;
344 }
Aart Bik2ca10eb2017-11-15 15:17:53 -0800345 }
Aart Bik24773202018-04-26 10:28:51 -0700346 return change;
Aart Bik2ca10eb2017-11-15 15:17:53 -0800347 }
348
Aart Bik24773202018-04-26 10:28:51 -0700349 template <size_t length> bool RunOptimizations(
Aart Bik2ca10eb2017-11-15 15:17:53 -0800350 HGraph* graph,
351 CodeGenerator* codegen,
352 const DexCompilationUnit& dex_compilation_unit,
353 PassObserver* pass_observer,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800354 const OptimizationDef (&definitions)[length]) const {
Aart Bik24773202018-04-26 10:28:51 -0700355 return RunOptimizations(
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100356 graph, codegen, dex_compilation_unit, pass_observer, definitions, length);
Aart Bik2ca10eb2017-11-15 15:17:53 -0800357 }
358
359 void RunOptimizations(HGraph* graph,
360 CodeGenerator* codegen,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700361 const DexCompilationUnit& dex_compilation_unit,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100362 PassObserver* pass_observer) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700363
Andreas Gampe53c913b2014-08-12 23:19:23 -0700364 private:
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000365 // Create a 'CompiledMethod' for an optimized graph.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100366 CompiledMethod* Emit(ArenaAllocator* allocator,
David Brazdil58282f42016-01-14 12:45:10 +0000367 CodeVectorAllocator* code_allocator,
368 CodeGenerator* codegen,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800369 const dex::CodeItem* item) const;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000370
371 // Try compiling a method and return the code generator used for
372 // compiling it.
373 // This method:
374 // 1) Builds the graph. Returns null if it failed to build it.
David Brazdil58282f42016-01-14 12:45:10 +0000375 // 2) Transforms the graph to SSA. Returns null if it failed.
376 // 3) Runs optimizations on the graph, including register allocator.
377 // 4) Generates code with the `code_allocator` provided.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100378 CodeGenerator* TryCompile(ArenaAllocator* allocator,
379 ArenaStack* arena_stack,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000380 CodeVectorAllocator* code_allocator,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000381 const DexCompilationUnit& dex_compilation_unit,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000382 ArtMethod* method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100383 CompilationKind compilation_kind,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000384 VariableSizedHandleScope* handles) const;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000385
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000386 CodeGenerator* TryCompileIntrinsic(ArenaAllocator* allocator,
387 ArenaStack* arena_stack,
388 CodeVectorAllocator* code_allocator,
389 const DexCompilationUnit& dex_compilation_unit,
390 ArtMethod* method,
391 VariableSizedHandleScope* handles) const;
392
Aart Bik24773202018-04-26 10:28:51 -0700393 bool RunArchOptimizations(HGraph* graph,
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700394 CodeGenerator* codegen,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800395 const DexCompilationUnit& dex_compilation_unit,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100396 PassObserver* pass_observer) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700397
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100398 bool RunBaselineOptimizations(HGraph* graph,
399 CodeGenerator* codegen,
400 const DexCompilationUnit& dex_compilation_unit,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100401 PassObserver* pass_observer) const;
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100402
David Srbecky41617b12020-03-18 21:19:06 +0000403 std::vector<uint8_t> GenerateJitDebugInfo(const debug::MethodDebugInfo& method_debug_info);
David Srbeckyc684f332018-01-19 17:38:06 +0000404
Fabio Rinaldi52d53542020-02-10 17:28:06 +0000405 // This must be called before any other function that dumps data to the cfg
406 void DumpInstructionSetFeaturesToCfg() const;
407
Calin Juravle2be39e02015-04-21 13:56:34 +0100408 std::unique_ptr<OptimizingCompilerStats> compilation_stats_;
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100409
Andreas Gampe53c913b2014-08-12 23:19:23 -0700410 std::unique_ptr<std::ostream> visualizer_output_;
411
Andreas Gampea0d81af2016-10-27 12:04:57 -0700412 mutable Mutex dump_mutex_; // To synchronize visualizer writing.
413
Andreas Gampe53c913b2014-08-12 23:19:23 -0700414 DISALLOW_COPY_AND_ASSIGN(OptimizingCompiler);
415};
416
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100417static const int kMaximumCompilationTimeBeforeWarning = 100; /* ms */
418
Vladimir Marko038924b2019-02-19 15:09:35 +0000419OptimizingCompiler::OptimizingCompiler(const CompilerOptions& compiler_options,
420 CompiledMethodStorage* storage)
421 : Compiler(compiler_options, storage, kMaximumCompilationTimeBeforeWarning),
422 dump_mutex_("Visualizer dump lock") {
423 // Enable C1visualizer output.
424 const std::string& cfg_file_name = compiler_options.GetDumpCfgFileName();
David Brazdil866c0312015-01-13 21:21:31 +0000425 if (!cfg_file_name.empty()) {
Calin Juravle87000a92015-08-24 15:34:44 +0100426 std::ios_base::openmode cfg_file_mode =
Vladimir Marko038924b2019-02-19 15:09:35 +0000427 compiler_options.GetDumpCfgAppend() ? std::ofstream::app : std::ofstream::out;
Calin Juravle87000a92015-08-24 15:34:44 +0100428 visualizer_output_.reset(new std::ofstream(cfg_file_name, cfg_file_mode));
Fabio Rinaldi52d53542020-02-10 17:28:06 +0000429 DumpInstructionSetFeaturesToCfg();
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100430 }
Vladimir Marko038924b2019-02-19 15:09:35 +0000431 if (compiler_options.GetDumpStats()) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100432 compilation_stats_.reset(new OptimizingCompilerStats());
433 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100434}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000435
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100436OptimizingCompiler::~OptimizingCompiler() {
Calin Juravle2be39e02015-04-21 13:56:34 +0100437 if (compilation_stats_.get() != nullptr) {
438 compilation_stats_->Log();
439 }
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100440}
441
Fabio Rinaldi52d53542020-02-10 17:28:06 +0000442void OptimizingCompiler::DumpInstructionSetFeaturesToCfg() const {
443 const CompilerOptions& compiler_options = GetCompilerOptions();
444 const InstructionSetFeatures* features = compiler_options.GetInstructionSetFeatures();
Evgeny Astigeevich2446feb2020-07-27 12:25:49 +0100445 std::string isa_string =
446 std::string("isa:") + GetInstructionSetString(features->GetInstructionSet());
Fabio Rinaldi52d53542020-02-10 17:28:06 +0000447 std::string features_string = "isa_features:" + features->GetFeatureString();
448 // It is assumed that visualizer_output_ is empty when calling this function, hence the fake
449 // compilation block containing the ISA features will be printed at the beginning of the .cfg
450 // file.
Evgeny Astigeevich2446feb2020-07-27 12:25:49 +0100451 *visualizer_output_
452 << HGraphVisualizer::InsertMetaDataAsCompilationBlock(isa_string + ' ' + features_string);
Fabio Rinaldi52d53542020-02-10 17:28:06 +0000453}
454
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000455bool OptimizingCompiler::CanCompileMethod(uint32_t method_idx ATTRIBUTE_UNUSED,
Vladimir Markodf739842016-03-23 16:59:07 +0000456 const DexFile& dex_file ATTRIBUTE_UNUSED) const {
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000457 return true;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700458}
459
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000460static bool IsInstructionSetSupported(InstructionSet instruction_set) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000461 return instruction_set == InstructionSet::kArm
462 || instruction_set == InstructionSet::kArm64
463 || instruction_set == InstructionSet::kThumb2
Vladimir Marko33bff252017-11-01 14:35:42 +0000464 || instruction_set == InstructionSet::kX86
465 || instruction_set == InstructionSet::kX86_64;
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000466}
467
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100468bool OptimizingCompiler::RunBaselineOptimizations(HGraph* graph,
469 CodeGenerator* codegen,
470 const DexCompilationUnit& dex_compilation_unit,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100471 PassObserver* pass_observer) const {
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100472 switch (codegen->GetCompilerOptions().GetInstructionSet()) {
Vladimir Markod3e9c622020-08-05 12:20:28 +0100473#if defined(ART_ENABLE_CODEGEN_arm)
474 case InstructionSet::kThumb2:
475 case InstructionSet::kArm: {
476 OptimizationDef arm_optimizations[] = {
477 OptDef(OptimizationPass::kCriticalNativeAbiFixupArm),
478 };
479 return RunOptimizations(graph,
480 codegen,
481 dex_compilation_unit,
482 pass_observer,
483 arm_optimizations);
484 }
485#endif
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100486#ifdef ART_ENABLE_CODEGEN_x86
487 case InstructionSet::kX86: {
488 OptimizationDef x86_optimizations[] = {
489 OptDef(OptimizationPass::kPcRelativeFixupsX86),
490 };
491 return RunOptimizations(graph,
492 codegen,
493 dex_compilation_unit,
494 pass_observer,
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100495 x86_optimizations);
496 }
497#endif
498 default:
499 UNUSED(graph);
500 UNUSED(codegen);
501 UNUSED(dex_compilation_unit);
502 UNUSED(pass_observer);
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100503 return false;
504 }
505}
506
Aart Bik24773202018-04-26 10:28:51 -0700507bool OptimizingCompiler::RunArchOptimizations(HGraph* graph,
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700508 CodeGenerator* codegen,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800509 const DexCompilationUnit& dex_compilation_unit,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100510 PassObserver* pass_observer) const {
Vladimir Markoa0431112018-06-25 09:32:54 +0100511 switch (codegen->GetCompilerOptions().GetInstructionSet()) {
Artem Serov2bbc9532016-10-21 11:51:50 +0100512#if defined(ART_ENABLE_CODEGEN_arm)
Vladimir Marko33bff252017-11-01 14:35:42 +0000513 case InstructionSet::kThumb2:
514 case InstructionSet::kArm: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800515 OptimizationDef arm_optimizations[] = {
516 OptDef(OptimizationPass::kInstructionSimplifierArm),
517 OptDef(OptimizationPass::kSideEffectsAnalysis),
518 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
Vladimir Markod3e9c622020-08-05 12:20:28 +0100519 OptDef(OptimizationPass::kCriticalNativeAbiFixupArm),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800520 OptDef(OptimizationPass::kScheduling)
Vladimir Markob4536b72015-11-24 13:45:23 +0000521 };
Aart Bik24773202018-04-26 10:28:51 -0700522 return RunOptimizations(graph,
523 codegen,
524 dex_compilation_unit,
525 pass_observer,
Aart Bik24773202018-04-26 10:28:51 -0700526 arm_optimizations);
Vladimir Markob4536b72015-11-24 13:45:23 +0000527 }
528#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100529#ifdef ART_ENABLE_CODEGEN_arm64
Vladimir Marko33bff252017-11-01 14:35:42 +0000530 case InstructionSet::kArm64: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800531 OptimizationDef arm64_optimizations[] = {
532 OptDef(OptimizationPass::kInstructionSimplifierArm64),
533 OptDef(OptimizationPass::kSideEffectsAnalysis),
534 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
535 OptDef(OptimizationPass::kScheduling)
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100536 };
Aart Bik24773202018-04-26 10:28:51 -0700537 return RunOptimizations(graph,
538 codegen,
539 dex_compilation_unit,
540 pass_observer,
Aart Bik24773202018-04-26 10:28:51 -0700541 arm64_optimizations);
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100542 }
543#endif
Mark Mendell0616ae02015-04-17 12:49:27 -0400544#ifdef ART_ENABLE_CODEGEN_x86
Vladimir Marko33bff252017-11-01 14:35:42 +0000545 case InstructionSet::kX86: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800546 OptimizationDef x86_optimizations[] = {
Shalini Salomi Bodapatidd121f62018-10-26 15:03:53 +0530547 OptDef(OptimizationPass::kInstructionSimplifierX86),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800548 OptDef(OptimizationPass::kSideEffectsAnalysis),
549 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
550 OptDef(OptimizationPass::kPcRelativeFixupsX86),
Hans Boehmf5f56c72018-07-13 00:05:27 +0000551 OptDef(OptimizationPass::kX86MemoryOperandGeneration)
Mark Mendell0616ae02015-04-17 12:49:27 -0400552 };
Aart Bik24773202018-04-26 10:28:51 -0700553 return RunOptimizations(graph,
554 codegen,
555 dex_compilation_unit,
556 pass_observer,
Aart Bik24773202018-04-26 10:28:51 -0700557 x86_optimizations);
Mark Mendell0616ae02015-04-17 12:49:27 -0400558 }
559#endif
Mark Mendellee8d9712016-07-12 11:13:15 -0400560#ifdef ART_ENABLE_CODEGEN_x86_64
Vladimir Marko33bff252017-11-01 14:35:42 +0000561 case InstructionSet::kX86_64: {
Aart Bik2ca10eb2017-11-15 15:17:53 -0800562 OptimizationDef x86_64_optimizations[] = {
Shalini Salomi Bodapatidd121f62018-10-26 15:03:53 +0530563 OptDef(OptimizationPass::kInstructionSimplifierX86_64),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800564 OptDef(OptimizationPass::kSideEffectsAnalysis),
565 OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
Hans Boehmf5f56c72018-07-13 00:05:27 +0000566 OptDef(OptimizationPass::kX86MemoryOperandGeneration)
Mark Mendellee8d9712016-07-12 11:13:15 -0400567 };
Aart Bik24773202018-04-26 10:28:51 -0700568 return RunOptimizations(graph,
569 codegen,
570 dex_compilation_unit,
571 pass_observer,
Aart Bik24773202018-04-26 10:28:51 -0700572 x86_64_optimizations);
Mark Mendellee8d9712016-07-12 11:13:15 -0400573 }
574#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100575 default:
Aart Bik24773202018-04-26 10:28:51 -0700576 return false;
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100577 }
578}
579
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000580NO_INLINE // Avoid increasing caller's frame size by large stack-allocated objects.
581static void AllocateRegisters(HGraph* graph,
582 CodeGenerator* codegen,
Matthew Gharrity2cd05b72016-08-03 16:57:37 -0700583 PassObserver* pass_observer,
Igor Murashkin6ef45672017-08-08 13:59:55 -0700584 RegisterAllocator::Strategy strategy,
585 OptimizingCompilerStats* stats) {
Mingyao Yang700347e2016-03-02 14:59:32 -0800586 {
587 PassScope scope(PrepareForRegisterAllocation::kPrepareForRegisterAllocationPassName,
588 pass_observer);
Nicolas Geoffray61ba8d22018-08-07 09:55:57 +0100589 PrepareForRegisterAllocation(graph, codegen->GetCompilerOptions(), stats).Run();
Mingyao Yang700347e2016-03-02 14:59:32 -0800590 }
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100591 // Use local allocator shared by SSA liveness analysis and register allocator.
592 // (Register allocator creates new objects in the liveness data.)
593 ScopedArenaAllocator local_allocator(graph->GetArenaStack());
594 SsaLivenessAnalysis liveness(graph, codegen, &local_allocator);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000595 {
596 PassScope scope(SsaLivenessAnalysis::kLivenessPassName, pass_observer);
597 liveness.Analyze();
598 }
599 {
600 PassScope scope(RegisterAllocator::kRegisterAllocatorPassName, pass_observer);
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100601 std::unique_ptr<RegisterAllocator> register_allocator =
602 RegisterAllocator::Create(&local_allocator, codegen, liveness, strategy);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100603 register_allocator->AllocateRegisters();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000604 }
605}
606
Aart Bik2ca10eb2017-11-15 15:17:53 -0800607// Strip pass name suffix to get optimization name.
608static std::string ConvertPassNameToOptimizationName(const std::string& pass_name) {
609 size_t pos = pass_name.find(kPassNameSeparator);
610 return pos == std::string::npos ? pass_name : pass_name.substr(0, pos);
611}
612
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700613void OptimizingCompiler::RunOptimizations(HGraph* graph,
614 CodeGenerator* codegen,
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700615 const DexCompilationUnit& dex_compilation_unit,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100616 PassObserver* pass_observer) const {
Vladimir Marko038924b2019-02-19 15:09:35 +0000617 const std::vector<std::string>* pass_names = GetCompilerOptions().GetPassesToRun();
Aart Bik2ca10eb2017-11-15 15:17:53 -0800618 if (pass_names != nullptr) {
619 // If passes were defined on command-line, build the optimization
620 // passes and run these instead of the built-in optimizations.
Aart Bik2e148682018-04-18 16:11:12 -0700621 // TODO: a way to define depends_on via command-line?
Aart Bik2ca10eb2017-11-15 15:17:53 -0800622 const size_t length = pass_names->size();
623 std::vector<OptimizationDef> optimizations;
624 for (const std::string& pass_name : *pass_names) {
625 std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
Greg Kaisere7e195d2019-03-26 08:13:00 -0700626 optimizations.push_back(OptDef(OptimizationPassByName(opt_name), pass_name.c_str()));
Aart Bik2ca10eb2017-11-15 15:17:53 -0800627 }
628 RunOptimizations(graph,
629 codegen,
630 dex_compilation_unit,
631 pass_observer,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800632 optimizations.data(),
633 length);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700634 return;
635 }
636
Aart Bik24773202018-04-26 10:28:51 -0700637 OptimizationDef optimizations[] = {
Aart Bik2e148682018-04-18 16:11:12 -0700638 // Initial optimizations.
Aart Bik2ca10eb2017-11-15 15:17:53 -0800639 OptDef(OptimizationPass::kConstantFolding),
640 OptDef(OptimizationPass::kInstructionSimplifier),
Aart Bik2e148682018-04-18 16:11:12 -0700641 OptDef(OptimizationPass::kDeadCodeElimination,
642 "dead_code_elimination$initial"),
643 // Inlining.
Aart Bik24773202018-04-26 10:28:51 -0700644 OptDef(OptimizationPass::kInliner),
Aart Bik2e148682018-04-18 16:11:12 -0700645 // Simplification (only if inlining occurred).
646 OptDef(OptimizationPass::kConstantFolding,
647 "constant_folding$after_inlining",
648 OptimizationPass::kInliner),
649 OptDef(OptimizationPass::kInstructionSimplifier,
650 "instruction_simplifier$after_inlining",
651 OptimizationPass::kInliner),
652 OptDef(OptimizationPass::kDeadCodeElimination,
653 "dead_code_elimination$after_inlining",
654 OptimizationPass::kInliner),
655 // GVN.
656 OptDef(OptimizationPass::kSideEffectsAnalysis,
657 "side_effects$before_gvn"),
Aart Bik6d057002018-04-09 15:39:58 -0700658 OptDef(OptimizationPass::kGlobalValueNumbering),
Aart Bik2e148682018-04-18 16:11:12 -0700659 // Simplification (TODO: only if GVN occurred).
Aart Bik2ca10eb2017-11-15 15:17:53 -0800660 OptDef(OptimizationPass::kSelectGenerator),
Aart Bik2e148682018-04-18 16:11:12 -0700661 OptDef(OptimizationPass::kConstantFolding,
662 "constant_folding$after_gvn"),
663 OptDef(OptimizationPass::kInstructionSimplifier,
664 "instruction_simplifier$after_gvn"),
665 OptDef(OptimizationPass::kDeadCodeElimination,
666 "dead_code_elimination$after_gvn"),
667 // High-level optimizations.
668 OptDef(OptimizationPass::kSideEffectsAnalysis,
669 "side_effects$before_licm"),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800670 OptDef(OptimizationPass::kInvariantCodeMotion),
671 OptDef(OptimizationPass::kInductionVarAnalysis),
672 OptDef(OptimizationPass::kBoundsCheckElimination),
673 OptDef(OptimizationPass::kLoopOptimization),
Aart Bik2e148682018-04-18 16:11:12 -0700674 // Simplification.
675 OptDef(OptimizationPass::kConstantFolding,
676 "constant_folding$after_bce"),
Evgeny Astigeevich6587d912020-06-12 10:51:43 +0100677 OptDef(OptimizationPass::kAggressiveInstructionSimplifier,
Aart Bik2e148682018-04-18 16:11:12 -0700678 "instruction_simplifier$after_bce"),
679 // Other high-level optimizations.
Aart Bik2ca10eb2017-11-15 15:17:53 -0800680 OptDef(OptimizationPass::kLoadStoreElimination),
681 OptDef(OptimizationPass::kCHAGuardOptimization),
Aart Bik2e148682018-04-18 16:11:12 -0700682 OptDef(OptimizationPass::kDeadCodeElimination,
683 "dead_code_elimination$final"),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800684 OptDef(OptimizationPass::kCodeSinking),
David Brazdil8993caf2015-12-07 10:04:40 +0000685 // The codegen has a few assumptions that only the instruction simplifier
686 // can satisfy. For example, the code generator does not expect to see a
687 // HTypeConversion from a type to the same type.
Evgeny Astigeevich6587d912020-06-12 10:51:43 +0100688 OptDef(OptimizationPass::kAggressiveInstructionSimplifier,
Aart Bik2e148682018-04-18 16:11:12 -0700689 "instruction_simplifier$before_codegen"),
Aart Bik2ca10eb2017-11-15 15:17:53 -0800690 // Eliminate constructor fences after code sinking to avoid
691 // complicated sinking logic to split a fence with many inputs.
692 OptDef(OptimizationPass::kConstructorFenceRedundancyElimination)
David Brazdil8993caf2015-12-07 10:04:40 +0000693 };
Aart Bik2ca10eb2017-11-15 15:17:53 -0800694 RunOptimizations(graph,
695 codegen,
696 dex_compilation_unit,
697 pass_observer,
Aart Bik24773202018-04-26 10:28:51 -0700698 optimizations);
David Brazdilbbd733e2015-08-18 17:48:17 +0100699
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100700 RunArchOptimizations(graph, codegen, dex_compilation_unit, pass_observer);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000701}
702
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100703static ArenaVector<linker::LinkerPatch> EmitAndSortLinkerPatches(CodeGenerator* codegen) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100704 ArenaVector<linker::LinkerPatch> linker_patches(codegen->GetGraph()->GetAllocator()->Adapter());
Vladimir Marko58155012015-08-19 12:49:41 +0000705 codegen->EmitLinkerPatches(&linker_patches);
706
707 // Sort patches by literal offset. Required for .oat_patches encoding.
708 std::sort(linker_patches.begin(), linker_patches.end(),
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100709 [](const linker::LinkerPatch& lhs, const linker::LinkerPatch& rhs) {
Vladimir Marko58155012015-08-19 12:49:41 +0000710 return lhs.LiteralOffset() < rhs.LiteralOffset();
711 });
712
713 return linker_patches;
714}
715
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100716CompiledMethod* OptimizingCompiler::Emit(ArenaAllocator* allocator,
David Brazdil58282f42016-01-14 12:45:10 +0000717 CodeVectorAllocator* code_allocator,
718 CodeGenerator* codegen,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800719 const dex::CodeItem* code_item_for_osr_check) const {
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100720 ArenaVector<linker::LinkerPatch> linker_patches = EmitAndSortLinkerPatches(codegen);
David Srbeckye7a91942018-08-01 17:23:53 +0100721 ScopedArenaVector<uint8_t> stack_map = codegen->BuildStackMaps(code_item_for_osr_check);
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000722
Vladimir Marko038924b2019-02-19 15:09:35 +0000723 CompiledMethodStorage* storage = GetCompiledMethodStorage();
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100724 CompiledMethod* compiled_method = CompiledMethod::SwapAllocCompiledMethod(
Vladimir Marko038924b2019-02-19 15:09:35 +0000725 storage,
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000726 codegen->GetInstructionSet(),
Vladimir Markoca1e0382018-04-11 09:58:41 +0000727 code_allocator->GetMemory(),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100728 ArrayRef<const uint8_t>(stack_map),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100729 ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data()),
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100730 ArrayRef<const linker::LinkerPatch>(linker_patches));
Mathieu Chartiered150002015-08-28 11:16:54 -0700731
Vladimir Markoca1e0382018-04-11 09:58:41 +0000732 for (const linker::LinkerPatch& patch : linker_patches) {
733 if (codegen->NeedsThunkCode(patch) && storage->GetThunkCode(patch).empty()) {
734 ArenaVector<uint8_t> code(allocator->Adapter());
735 std::string debug_name;
736 codegen->EmitThunkCode(patch, &code, &debug_name);
737 storage->SetThunkCode(patch, ArrayRef<const uint8_t>(code), debug_name);
738 }
739 }
740
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100741 return compiled_method;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000742}
743
Vladimir Markoca6fff82017-10-03 14:49:14 +0100744CodeGenerator* OptimizingCompiler::TryCompile(ArenaAllocator* allocator,
745 ArenaStack* arena_stack,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000746 CodeVectorAllocator* code_allocator,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000747 const DexCompilationUnit& dex_compilation_unit,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000748 ArtMethod* method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100749 CompilationKind compilation_kind,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000750 VariableSizedHandleScope* handles) const {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000751 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kAttemptBytecodeCompilation);
Vladimir Marko038924b2019-02-19 15:09:35 +0000752 const CompilerOptions& compiler_options = GetCompilerOptions();
Vladimir Markoa0431112018-06-25 09:32:54 +0100753 InstructionSet instruction_set = compiler_options.GetInstructionSet();
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000754 const DexFile& dex_file = *dex_compilation_unit.GetDexFile();
755 uint32_t method_idx = dex_compilation_unit.GetDexMethodIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800756 const dex::CodeItem* code_item = dex_compilation_unit.GetCodeItem();
Calin Juravlecff8cc72015-10-09 12:03:24 +0100757
Roland Levillain3b359c72015-11-17 19:35:12 +0000758 // Always use the Thumb-2 assembler: some runtime functionality
759 // (like implicit stack overflow checks) assume Thumb-2.
Vladimir Marko33bff252017-11-01 14:35:42 +0000760 DCHECK_NE(instruction_set, InstructionSet::kArm);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100761
762 // Do not attempt to compile on architectures we do not support.
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000763 if (!IsInstructionSetSupported(instruction_set)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700764 MaybeRecordStat(compilation_stats_.get(),
765 MethodCompilationStat::kNotCompiledUnsupportedIsa);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100766 return nullptr;
767 }
768
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000769 if (Compiler::IsPathologicalCase(*code_item, method_idx, dex_file)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000770 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledPathological);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000771 return nullptr;
772 }
773
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000774 // Implementation of the space filter: do not compile a code item whose size in
Nicolas Geoffray432bf3d2015-07-17 11:11:09 +0100775 // code units is bigger than 128.
776 static constexpr size_t kSpaceFilterOptimizingThreshold = 128;
Andreas Gampe29d38e72016-03-23 15:31:51 +0000777 if ((compiler_options.GetCompilerFilter() == CompilerFilter::kSpace)
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800778 && (CodeItemInstructionAccessor(dex_file, code_item).InsnsSizeInCodeUnits() >
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800779 kSpaceFilterOptimizingThreshold)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000780 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledSpaceFilter);
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000781 return nullptr;
782 }
783
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800784 CodeItemDebugInfoAccessor code_item_accessor(dex_file, code_item, method_idx);
Hans Boehm206348c2018-12-05 11:11:33 -0800785
786 bool dead_reference_safe;
Hans Boehm206348c2018-12-05 11:11:33 -0800787 // For AOT compilation, we may not get a method, for example if its class is erroneous,
788 // possibly due to an unavailable superclass. JIT should always have a method.
789 DCHECK(Runtime::Current()->IsAotCompiler() || method != nullptr);
790 if (method != nullptr) {
791 const dex::ClassDef* containing_class;
792 {
793 ScopedObjectAccess soa(Thread::Current());
794 containing_class = &method->GetClassDef();
Hans Boehm206348c2018-12-05 11:11:33 -0800795 }
796 // MethodContainsRSensitiveAccess is currently slow, but HasDeadReferenceSafeAnnotation()
797 // is currently rarely true.
798 dead_reference_safe =
799 annotations::HasDeadReferenceSafeAnnotation(dex_file, *containing_class)
800 && !annotations::MethodContainsRSensitiveAccess(dex_file, *containing_class, method_idx);
801 } else {
802 // If we could not resolve the class, conservatively assume it's dead-reference unsafe.
803 dead_reference_safe = false;
804 }
805
Vladimir Markoca6fff82017-10-03 14:49:14 +0100806 HGraph* graph = new (allocator) HGraph(
807 allocator,
808 arena_stack,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100809 handles,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000810 dex_file,
811 method_idx,
Vladimir Markoa0431112018-06-25 09:32:54 +0100812 compiler_options.GetInstructionSet(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000813 kInvalidInvokeType,
Hans Boehm206348c2018-12-05 11:11:33 -0800814 dead_reference_safe,
Vladimir Marko038924b2019-02-19 15:09:35 +0000815 compiler_options.GetDebuggable(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100816 compilation_kind);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000817
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000818 if (method != nullptr) {
819 graph->SetArtMethod(method);
David Brazdilbadd8262016-02-02 16:28:56 +0000820 }
821
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000822 std::unique_ptr<CodeGenerator> codegen(
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000823 CodeGenerator::Create(graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100824 compiler_options,
Calin Juravle2ae48182016-03-16 14:05:09 +0000825 compilation_stats_.get()));
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000826 if (codegen.get() == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000827 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledNoCodegen);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000828 return nullptr;
829 }
Vladimir Marko038924b2019-02-19 15:09:35 +0000830 codegen->GetAssembler()->cfi().SetEnabled(compiler_options.GenerateAnyDebugInfo());
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000831
David Brazdil69ba7b72015-06-23 18:27:30 +0100832 PassObserver pass_observer(graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100833 codegen.get(),
834 visualizer_output_.get(),
Vladimir Marko038924b2019-02-19 15:09:35 +0000835 compiler_options,
Andreas Gampea0d81af2016-10-27 12:04:57 -0700836 dump_mutex_);
David Brazdil5e8b1372015-01-23 14:39:08 +0000837
David Brazdil809658e2015-02-05 11:34:02 +0000838 {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000839 VLOG(compiler) << "Building " << pass_observer.GetMethodName();
840 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
841 HGraphBuilder builder(graph,
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800842 code_item_accessor,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000843 &dex_compilation_unit,
844 &dex_compilation_unit,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000845 codegen.get(),
Nicolas Geoffray4924ea92021-03-23 08:25:31 +0000846 compilation_stats_.get());
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000847 GraphAnalysisResult result = builder.BuildGraph();
848 if (result != kAnalysisSuccess) {
849 switch (result) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700850 case kAnalysisSkipped: {
851 MaybeRecordStat(compilation_stats_.get(),
852 MethodCompilationStat::kNotCompiledSkipped);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000853 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100854 }
Igor Murashkin1e065a52017-08-09 13:20:34 -0700855 case kAnalysisInvalidBytecode: {
856 MaybeRecordStat(compilation_stats_.get(),
857 MethodCompilationStat::kNotCompiledInvalidBytecode);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000858 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100859 }
Igor Murashkin1e065a52017-08-09 13:20:34 -0700860 case kAnalysisFailThrowCatchLoop: {
861 MaybeRecordStat(compilation_stats_.get(),
862 MethodCompilationStat::kNotCompiledThrowCatchLoop);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000863 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100864 }
Igor Murashkin1e065a52017-08-09 13:20:34 -0700865 case kAnalysisFailAmbiguousArrayOp: {
866 MaybeRecordStat(compilation_stats_.get(),
867 MethodCompilationStat::kNotCompiledAmbiguousArrayOp);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000868 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100869 }
Nicolas Geoffray0846a8f2018-09-12 15:21:07 +0100870 case kAnalysisFailIrreducibleLoopAndStringInit: {
871 MaybeRecordStat(compilation_stats_.get(),
872 MethodCompilationStat::kNotCompiledIrreducibleLoopAndStringInit);
873 break;
874 }
Nicolas Geoffray7cfc8f52019-08-07 10:41:09 +0100875 case kAnalysisFailPhiEquivalentInOsr: {
876 MaybeRecordStat(compilation_stats_.get(),
877 MethodCompilationStat::kNotCompiledPhiEquivalentInOsr);
878 break;
879 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000880 case kAnalysisSuccess:
881 UNREACHABLE();
David Brazdil809658e2015-02-05 11:34:02 +0000882 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000883 pass_observer.SetGraphInBadState();
884 return nullptr;
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000885 }
David Brazdilbadd8262016-02-02 16:28:56 +0000886 }
Vladimir Markof9f64412015-09-02 14:05:49 +0100887
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100888 if (compilation_kind == CompilationKind::kBaseline) {
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100889 RunBaselineOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer);
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100890 } else {
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100891 RunOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer);
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100892 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000893
894 RegisterAllocator::Strategy regalloc_strategy =
895 compiler_options.GetRegisterAllocationStrategy();
Igor Murashkin1e065a52017-08-09 13:20:34 -0700896 AllocateRegisters(graph,
897 codegen.get(),
898 &pass_observer,
Igor Murashkin6ef45672017-08-08 13:59:55 -0700899 regalloc_strategy,
900 compilation_stats_.get());
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000901
902 codegen->Compile(code_allocator);
903 pass_observer.DumpDisassembly();
904
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000905 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledBytecode);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000906 return codegen.release();
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000907}
908
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000909CodeGenerator* OptimizingCompiler::TryCompileIntrinsic(
910 ArenaAllocator* allocator,
911 ArenaStack* arena_stack,
912 CodeVectorAllocator* code_allocator,
913 const DexCompilationUnit& dex_compilation_unit,
914 ArtMethod* method,
915 VariableSizedHandleScope* handles) const {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000916 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kAttemptIntrinsicCompilation);
Vladimir Marko038924b2019-02-19 15:09:35 +0000917 const CompilerOptions& compiler_options = GetCompilerOptions();
Vladimir Markoa0431112018-06-25 09:32:54 +0100918 InstructionSet instruction_set = compiler_options.GetInstructionSet();
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000919 const DexFile& dex_file = *dex_compilation_unit.GetDexFile();
920 uint32_t method_idx = dex_compilation_unit.GetDexMethodIndex();
921
922 // Always use the Thumb-2 assembler: some runtime functionality
923 // (like implicit stack overflow checks) assume Thumb-2.
924 DCHECK_NE(instruction_set, InstructionSet::kArm);
925
926 // Do not attempt to compile on architectures we do not support.
927 if (!IsInstructionSetSupported(instruction_set)) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000928 return nullptr;
929 }
930
931 HGraph* graph = new (allocator) HGraph(
932 allocator,
933 arena_stack,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100934 handles,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000935 dex_file,
936 method_idx,
Vladimir Marko2afaff72018-11-30 17:01:50 +0000937 compiler_options.GetInstructionSet(),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000938 kInvalidInvokeType,
Hans Boehm206348c2018-12-05 11:11:33 -0800939 /* dead_reference_safe= */ true, // Intrinsics don't affect dead reference safety.
Vladimir Marko2afaff72018-11-30 17:01:50 +0000940 compiler_options.GetDebuggable(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100941 CompilationKind::kOptimized);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000942
943 DCHECK(Runtime::Current()->IsAotCompiler());
944 DCHECK(method != nullptr);
945 graph->SetArtMethod(method);
946
947 std::unique_ptr<CodeGenerator> codegen(
948 CodeGenerator::Create(graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100949 compiler_options,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000950 compilation_stats_.get()));
951 if (codegen.get() == nullptr) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000952 return nullptr;
953 }
Vladimir Markoa0431112018-06-25 09:32:54 +0100954 codegen->GetAssembler()->cfi().SetEnabled(compiler_options.GenerateAnyDebugInfo());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000955
956 PassObserver pass_observer(graph,
957 codegen.get(),
958 visualizer_output_.get(),
Vladimir Marko038924b2019-02-19 15:09:35 +0000959 compiler_options,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000960 dump_mutex_);
961
962 {
963 VLOG(compiler) << "Building intrinsic graph " << pass_observer.GetMethodName();
964 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
965 HGraphBuilder builder(graph,
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800966 CodeItemDebugInfoAccessor(), // Null code item.
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000967 &dex_compilation_unit,
968 &dex_compilation_unit,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000969 codegen.get(),
Nicolas Geoffray4924ea92021-03-23 08:25:31 +0000970 compilation_stats_.get());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000971 builder.BuildIntrinsicGraph(method);
972 }
973
Aart Bik2ca10eb2017-11-15 15:17:53 -0800974 OptimizationDef optimizations[] = {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +0100975 // The codegen has a few assumptions that only the instruction simplifier
976 // can satisfy.
Aart Bik2ca10eb2017-11-15 15:17:53 -0800977 OptDef(OptimizationPass::kInstructionSimplifier),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000978 };
Aart Bik2ca10eb2017-11-15 15:17:53 -0800979 RunOptimizations(graph,
980 codegen.get(),
981 dex_compilation_unit,
982 &pass_observer,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800983 optimizations);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000984
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100985 RunArchOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000986
987 AllocateRegisters(graph,
988 codegen.get(),
989 &pass_observer,
Vladimir Marko038924b2019-02-19 15:09:35 +0000990 compiler_options.GetRegisterAllocationStrategy(),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000991 compilation_stats_.get());
992 if (!codegen->IsLeafMethod()) {
993 VLOG(compiler) << "Intrinsic method is not leaf: " << method->GetIntrinsic()
994 << " " << graph->PrettyMethod();
995 return nullptr;
996 }
997
998 codegen->Compile(code_allocator);
999 pass_observer.DumpDisassembly();
1000
1001 VLOG(compiler) << "Compiled intrinsic: " << method->GetIntrinsic()
1002 << " " << graph->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001003 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledIntrinsic);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001004 return codegen.release();
1005}
1006
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001007CompiledMethod* OptimizingCompiler::Compile(const dex::CodeItem* code_item,
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001008 uint32_t access_flags,
1009 InvokeType invoke_type,
1010 uint16_t class_def_idx,
1011 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001012 Handle<mirror::ClassLoader> jclass_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -07001013 const DexFile& dex_file,
1014 Handle<mirror::DexCache> dex_cache) const {
Vladimir Marko038924b2019-02-19 15:09:35 +00001015 const CompilerOptions& compiler_options = GetCompilerOptions();
Vladimir Marko695348f2020-05-19 14:42:02 +01001016 DCHECK(compiler_options.IsAotCompiler());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001017 CompiledMethod* compiled_method = nullptr;
1018 Runtime* runtime = Runtime::Current();
1019 DCHECK(runtime->IsAotCompiler());
Vladimir Marko2afaff72018-11-30 17:01:50 +00001020 const VerifiedMethod* verified_method = compiler_options.GetVerifiedMethod(&dex_file, method_idx);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001021 DCHECK(!verified_method->HasRuntimeThrow());
Vladimir Marko2afaff72018-11-30 17:01:50 +00001022 if (compiler_options.IsMethodVerifiedWithoutFailures(method_idx, class_def_idx, dex_file) ||
Vladimir Markoca6fff82017-10-03 14:49:14 +01001023 verifier::CanCompilerHandleVerificationFailure(
1024 verified_method->GetEncounteredVerificationFailures())) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001025 ArenaAllocator allocator(runtime->GetArenaPool());
1026 ArenaStack arena_stack(runtime->GetArenaPool());
Vladimir Markoca6fff82017-10-03 14:49:14 +01001027 CodeVectorAllocator code_allocator(&allocator);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001028 std::unique_ptr<CodeGenerator> codegen;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001029 bool compiled_intrinsic = false;
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001030 {
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001031 ScopedObjectAccess soa(Thread::Current());
1032 ArtMethod* method =
1033 runtime->GetClassLinker()->ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
1034 method_idx, dex_cache, jclass_loader, /*referrer=*/ nullptr, invoke_type);
1035 DCHECK_EQ(method == nullptr, soa.Self()->IsExceptionPending());
1036 soa.Self()->ClearException(); // Suppress exception if any.
1037 VariableSizedHandleScope handles(soa.Self());
1038 Handle<mirror::Class> compiling_class =
1039 handles.NewHandle(method != nullptr ? method->GetDeclaringClass() : nullptr);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001040 DexCompilationUnit dex_compilation_unit(
1041 jclass_loader,
1042 runtime->GetClassLinker(),
1043 dex_file,
1044 code_item,
1045 class_def_idx,
1046 method_idx,
1047 access_flags,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001048 /*verified_method=*/ nullptr, // Not needed by the Optimizing compiler.
1049 dex_cache,
1050 compiling_class);
Vladimir Marko43d57552020-09-07 12:30:17 +00001051 // All signature polymorphic methods are native.
1052 DCHECK(method == nullptr || !method->IsSignaturePolymorphic());
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001053 // Go to native so that we don't block GC during compilation.
1054 ScopedThreadSuspension sts(soa.Self(), kNative);
Vladimir Marko43d57552020-09-07 12:30:17 +00001055 // Try to compile a fully intrinsified implementation.
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001056 if (method != nullptr && UNLIKELY(method->IsIntrinsic())) {
Vladimir Marko2afaff72018-11-30 17:01:50 +00001057 DCHECK(compiler_options.IsBootImage());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001058 codegen.reset(
1059 TryCompileIntrinsic(&allocator,
1060 &arena_stack,
1061 &code_allocator,
1062 dex_compilation_unit,
1063 method,
1064 &handles));
1065 if (codegen != nullptr) {
1066 compiled_intrinsic = true;
1067 }
1068 }
1069 if (codegen == nullptr) {
1070 codegen.reset(
1071 TryCompile(&allocator,
1072 &arena_stack,
1073 &code_allocator,
1074 dex_compilation_unit,
1075 method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001076 compiler_options.IsBaseline()
1077 ? CompilationKind::kBaseline
1078 : CompilationKind::kOptimized,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001079 &handles));
1080 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001081 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001082 if (codegen.get() != nullptr) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001083 compiled_method = Emit(&allocator,
1084 &code_allocator,
1085 codegen.get(),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001086 compiled_intrinsic ? nullptr : code_item);
1087 if (compiled_intrinsic) {
1088 compiled_method->MarkAsIntrinsic();
1089 }
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001090
1091 if (kArenaAllocatorCountAllocations) {
Vladimir Marko174b2e22017-10-12 13:34:49 +01001092 codegen.reset(); // Release codegen's ScopedArenaAllocator for memory accounting.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001093 size_t total_allocated = allocator.BytesAllocated() + arena_stack.PeakBytesAllocated();
1094 if (total_allocated > kArenaAllocatorMemoryReportThreshold) {
1095 MemStats mem_stats(allocator.GetMemStats());
1096 MemStats peak_stats(arena_stack.GetPeakStats());
Vladimir Marko69d310e2017-10-09 14:12:23 +01001097 LOG(INFO) << "Used " << total_allocated << " bytes of arena memory for compiling "
1098 << dex_file.PrettyMethod(method_idx)
Vladimir Markoca6fff82017-10-03 14:49:14 +01001099 << "\n" << Dumpable<MemStats>(mem_stats)
1100 << "\n" << Dumpable<MemStats>(peak_stats);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001101 }
1102 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001103 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001104 } else {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001105 MethodCompilationStat method_stat;
Vladimir Marko2afaff72018-11-30 17:01:50 +00001106 if (compiler_options.VerifyAtRuntime()) {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001107 method_stat = MethodCompilationStat::kNotCompiledVerifyAtRuntime;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001108 } else {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001109 method_stat = MethodCompilationStat::kNotCompiledVerificationError;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001110 }
Igor Murashkin1e065a52017-08-09 13:20:34 -07001111 MaybeRecordStat(compilation_stats_.get(), method_stat);
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001112 }
1113
Calin Juravlecff8cc72015-10-09 12:03:24 +01001114 if (kIsDebugBuild &&
David Srbecky4fa07a52020-03-31 20:52:09 +01001115 compiler_options.CompileArtTest() &&
Vladimir Marko2afaff72018-11-30 17:01:50 +00001116 IsInstructionSetSupported(compiler_options.GetInstructionSet())) {
Roland Levillain0d5a2812015-11-13 10:07:31 +00001117 // For testing purposes, we put a special marker on method names
Goran Jakovljevic9c4f0d8f2017-04-05 16:27:25 +02001118 // that should be compiled with this compiler (when the
1119 // instruction set is supported). This makes sure we're not
Roland Levillain0d5a2812015-11-13 10:07:31 +00001120 // regressing.
David Sehr709b0702016-10-13 09:12:37 -07001121 std::string method_name = dex_file.PrettyMethod(method_idx);
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001122 bool shouldCompile = method_name.find("$opt$") != std::string::npos;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001123 DCHECK((compiled_method != nullptr) || !shouldCompile) << "Didn't compile " << method_name;
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001124 }
1125
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001126 return compiled_method;
1127}
1128
David Srbeckye7a91942018-08-01 17:23:53 +01001129static ScopedArenaVector<uint8_t> CreateJniStackMap(ScopedArenaAllocator* allocator,
David Srbecky17b4d2b2021-03-02 18:14:31 +00001130 const JniCompiledMethod& jni_compiled_method,
1131 size_t code_size) {
Vladimir Markoced04832018-07-26 14:42:17 +01001132 // StackMapStream is quite large, so allocate it using the ScopedArenaAllocator
1133 // to stay clear of the frame size limit.
1134 std::unique_ptr<StackMapStream> stack_map_stream(
David Srbeckye7a91942018-08-01 17:23:53 +01001135 new (allocator) StackMapStream(allocator, jni_compiled_method.GetInstructionSet()));
Vladimir Markoced04832018-07-26 14:42:17 +01001136 stack_map_stream->BeginMethod(
David Srbeckyafc97bc2018-07-05 08:14:35 +00001137 jni_compiled_method.GetFrameSize(),
1138 jni_compiled_method.GetCoreSpillMask(),
1139 jni_compiled_method.GetFpSpillMask(),
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001140 /* num_dex_registers= */ 0,
1141 /* baseline= */ false);
David Srbecky17b4d2b2021-03-02 18:14:31 +00001142 stack_map_stream->EndMethod(code_size);
David Srbeckye7a91942018-08-01 17:23:53 +01001143 return stack_map_stream->Encode();
David Srbeckyafc97bc2018-07-05 08:14:35 +00001144}
1145
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001146CompiledMethod* OptimizingCompiler::JniCompile(uint32_t access_flags,
1147 uint32_t method_idx,
1148 const DexFile& dex_file,
1149 Handle<mirror::DexCache> dex_cache) const {
David Srbeckyafc97bc2018-07-05 08:14:35 +00001150 Runtime* runtime = Runtime::Current();
1151 ArenaAllocator allocator(runtime->GetArenaPool());
1152 ArenaStack arena_stack(runtime->GetArenaPool());
1153
Vladimir Marko038924b2019-02-19 15:09:35 +00001154 const CompilerOptions& compiler_options = GetCompilerOptions();
Vladimir Markoa0431112018-06-25 09:32:54 +01001155 if (compiler_options.IsBootImage()) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001156 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001157 ArtMethod* method = runtime->GetClassLinker()->LookupResolvedMethod(
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001158 method_idx, dex_cache.Get(), /*class_loader=*/ nullptr);
Vladimir Marko43d57552020-09-07 12:30:17 +00001159 // Try to compile a fully intrinsified implementation. Do not try to do this for
1160 // signature polymorphic methods as the InstructionBuilder cannot handle them;
1161 // and it would be useless as they always have a slow path for type conversions.
1162 if (method != nullptr && UNLIKELY(method->IsIntrinsic()) && !method->IsSignaturePolymorphic()) {
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001163 VariableSizedHandleScope handles(soa.Self());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001164 ScopedNullHandle<mirror::ClassLoader> class_loader; // null means boot class path loader.
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001165 Handle<mirror::Class> compiling_class = handles.NewHandle(method->GetDeclaringClass());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001166 DexCompilationUnit dex_compilation_unit(
1167 class_loader,
1168 runtime->GetClassLinker(),
1169 dex_file,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001170 /*code_item=*/ nullptr,
1171 /*class_def_idx=*/ DexFile::kDexNoIndex16,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001172 method_idx,
1173 access_flags,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001174 /*verified_method=*/ nullptr,
1175 dex_cache,
1176 compiling_class);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001177 CodeVectorAllocator code_allocator(&allocator);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001178 // Go to native so that we don't block GC during compilation.
1179 ScopedThreadSuspension sts(soa.Self(), kNative);
1180 std::unique_ptr<CodeGenerator> codegen(
1181 TryCompileIntrinsic(&allocator,
1182 &arena_stack,
1183 &code_allocator,
1184 dex_compilation_unit,
1185 method,
1186 &handles));
1187 if (codegen != nullptr) {
1188 CompiledMethod* compiled_method = Emit(&allocator,
1189 &code_allocator,
1190 codegen.get(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001191 /* item= */ nullptr);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001192 compiled_method->MarkAsIntrinsic();
1193 return compiled_method;
1194 }
1195 }
1196 }
1197
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001198 JniCompiledMethod jni_compiled_method = ArtQuickJniCompileMethod(
Vladimir Markoa0431112018-06-25 09:32:54 +01001199 compiler_options, access_flags, method_idx, dex_file);
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001200 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledNativeStub);
David Srbeckyafc97bc2018-07-05 08:14:35 +00001201
David Srbeckye7a91942018-08-01 17:23:53 +01001202 ScopedArenaAllocator stack_map_allocator(&arena_stack); // Will hold the stack map.
David Srbecky17b4d2b2021-03-02 18:14:31 +00001203 ScopedArenaVector<uint8_t> stack_map = CreateJniStackMap(
1204 &stack_map_allocator, jni_compiled_method, jni_compiled_method.GetCode().size());
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001205 return CompiledMethod::SwapAllocCompiledMethod(
Vladimir Marko038924b2019-02-19 15:09:35 +00001206 GetCompiledMethodStorage(),
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001207 jni_compiled_method.GetInstructionSet(),
1208 jni_compiled_method.GetCode(),
David Srbeckyafc97bc2018-07-05 08:14:35 +00001209 ArrayRef<const uint8_t>(stack_map),
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001210 jni_compiled_method.GetCfi(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001211 /* patches= */ ArrayRef<const linker::LinkerPatch>());
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001212}
1213
Vladimir Marko038924b2019-02-19 15:09:35 +00001214Compiler* CreateOptimizingCompiler(const CompilerOptions& compiler_options,
1215 CompiledMethodStorage* storage) {
1216 return new OptimizingCompiler(compiler_options, storage);
Andreas Gampe53c913b2014-08-12 23:19:23 -07001217}
1218
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001219bool EncodeArtMethodInInlineInfo(ArtMethod* method ATTRIBUTE_UNUSED) {
1220 // Note: the runtime is null only for unit testing.
1221 return Runtime::Current() == nullptr || !Runtime::Current()->IsAotCompiler();
1222}
1223
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001224bool OptimizingCompiler::JitCompile(Thread* self,
1225 jit::JitCodeCache* code_cache,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +01001226 jit::JitMemoryRegion* region,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001227 ArtMethod* method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001228 CompilationKind compilation_kind,
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001229 jit::JitLogger* jit_logger) {
Vladimir Marko695348f2020-05-19 14:42:02 +01001230 const CompilerOptions& compiler_options = GetCompilerOptions();
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001231 // If the baseline flag was explicitly passed, change the compilation kind
1232 // from optimized to baseline.
1233 if (compiler_options.IsBaseline() && compilation_kind == CompilationKind::kOptimized) {
1234 compilation_kind = CompilationKind::kBaseline;
1235 }
Vladimir Marko695348f2020-05-19 14:42:02 +01001236 DCHECK(compiler_options.IsJitCompiler());
1237 DCHECK_EQ(compiler_options.IsJitCompilerForSharedCode(), code_cache->IsSharedRegion(*region));
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001238 StackHandleScope<3> hs(self);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001239 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1240 method->GetDeclaringClass()->GetClassLoader()));
1241 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001242 DCHECK(method->IsCompilable());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001243
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001244 const DexFile* dex_file = method->GetDexFile();
1245 const uint16_t class_def_idx = method->GetClassDefIndex();
Nicolas Geoffray47171752020-08-31 15:03:20 +01001246 const dex::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001247 const uint32_t method_idx = method->GetDexMethodIndex();
1248 const uint32_t access_flags = method->GetAccessFlags();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001249
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001250 Runtime* runtime = Runtime::Current();
1251 ArenaAllocator allocator(runtime->GetJitArenaPool());
Vladimir Marko2196c652017-11-30 16:16:07 +00001252
1253 if (UNLIKELY(method->IsNative())) {
1254 JniCompiledMethod jni_compiled_method = ArtQuickJniCompileMethod(
Vladimir Markoa0431112018-06-25 09:32:54 +01001255 compiler_options, access_flags, method_idx, *dex_file);
Vladimir Markoac3ac682018-09-20 11:01:43 +01001256 std::vector<Handle<mirror::Object>> roots;
Vladimir Marko2196c652017-11-30 16:16:07 +00001257 ArenaSet<ArtMethod*, std::less<ArtMethod*>> cha_single_implementation_list(
1258 allocator.Adapter(kArenaAllocCHA));
David Srbeckyafc97bc2018-07-05 08:14:35 +00001259 ArenaStack arena_stack(runtime->GetJitArenaPool());
1260 // StackMapStream is large and it does not fit into this frame, so we need helper method.
David Srbeckye7a91942018-08-01 17:23:53 +01001261 ScopedArenaAllocator stack_map_allocator(&arena_stack); // Will hold the stack map.
David Srbecky17b4d2b2021-03-02 18:14:31 +00001262 ScopedArenaVector<uint8_t> stack_map = CreateJniStackMap(
1263 &stack_map_allocator, jni_compiled_method, jni_compiled_method.GetCode().size());
David Srbeckyadb66f92019-10-10 12:59:43 +00001264
1265 ArrayRef<const uint8_t> reserved_code;
1266 ArrayRef<const uint8_t> reserved_data;
1267 if (!code_cache->Reserve(self,
1268 region,
1269 jni_compiled_method.GetCode().size(),
1270 stack_map.size(),
1271 /* number_of_roots= */ 0,
1272 method,
1273 /*out*/ &reserved_code,
1274 /*out*/ &reserved_data)) {
David Srbeckyafc97bc2018-07-05 08:14:35 +00001275 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kJitOutOfMemoryForCommit);
1276 return false;
1277 }
David Srbeckyadb66f92019-10-10 12:59:43 +00001278 const uint8_t* code = reserved_code.data() + OatQuickMethodHeader::InstructionAlignedSize();
David Srbeckyafc97bc2018-07-05 08:14:35 +00001279
David Srbecky444e9982019-10-02 17:59:23 +01001280 // Add debug info after we know the code location but before we update entry-point.
David Srbecky41617b12020-03-18 21:19:06 +00001281 std::vector<uint8_t> debug_info;
David Srbeckyadb66f92019-10-10 12:59:43 +00001282 if (compiler_options.GenerateAnyDebugInfo()) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001283 debug::MethodDebugInfo info = {};
Yabin Cuif3f1c8b2021-01-26 13:44:07 -08001284 // Simpleperf relies on art_jni_trampoline to detect jni methods.
David Srbeckyfe1d9522019-03-25 17:19:11 +00001285 info.custom_name = "art_jni_trampoline";
Vladimir Marko2196c652017-11-30 16:16:07 +00001286 info.dex_file = dex_file;
1287 info.class_def_index = class_def_idx;
1288 info.dex_method_index = method_idx;
1289 info.access_flags = access_flags;
1290 info.code_item = code_item;
1291 info.isa = jni_compiled_method.GetInstructionSet();
1292 info.deduped = false;
1293 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1294 info.is_optimized = true;
1295 info.is_code_address_text_relative = false;
David Srbeckyadb66f92019-10-10 12:59:43 +00001296 info.code_address = reinterpret_cast<uintptr_t>(code);
Vladimir Marko2196c652017-11-30 16:16:07 +00001297 info.code_size = jni_compiled_method.GetCode().size();
David Srbeckyadb66f92019-10-10 12:59:43 +00001298 info.frame_size_in_bytes = jni_compiled_method.GetFrameSize();
Vladimir Marko2196c652017-11-30 16:16:07 +00001299 info.code_info = nullptr;
1300 info.cfi = jni_compiled_method.GetCfi();
David Srbecky41617b12020-03-18 21:19:06 +00001301 debug_info = GenerateJitDebugInfo(info);
David Srbeckyadb66f92019-10-10 12:59:43 +00001302 }
David Srbecky444e9982019-10-02 17:59:23 +01001303
David Srbeckyadb66f92019-10-10 12:59:43 +00001304 if (!code_cache->Commit(self,
1305 region,
1306 method,
1307 reserved_code,
1308 jni_compiled_method.GetCode(),
1309 reserved_data,
1310 roots,
1311 ArrayRef<const uint8_t>(stack_map),
David Srbecky41617b12020-03-18 21:19:06 +00001312 debug_info,
1313 /* is_full_debug_info= */ compiler_options.GetGenerateDebugInfo(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001314 compilation_kind,
David Srbeckyadb66f92019-10-10 12:59:43 +00001315 /* has_should_deoptimize_flag= */ false,
1316 cha_single_implementation_list)) {
1317 code_cache->Free(self, region, reserved_code.data(), reserved_data.data());
David Srbecky444e9982019-10-02 17:59:23 +01001318 return false;
Vladimir Marko2196c652017-11-30 16:16:07 +00001319 }
1320
1321 Runtime::Current()->GetJit()->AddMemoryUsage(method, allocator.BytesUsed());
1322 if (jit_logger != nullptr) {
1323 jit_logger->WriteLog(code, jni_compiled_method.GetCode().size(), method);
1324 }
1325 return true;
1326 }
1327
1328 ArenaStack arena_stack(runtime->GetJitArenaPool());
Vladimir Markoca6fff82017-10-03 14:49:14 +01001329 CodeVectorAllocator code_allocator(&allocator);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001330 VariableSizedHandleScope handles(self);
1331
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001332 std::unique_ptr<CodeGenerator> codegen;
1333 {
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001334 Handle<mirror::Class> compiling_class = handles.NewHandle(method->GetDeclaringClass());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001335 DexCompilationUnit dex_compilation_unit(
1336 class_loader,
1337 runtime->GetClassLinker(),
1338 *dex_file,
1339 code_item,
1340 class_def_idx,
1341 method_idx,
1342 access_flags,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001343 /*verified_method=*/ nullptr,
1344 dex_cache,
1345 compiling_class);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001346
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001347 // Go to native so that we don't block GC during compilation.
1348 ScopedThreadSuspension sts(self, kNative);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001349 codegen.reset(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001350 TryCompile(&allocator,
1351 &arena_stack,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001352 &code_allocator,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001353 dex_compilation_unit,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +00001354 method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001355 compilation_kind,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001356 &handles));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001357 if (codegen.get() == nullptr) {
1358 return false;
1359 }
1360 }
1361
David Srbeckye7a91942018-08-01 17:23:53 +01001362 ScopedArenaVector<uint8_t> stack_map = codegen->BuildStackMaps(code_item);
David Srbeckyadb66f92019-10-10 12:59:43 +00001363
1364 ArrayRef<const uint8_t> reserved_code;
1365 ArrayRef<const uint8_t> reserved_data;
1366 if (!code_cache->Reserve(self,
1367 region,
1368 code_allocator.GetMemory().size(),
1369 stack_map.size(),
1370 /*number_of_roots=*/codegen->GetNumberOfJitRoots(),
1371 method,
1372 /*out*/ &reserved_code,
1373 /*out*/ &reserved_data)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001374 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kJitOutOfMemoryForCommit);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001375 return false;
1376 }
David Srbeckyadb66f92019-10-10 12:59:43 +00001377 const uint8_t* code = reserved_code.data() + OatQuickMethodHeader::InstructionAlignedSize();
1378 const uint8_t* roots_data = reserved_data.data();
1379
Vladimir Markoac3ac682018-09-20 11:01:43 +01001380 std::vector<Handle<mirror::Object>> roots;
1381 codegen->EmitJitRoots(code_allocator.GetData(), roots_data, &roots);
1382 // The root Handle<>s filled by the codegen reference entries in the VariableSizedHandleScope.
1383 DCHECK(std::all_of(roots.begin(),
1384 roots.end(),
1385 [&handles](Handle<mirror::Object> root){
1386 return handles.Contains(root.GetReference());
1387 }));
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001388
David Srbecky444e9982019-10-02 17:59:23 +01001389 // Add debug info after we know the code location but before we update entry-point.
David Srbecky41617b12020-03-18 21:19:06 +00001390 std::vector<uint8_t> debug_info;
David Srbeckyadb66f92019-10-10 12:59:43 +00001391 if (compiler_options.GenerateAnyDebugInfo()) {
Vladimir Marko1b404a82017-09-01 13:35:26 +01001392 debug::MethodDebugInfo info = {};
David Srbeckyc684f332018-01-19 17:38:06 +00001393 DCHECK(info.custom_name.empty());
David Srbecky197160d2016-03-07 17:33:57 +00001394 info.dex_file = dex_file;
1395 info.class_def_index = class_def_idx;
1396 info.dex_method_index = method_idx;
1397 info.access_flags = access_flags;
1398 info.code_item = code_item;
1399 info.isa = codegen->GetInstructionSet();
1400 info.deduped = false;
1401 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1402 info.is_optimized = true;
1403 info.is_code_address_text_relative = false;
David Srbeckyadb66f92019-10-10 12:59:43 +00001404 info.code_address = reinterpret_cast<uintptr_t>(code);
Vladimir Markoca1e0382018-04-11 09:58:41 +00001405 info.code_size = code_allocator.GetMemory().size();
David Srbeckyadb66f92019-10-10 12:59:43 +00001406 info.frame_size_in_bytes = codegen->GetFrameSize();
1407 info.code_info = stack_map.size() == 0 ? nullptr : stack_map.data();
David Srbecky197160d2016-03-07 17:33:57 +00001408 info.cfi = ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data());
David Srbecky41617b12020-03-18 21:19:06 +00001409 debug_info = GenerateJitDebugInfo(info);
David Srbeckyadb66f92019-10-10 12:59:43 +00001410 }
David Srbecky444e9982019-10-02 17:59:23 +01001411
David Srbeckyadb66f92019-10-10 12:59:43 +00001412 if (!code_cache->Commit(self,
1413 region,
1414 method,
1415 reserved_code,
1416 code_allocator.GetMemory(),
1417 reserved_data,
1418 roots,
1419 ArrayRef<const uint8_t>(stack_map),
David Srbecky41617b12020-03-18 21:19:06 +00001420 debug_info,
1421 /* is_full_debug_info= */ compiler_options.GetGenerateDebugInfo(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001422 compilation_kind,
David Srbeckyadb66f92019-10-10 12:59:43 +00001423 codegen->GetGraph()->HasShouldDeoptimizeFlag(),
1424 codegen->GetGraph()->GetCHASingleImplementationList())) {
1425 code_cache->Free(self, region, reserved_code.data(), reserved_data.data());
David Srbecky444e9982019-10-02 17:59:23 +01001426 return false;
David Srbecky5cc349f2015-12-18 15:04:48 +00001427 }
1428
Vladimir Markoca6fff82017-10-03 14:49:14 +01001429 Runtime::Current()->GetJit()->AddMemoryUsage(method, allocator.BytesUsed());
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001430 if (jit_logger != nullptr) {
Vladimir Markoca1e0382018-04-11 09:58:41 +00001431 jit_logger->WriteLog(code, code_allocator.GetMemory().size(), method);
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001432 }
Nicolas Geoffraya4f81542016-03-08 16:57:48 +00001433
Vladimir Marko174b2e22017-10-12 13:34:49 +01001434 if (kArenaAllocatorCountAllocations) {
1435 codegen.reset(); // Release codegen's ScopedArenaAllocator for memory accounting.
1436 size_t total_allocated = allocator.BytesAllocated() + arena_stack.PeakBytesAllocated();
1437 if (total_allocated > kArenaAllocatorMemoryReportThreshold) {
1438 MemStats mem_stats(allocator.GetMemStats());
1439 MemStats peak_stats(arena_stack.GetPeakStats());
1440 LOG(INFO) << "Used " << total_allocated << " bytes of arena memory for compiling "
1441 << dex_file->PrettyMethod(method_idx)
1442 << "\n" << Dumpable<MemStats>(mem_stats)
1443 << "\n" << Dumpable<MemStats>(peak_stats);
1444 }
1445 }
1446
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001447 return true;
1448}
1449
David Srbecky41617b12020-03-18 21:19:06 +00001450std::vector<uint8_t> OptimizingCompiler::GenerateJitDebugInfo(const debug::MethodDebugInfo& info) {
Vladimir Marko038924b2019-02-19 15:09:35 +00001451 const CompilerOptions& compiler_options = GetCompilerOptions();
David Srbecky444e9982019-10-02 17:59:23 +01001452 if (compiler_options.GenerateAnyDebugInfo()) {
David Srbecky43ae7792019-01-09 17:34:01 +00001453 // If both flags are passed, generate full debug info.
1454 const bool mini_debug_info = !compiler_options.GetGenerateDebugInfo();
David Srbeckyc684f332018-01-19 17:38:06 +00001455
David Srbecky43ae7792019-01-09 17:34:01 +00001456 // Create entry for the single method that we just compiled.
David Srbecky8fc2f952019-07-31 18:40:09 +01001457 InstructionSet isa = compiler_options.GetInstructionSet();
1458 const InstructionSetFeatures* features = compiler_options.GetInstructionSetFeatures();
David Srbecky41617b12020-03-18 21:19:06 +00001459 return debug::MakeElfFileForJIT(isa, features, mini_debug_info, info);
David Srbecky43ae7792019-01-09 17:34:01 +00001460 }
David Srbecky41617b12020-03-18 21:19:06 +00001461 return std::vector<uint8_t>();
David Srbeckyc684f332018-01-19 17:38:06 +00001462}
1463
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001464} // namespace art