blob: 8cd34cf68f9c30f5852bbff3495aa72aaa3246a3 [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;
787 ArrayRef<const uint8_t> interpreter_metadata;
788 // For AOT compilation, we may not get a method, for example if its class is erroneous,
789 // possibly due to an unavailable superclass. JIT should always have a method.
790 DCHECK(Runtime::Current()->IsAotCompiler() || method != nullptr);
791 if (method != nullptr) {
792 const dex::ClassDef* containing_class;
793 {
794 ScopedObjectAccess soa(Thread::Current());
795 containing_class = &method->GetClassDef();
796 interpreter_metadata = method->GetQuickenedInfo();
797 }
798 // MethodContainsRSensitiveAccess is currently slow, but HasDeadReferenceSafeAnnotation()
799 // is currently rarely true.
800 dead_reference_safe =
801 annotations::HasDeadReferenceSafeAnnotation(dex_file, *containing_class)
802 && !annotations::MethodContainsRSensitiveAccess(dex_file, *containing_class, method_idx);
803 } else {
804 // If we could not resolve the class, conservatively assume it's dead-reference unsafe.
805 dead_reference_safe = false;
806 }
807
Vladimir Markoca6fff82017-10-03 14:49:14 +0100808 HGraph* graph = new (allocator) HGraph(
809 allocator,
810 arena_stack,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100811 handles,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000812 dex_file,
813 method_idx,
Vladimir Markoa0431112018-06-25 09:32:54 +0100814 compiler_options.GetInstructionSet(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000815 kInvalidInvokeType,
Hans Boehm206348c2018-12-05 11:11:33 -0800816 dead_reference_safe,
Vladimir Marko038924b2019-02-19 15:09:35 +0000817 compiler_options.GetDebuggable(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100818 compilation_kind);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000819
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000820 if (method != nullptr) {
821 graph->SetArtMethod(method);
David Brazdilbadd8262016-02-02 16:28:56 +0000822 }
823
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000824 std::unique_ptr<CodeGenerator> codegen(
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000825 CodeGenerator::Create(graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100826 compiler_options,
Calin Juravle2ae48182016-03-16 14:05:09 +0000827 compilation_stats_.get()));
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000828 if (codegen.get() == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000829 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledNoCodegen);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000830 return nullptr;
831 }
Vladimir Marko038924b2019-02-19 15:09:35 +0000832 codegen->GetAssembler()->cfi().SetEnabled(compiler_options.GenerateAnyDebugInfo());
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000833
David Brazdil69ba7b72015-06-23 18:27:30 +0100834 PassObserver pass_observer(graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100835 codegen.get(),
836 visualizer_output_.get(),
Vladimir Marko038924b2019-02-19 15:09:35 +0000837 compiler_options,
Andreas Gampea0d81af2016-10-27 12:04:57 -0700838 dump_mutex_);
David Brazdil5e8b1372015-01-23 14:39:08 +0000839
David Brazdil809658e2015-02-05 11:34:02 +0000840 {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000841 VLOG(compiler) << "Building " << pass_observer.GetMethodName();
842 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
843 HGraphBuilder builder(graph,
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800844 code_item_accessor,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000845 &dex_compilation_unit,
846 &dex_compilation_unit,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000847 codegen.get(),
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000848 compilation_stats_.get(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100849 interpreter_metadata);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000850 GraphAnalysisResult result = builder.BuildGraph();
851 if (result != kAnalysisSuccess) {
852 switch (result) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700853 case kAnalysisSkipped: {
854 MaybeRecordStat(compilation_stats_.get(),
855 MethodCompilationStat::kNotCompiledSkipped);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000856 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100857 }
Igor Murashkin1e065a52017-08-09 13:20:34 -0700858 case kAnalysisInvalidBytecode: {
859 MaybeRecordStat(compilation_stats_.get(),
860 MethodCompilationStat::kNotCompiledInvalidBytecode);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000861 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100862 }
Igor Murashkin1e065a52017-08-09 13:20:34 -0700863 case kAnalysisFailThrowCatchLoop: {
864 MaybeRecordStat(compilation_stats_.get(),
865 MethodCompilationStat::kNotCompiledThrowCatchLoop);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000866 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100867 }
Igor Murashkin1e065a52017-08-09 13:20:34 -0700868 case kAnalysisFailAmbiguousArrayOp: {
869 MaybeRecordStat(compilation_stats_.get(),
870 MethodCompilationStat::kNotCompiledAmbiguousArrayOp);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000871 break;
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +0100872 }
Nicolas Geoffray0846a8f2018-09-12 15:21:07 +0100873 case kAnalysisFailIrreducibleLoopAndStringInit: {
874 MaybeRecordStat(compilation_stats_.get(),
875 MethodCompilationStat::kNotCompiledIrreducibleLoopAndStringInit);
876 break;
877 }
Nicolas Geoffray7cfc8f52019-08-07 10:41:09 +0100878 case kAnalysisFailPhiEquivalentInOsr: {
879 MaybeRecordStat(compilation_stats_.get(),
880 MethodCompilationStat::kNotCompiledPhiEquivalentInOsr);
881 break;
882 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000883 case kAnalysisSuccess:
884 UNREACHABLE();
David Brazdil809658e2015-02-05 11:34:02 +0000885 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000886 pass_observer.SetGraphInBadState();
887 return nullptr;
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000888 }
David Brazdilbadd8262016-02-02 16:28:56 +0000889 }
Vladimir Markof9f64412015-09-02 14:05:49 +0100890
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100891 if (compilation_kind == CompilationKind::kBaseline) {
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100892 RunBaselineOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer);
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100893 } else {
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100894 RunOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer);
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +0100895 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000896
897 RegisterAllocator::Strategy regalloc_strategy =
898 compiler_options.GetRegisterAllocationStrategy();
Igor Murashkin1e065a52017-08-09 13:20:34 -0700899 AllocateRegisters(graph,
900 codegen.get(),
901 &pass_observer,
Igor Murashkin6ef45672017-08-08 13:59:55 -0700902 regalloc_strategy,
903 compilation_stats_.get());
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000904
905 codegen->Compile(code_allocator);
906 pass_observer.DumpDisassembly();
907
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000908 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledBytecode);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000909 return codegen.release();
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000910}
911
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000912CodeGenerator* OptimizingCompiler::TryCompileIntrinsic(
913 ArenaAllocator* allocator,
914 ArenaStack* arena_stack,
915 CodeVectorAllocator* code_allocator,
916 const DexCompilationUnit& dex_compilation_unit,
917 ArtMethod* method,
918 VariableSizedHandleScope* handles) const {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000919 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kAttemptIntrinsicCompilation);
Vladimir Marko038924b2019-02-19 15:09:35 +0000920 const CompilerOptions& compiler_options = GetCompilerOptions();
Vladimir Markoa0431112018-06-25 09:32:54 +0100921 InstructionSet instruction_set = compiler_options.GetInstructionSet();
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000922 const DexFile& dex_file = *dex_compilation_unit.GetDexFile();
923 uint32_t method_idx = dex_compilation_unit.GetDexMethodIndex();
924
925 // Always use the Thumb-2 assembler: some runtime functionality
926 // (like implicit stack overflow checks) assume Thumb-2.
927 DCHECK_NE(instruction_set, InstructionSet::kArm);
928
929 // Do not attempt to compile on architectures we do not support.
930 if (!IsInstructionSetSupported(instruction_set)) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000931 return nullptr;
932 }
933
934 HGraph* graph = new (allocator) HGraph(
935 allocator,
936 arena_stack,
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100937 handles,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000938 dex_file,
939 method_idx,
Vladimir Marko2afaff72018-11-30 17:01:50 +0000940 compiler_options.GetInstructionSet(),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000941 kInvalidInvokeType,
Hans Boehm206348c2018-12-05 11:11:33 -0800942 /* dead_reference_safe= */ true, // Intrinsics don't affect dead reference safety.
Vladimir Marko2afaff72018-11-30 17:01:50 +0000943 compiler_options.GetDebuggable(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100944 CompilationKind::kOptimized);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000945
946 DCHECK(Runtime::Current()->IsAotCompiler());
947 DCHECK(method != nullptr);
948 graph->SetArtMethod(method);
949
950 std::unique_ptr<CodeGenerator> codegen(
951 CodeGenerator::Create(graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100952 compiler_options,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000953 compilation_stats_.get()));
954 if (codegen.get() == nullptr) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000955 return nullptr;
956 }
Vladimir Markoa0431112018-06-25 09:32:54 +0100957 codegen->GetAssembler()->cfi().SetEnabled(compiler_options.GenerateAnyDebugInfo());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000958
959 PassObserver pass_observer(graph,
960 codegen.get(),
961 visualizer_output_.get(),
Vladimir Marko038924b2019-02-19 15:09:35 +0000962 compiler_options,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000963 dump_mutex_);
964
965 {
966 VLOG(compiler) << "Building intrinsic graph " << pass_observer.GetMethodName();
967 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
968 HGraphBuilder builder(graph,
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800969 CodeItemDebugInfoAccessor(), // Null code item.
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000970 &dex_compilation_unit,
971 &dex_compilation_unit,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000972 codegen.get(),
973 compilation_stats_.get(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100974 /* interpreter_metadata= */ ArrayRef<const uint8_t>());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000975 builder.BuildIntrinsicGraph(method);
976 }
977
Aart Bik2ca10eb2017-11-15 15:17:53 -0800978 OptimizationDef optimizations[] = {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +0100979 // The codegen has a few assumptions that only the instruction simplifier
980 // can satisfy.
Aart Bik2ca10eb2017-11-15 15:17:53 -0800981 OptDef(OptimizationPass::kInstructionSimplifier),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000982 };
Aart Bik2ca10eb2017-11-15 15:17:53 -0800983 RunOptimizations(graph,
984 codegen.get(),
985 dex_compilation_unit,
986 &pass_observer,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800987 optimizations);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000988
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100989 RunArchOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000990
991 AllocateRegisters(graph,
992 codegen.get(),
993 &pass_observer,
Vladimir Marko038924b2019-02-19 15:09:35 +0000994 compiler_options.GetRegisterAllocationStrategy(),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000995 compilation_stats_.get());
996 if (!codegen->IsLeafMethod()) {
997 VLOG(compiler) << "Intrinsic method is not leaf: " << method->GetIntrinsic()
998 << " " << graph->PrettyMethod();
999 return nullptr;
1000 }
1001
1002 codegen->Compile(code_allocator);
1003 pass_observer.DumpDisassembly();
1004
1005 VLOG(compiler) << "Compiled intrinsic: " << method->GetIntrinsic()
1006 << " " << graph->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001007 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledIntrinsic);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001008 return codegen.release();
1009}
1010
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001011CompiledMethod* OptimizingCompiler::Compile(const dex::CodeItem* code_item,
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001012 uint32_t access_flags,
1013 InvokeType invoke_type,
1014 uint16_t class_def_idx,
1015 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001016 Handle<mirror::ClassLoader> jclass_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -07001017 const DexFile& dex_file,
1018 Handle<mirror::DexCache> dex_cache) const {
Vladimir Marko038924b2019-02-19 15:09:35 +00001019 const CompilerOptions& compiler_options = GetCompilerOptions();
Vladimir Marko695348f2020-05-19 14:42:02 +01001020 DCHECK(compiler_options.IsAotCompiler());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001021 CompiledMethod* compiled_method = nullptr;
1022 Runtime* runtime = Runtime::Current();
1023 DCHECK(runtime->IsAotCompiler());
Vladimir Marko2afaff72018-11-30 17:01:50 +00001024 const VerifiedMethod* verified_method = compiler_options.GetVerifiedMethod(&dex_file, method_idx);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001025 DCHECK(!verified_method->HasRuntimeThrow());
Vladimir Marko2afaff72018-11-30 17:01:50 +00001026 if (compiler_options.IsMethodVerifiedWithoutFailures(method_idx, class_def_idx, dex_file) ||
Vladimir Markoca6fff82017-10-03 14:49:14 +01001027 verifier::CanCompilerHandleVerificationFailure(
1028 verified_method->GetEncounteredVerificationFailures())) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001029 ArenaAllocator allocator(runtime->GetArenaPool());
1030 ArenaStack arena_stack(runtime->GetArenaPool());
Vladimir Markoca6fff82017-10-03 14:49:14 +01001031 CodeVectorAllocator code_allocator(&allocator);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001032 std::unique_ptr<CodeGenerator> codegen;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001033 bool compiled_intrinsic = false;
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001034 {
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001035 ScopedObjectAccess soa(Thread::Current());
1036 ArtMethod* method =
1037 runtime->GetClassLinker()->ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
1038 method_idx, dex_cache, jclass_loader, /*referrer=*/ nullptr, invoke_type);
1039 DCHECK_EQ(method == nullptr, soa.Self()->IsExceptionPending());
1040 soa.Self()->ClearException(); // Suppress exception if any.
1041 VariableSizedHandleScope handles(soa.Self());
1042 Handle<mirror::Class> compiling_class =
1043 handles.NewHandle(method != nullptr ? method->GetDeclaringClass() : nullptr);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001044 DexCompilationUnit dex_compilation_unit(
1045 jclass_loader,
1046 runtime->GetClassLinker(),
1047 dex_file,
1048 code_item,
1049 class_def_idx,
1050 method_idx,
1051 access_flags,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001052 /*verified_method=*/ nullptr, // Not needed by the Optimizing compiler.
1053 dex_cache,
1054 compiling_class);
Vladimir Marko43d57552020-09-07 12:30:17 +00001055 // All signature polymorphic methods are native.
1056 DCHECK(method == nullptr || !method->IsSignaturePolymorphic());
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001057 // Go to native so that we don't block GC during compilation.
1058 ScopedThreadSuspension sts(soa.Self(), kNative);
Vladimir Marko43d57552020-09-07 12:30:17 +00001059 // Try to compile a fully intrinsified implementation.
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001060 if (method != nullptr && UNLIKELY(method->IsIntrinsic())) {
Vladimir Marko2afaff72018-11-30 17:01:50 +00001061 DCHECK(compiler_options.IsBootImage());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001062 codegen.reset(
1063 TryCompileIntrinsic(&allocator,
1064 &arena_stack,
1065 &code_allocator,
1066 dex_compilation_unit,
1067 method,
1068 &handles));
1069 if (codegen != nullptr) {
1070 compiled_intrinsic = true;
1071 }
1072 }
1073 if (codegen == nullptr) {
1074 codegen.reset(
1075 TryCompile(&allocator,
1076 &arena_stack,
1077 &code_allocator,
1078 dex_compilation_unit,
1079 method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001080 compiler_options.IsBaseline()
1081 ? CompilationKind::kBaseline
1082 : CompilationKind::kOptimized,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001083 &handles));
1084 }
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001085 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001086 if (codegen.get() != nullptr) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001087 compiled_method = Emit(&allocator,
1088 &code_allocator,
1089 codegen.get(),
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001090 compiled_intrinsic ? nullptr : code_item);
1091 if (compiled_intrinsic) {
1092 compiled_method->MarkAsIntrinsic();
1093 }
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001094
1095 if (kArenaAllocatorCountAllocations) {
Vladimir Marko174b2e22017-10-12 13:34:49 +01001096 codegen.reset(); // Release codegen's ScopedArenaAllocator for memory accounting.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001097 size_t total_allocated = allocator.BytesAllocated() + arena_stack.PeakBytesAllocated();
1098 if (total_allocated > kArenaAllocatorMemoryReportThreshold) {
1099 MemStats mem_stats(allocator.GetMemStats());
1100 MemStats peak_stats(arena_stack.GetPeakStats());
Vladimir Marko69d310e2017-10-09 14:12:23 +01001101 LOG(INFO) << "Used " << total_allocated << " bytes of arena memory for compiling "
1102 << dex_file.PrettyMethod(method_idx)
Vladimir Markoca6fff82017-10-03 14:49:14 +01001103 << "\n" << Dumpable<MemStats>(mem_stats)
1104 << "\n" << Dumpable<MemStats>(peak_stats);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001105 }
1106 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001107 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001108 } else {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001109 MethodCompilationStat method_stat;
Vladimir Marko2afaff72018-11-30 17:01:50 +00001110 if (compiler_options.VerifyAtRuntime()) {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001111 method_stat = MethodCompilationStat::kNotCompiledVerifyAtRuntime;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001112 } else {
Igor Murashkin1e065a52017-08-09 13:20:34 -07001113 method_stat = MethodCompilationStat::kNotCompiledVerificationError;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001114 }
Igor Murashkin1e065a52017-08-09 13:20:34 -07001115 MaybeRecordStat(compilation_stats_.get(), method_stat);
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001116 }
1117
Calin Juravlecff8cc72015-10-09 12:03:24 +01001118 if (kIsDebugBuild &&
David Srbecky4fa07a52020-03-31 20:52:09 +01001119 compiler_options.CompileArtTest() &&
Vladimir Marko2afaff72018-11-30 17:01:50 +00001120 IsInstructionSetSupported(compiler_options.GetInstructionSet())) {
Roland Levillain0d5a2812015-11-13 10:07:31 +00001121 // For testing purposes, we put a special marker on method names
Goran Jakovljevic9c4f0d8f2017-04-05 16:27:25 +02001122 // that should be compiled with this compiler (when the
1123 // instruction set is supported). This makes sure we're not
Roland Levillain0d5a2812015-11-13 10:07:31 +00001124 // regressing.
David Sehr709b0702016-10-13 09:12:37 -07001125 std::string method_name = dex_file.PrettyMethod(method_idx);
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001126 bool shouldCompile = method_name.find("$opt$") != std::string::npos;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001127 DCHECK((compiled_method != nullptr) || !shouldCompile) << "Didn't compile " << method_name;
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001128 }
1129
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001130 return compiled_method;
1131}
1132
David Srbeckye7a91942018-08-01 17:23:53 +01001133static ScopedArenaVector<uint8_t> CreateJniStackMap(ScopedArenaAllocator* allocator,
Nicolas Geoffraybf5f0f32019-03-05 15:41:50 +00001134 const JniCompiledMethod& jni_compiled_method) {
Vladimir Markoced04832018-07-26 14:42:17 +01001135 // StackMapStream is quite large, so allocate it using the ScopedArenaAllocator
1136 // to stay clear of the frame size limit.
1137 std::unique_ptr<StackMapStream> stack_map_stream(
David Srbeckye7a91942018-08-01 17:23:53 +01001138 new (allocator) StackMapStream(allocator, jni_compiled_method.GetInstructionSet()));
Vladimir Markoced04832018-07-26 14:42:17 +01001139 stack_map_stream->BeginMethod(
David Srbeckyafc97bc2018-07-05 08:14:35 +00001140 jni_compiled_method.GetFrameSize(),
1141 jni_compiled_method.GetCoreSpillMask(),
1142 jni_compiled_method.GetFpSpillMask(),
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001143 /* num_dex_registers= */ 0,
1144 /* baseline= */ false);
Nicolas Geoffraybf5f0f32019-03-05 15:41:50 +00001145 stack_map_stream->EndMethod();
David Srbeckye7a91942018-08-01 17:23:53 +01001146 return stack_map_stream->Encode();
David Srbeckyafc97bc2018-07-05 08:14:35 +00001147}
1148
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001149CompiledMethod* OptimizingCompiler::JniCompile(uint32_t access_flags,
1150 uint32_t method_idx,
1151 const DexFile& dex_file,
1152 Handle<mirror::DexCache> dex_cache) const {
David Srbeckyafc97bc2018-07-05 08:14:35 +00001153 Runtime* runtime = Runtime::Current();
1154 ArenaAllocator allocator(runtime->GetArenaPool());
1155 ArenaStack arena_stack(runtime->GetArenaPool());
1156
Vladimir Marko038924b2019-02-19 15:09:35 +00001157 const CompilerOptions& compiler_options = GetCompilerOptions();
Vladimir Markoa0431112018-06-25 09:32:54 +01001158 if (compiler_options.IsBootImage()) {
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001159 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001160 ArtMethod* method = runtime->GetClassLinker()->LookupResolvedMethod(
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001161 method_idx, dex_cache.Get(), /*class_loader=*/ nullptr);
Vladimir Marko43d57552020-09-07 12:30:17 +00001162 // Try to compile a fully intrinsified implementation. Do not try to do this for
1163 // signature polymorphic methods as the InstructionBuilder cannot handle them;
1164 // and it would be useless as they always have a slow path for type conversions.
1165 if (method != nullptr && UNLIKELY(method->IsIntrinsic()) && !method->IsSignaturePolymorphic()) {
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001166 VariableSizedHandleScope handles(soa.Self());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001167 ScopedNullHandle<mirror::ClassLoader> class_loader; // null means boot class path loader.
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001168 Handle<mirror::Class> compiling_class = handles.NewHandle(method->GetDeclaringClass());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001169 DexCompilationUnit dex_compilation_unit(
1170 class_loader,
1171 runtime->GetClassLinker(),
1172 dex_file,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001173 /*code_item=*/ nullptr,
1174 /*class_def_idx=*/ DexFile::kDexNoIndex16,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001175 method_idx,
1176 access_flags,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001177 /*verified_method=*/ nullptr,
1178 dex_cache,
1179 compiling_class);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001180 CodeVectorAllocator code_allocator(&allocator);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001181 // Go to native so that we don't block GC during compilation.
1182 ScopedThreadSuspension sts(soa.Self(), kNative);
1183 std::unique_ptr<CodeGenerator> codegen(
1184 TryCompileIntrinsic(&allocator,
1185 &arena_stack,
1186 &code_allocator,
1187 dex_compilation_unit,
1188 method,
1189 &handles));
1190 if (codegen != nullptr) {
1191 CompiledMethod* compiled_method = Emit(&allocator,
1192 &code_allocator,
1193 codegen.get(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001194 /* item= */ nullptr);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001195 compiled_method->MarkAsIntrinsic();
1196 return compiled_method;
1197 }
1198 }
1199 }
1200
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001201 JniCompiledMethod jni_compiled_method = ArtQuickJniCompileMethod(
Vladimir Markoa0431112018-06-25 09:32:54 +01001202 compiler_options, access_flags, method_idx, dex_file);
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001203 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledNativeStub);
David Srbeckyafc97bc2018-07-05 08:14:35 +00001204
David Srbeckye7a91942018-08-01 17:23:53 +01001205 ScopedArenaAllocator stack_map_allocator(&arena_stack); // Will hold the stack map.
Nicolas Geoffraybf5f0f32019-03-05 15:41:50 +00001206 ScopedArenaVector<uint8_t> stack_map = CreateJniStackMap(&stack_map_allocator,
1207 jni_compiled_method);
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001208 return CompiledMethod::SwapAllocCompiledMethod(
Vladimir Marko038924b2019-02-19 15:09:35 +00001209 GetCompiledMethodStorage(),
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001210 jni_compiled_method.GetInstructionSet(),
1211 jni_compiled_method.GetCode(),
David Srbeckyafc97bc2018-07-05 08:14:35 +00001212 ArrayRef<const uint8_t>(stack_map),
Vladimir Marko7bdc6e72017-11-28 12:37:13 +00001213 jni_compiled_method.GetCfi(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001214 /* patches= */ ArrayRef<const linker::LinkerPatch>());
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001215}
1216
Vladimir Marko038924b2019-02-19 15:09:35 +00001217Compiler* CreateOptimizingCompiler(const CompilerOptions& compiler_options,
1218 CompiledMethodStorage* storage) {
1219 return new OptimizingCompiler(compiler_options, storage);
Andreas Gampe53c913b2014-08-12 23:19:23 -07001220}
1221
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001222bool EncodeArtMethodInInlineInfo(ArtMethod* method ATTRIBUTE_UNUSED) {
1223 // Note: the runtime is null only for unit testing.
1224 return Runtime::Current() == nullptr || !Runtime::Current()->IsAotCompiler();
1225}
1226
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001227bool OptimizingCompiler::JitCompile(Thread* self,
1228 jit::JitCodeCache* code_cache,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +01001229 jit::JitMemoryRegion* region,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001230 ArtMethod* method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001231 CompilationKind compilation_kind,
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001232 jit::JitLogger* jit_logger) {
Vladimir Marko695348f2020-05-19 14:42:02 +01001233 const CompilerOptions& compiler_options = GetCompilerOptions();
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001234 // If the baseline flag was explicitly passed, change the compilation kind
1235 // from optimized to baseline.
1236 if (compiler_options.IsBaseline() && compilation_kind == CompilationKind::kOptimized) {
1237 compilation_kind = CompilationKind::kBaseline;
1238 }
Vladimir Marko695348f2020-05-19 14:42:02 +01001239 DCHECK(compiler_options.IsJitCompiler());
1240 DCHECK_EQ(compiler_options.IsJitCompilerForSharedCode(), code_cache->IsSharedRegion(*region));
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001241 StackHandleScope<3> hs(self);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001242 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1243 method->GetDeclaringClass()->GetClassLoader()));
1244 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001245 DCHECK(method->IsCompilable());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001246
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001247 const DexFile* dex_file = method->GetDexFile();
1248 const uint16_t class_def_idx = method->GetClassDefIndex();
Nicolas Geoffray47171752020-08-31 15:03:20 +01001249 const dex::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001250 const uint32_t method_idx = method->GetDexMethodIndex();
1251 const uint32_t access_flags = method->GetAccessFlags();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001252
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001253 Runtime* runtime = Runtime::Current();
1254 ArenaAllocator allocator(runtime->GetJitArenaPool());
Vladimir Marko2196c652017-11-30 16:16:07 +00001255
1256 if (UNLIKELY(method->IsNative())) {
1257 JniCompiledMethod jni_compiled_method = ArtQuickJniCompileMethod(
Vladimir Markoa0431112018-06-25 09:32:54 +01001258 compiler_options, access_flags, method_idx, *dex_file);
Vladimir Markoac3ac682018-09-20 11:01:43 +01001259 std::vector<Handle<mirror::Object>> roots;
Vladimir Marko2196c652017-11-30 16:16:07 +00001260 ArenaSet<ArtMethod*, std::less<ArtMethod*>> cha_single_implementation_list(
1261 allocator.Adapter(kArenaAllocCHA));
David Srbeckyafc97bc2018-07-05 08:14:35 +00001262 ArenaStack arena_stack(runtime->GetJitArenaPool());
1263 // StackMapStream is large and it does not fit into this frame, so we need helper method.
David Srbeckye7a91942018-08-01 17:23:53 +01001264 ScopedArenaAllocator stack_map_allocator(&arena_stack); // Will hold the stack map.
Nicolas Geoffraybf5f0f32019-03-05 15:41:50 +00001265 ScopedArenaVector<uint8_t> stack_map = CreateJniStackMap(&stack_map_allocator,
1266 jni_compiled_method);
David Srbeckyadb66f92019-10-10 12:59:43 +00001267
1268 ArrayRef<const uint8_t> reserved_code;
1269 ArrayRef<const uint8_t> reserved_data;
1270 if (!code_cache->Reserve(self,
1271 region,
1272 jni_compiled_method.GetCode().size(),
1273 stack_map.size(),
1274 /* number_of_roots= */ 0,
1275 method,
1276 /*out*/ &reserved_code,
1277 /*out*/ &reserved_data)) {
David Srbeckyafc97bc2018-07-05 08:14:35 +00001278 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kJitOutOfMemoryForCommit);
1279 return false;
1280 }
David Srbeckyadb66f92019-10-10 12:59:43 +00001281 const uint8_t* code = reserved_code.data() + OatQuickMethodHeader::InstructionAlignedSize();
David Srbeckyafc97bc2018-07-05 08:14:35 +00001282
David Srbecky444e9982019-10-02 17:59:23 +01001283 // Add debug info after we know the code location but before we update entry-point.
David Srbecky41617b12020-03-18 21:19:06 +00001284 std::vector<uint8_t> debug_info;
David Srbeckyadb66f92019-10-10 12:59:43 +00001285 if (compiler_options.GenerateAnyDebugInfo()) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001286 debug::MethodDebugInfo info = {};
David Srbeckyfe1d9522019-03-25 17:19:11 +00001287 info.custom_name = "art_jni_trampoline";
Vladimir Marko2196c652017-11-30 16:16:07 +00001288 info.dex_file = dex_file;
1289 info.class_def_index = class_def_idx;
1290 info.dex_method_index = method_idx;
1291 info.access_flags = access_flags;
1292 info.code_item = code_item;
1293 info.isa = jni_compiled_method.GetInstructionSet();
1294 info.deduped = false;
1295 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1296 info.is_optimized = true;
1297 info.is_code_address_text_relative = false;
David Srbeckyadb66f92019-10-10 12:59:43 +00001298 info.code_address = reinterpret_cast<uintptr_t>(code);
Vladimir Marko2196c652017-11-30 16:16:07 +00001299 info.code_size = jni_compiled_method.GetCode().size();
David Srbeckyadb66f92019-10-10 12:59:43 +00001300 info.frame_size_in_bytes = jni_compiled_method.GetFrameSize();
Vladimir Marko2196c652017-11-30 16:16:07 +00001301 info.code_info = nullptr;
1302 info.cfi = jni_compiled_method.GetCfi();
David Srbecky41617b12020-03-18 21:19:06 +00001303 debug_info = GenerateJitDebugInfo(info);
David Srbeckyadb66f92019-10-10 12:59:43 +00001304 }
David Srbecky444e9982019-10-02 17:59:23 +01001305
David Srbeckyadb66f92019-10-10 12:59:43 +00001306 if (!code_cache->Commit(self,
1307 region,
1308 method,
1309 reserved_code,
1310 jni_compiled_method.GetCode(),
1311 reserved_data,
1312 roots,
1313 ArrayRef<const uint8_t>(stack_map),
David Srbecky41617b12020-03-18 21:19:06 +00001314 debug_info,
1315 /* is_full_debug_info= */ compiler_options.GetGenerateDebugInfo(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001316 compilation_kind,
David Srbeckyadb66f92019-10-10 12:59:43 +00001317 /* has_should_deoptimize_flag= */ false,
1318 cha_single_implementation_list)) {
1319 code_cache->Free(self, region, reserved_code.data(), reserved_data.data());
David Srbecky444e9982019-10-02 17:59:23 +01001320 return false;
Vladimir Marko2196c652017-11-30 16:16:07 +00001321 }
1322
1323 Runtime::Current()->GetJit()->AddMemoryUsage(method, allocator.BytesUsed());
1324 if (jit_logger != nullptr) {
1325 jit_logger->WriteLog(code, jni_compiled_method.GetCode().size(), method);
1326 }
1327 return true;
1328 }
1329
1330 ArenaStack arena_stack(runtime->GetJitArenaPool());
Vladimir Markoca6fff82017-10-03 14:49:14 +01001331 CodeVectorAllocator code_allocator(&allocator);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001332 VariableSizedHandleScope handles(self);
1333
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001334 std::unique_ptr<CodeGenerator> codegen;
1335 {
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001336 Handle<mirror::Class> compiling_class = handles.NewHandle(method->GetDeclaringClass());
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001337 DexCompilationUnit dex_compilation_unit(
1338 class_loader,
1339 runtime->GetClassLinker(),
1340 *dex_file,
1341 code_item,
1342 class_def_idx,
1343 method_idx,
1344 access_flags,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001345 /*verified_method=*/ nullptr,
1346 dex_cache,
1347 compiling_class);
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001348
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001349 // Go to native so that we don't block GC during compilation.
1350 ScopedThreadSuspension sts(self, kNative);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001351 codegen.reset(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001352 TryCompile(&allocator,
1353 &arena_stack,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001354 &code_allocator,
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001355 dex_compilation_unit,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +00001356 method,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001357 compilation_kind,
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001358 &handles));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001359 if (codegen.get() == nullptr) {
1360 return false;
1361 }
1362 }
1363
David Srbeckye7a91942018-08-01 17:23:53 +01001364 ScopedArenaVector<uint8_t> stack_map = codegen->BuildStackMaps(code_item);
David Srbeckyadb66f92019-10-10 12:59:43 +00001365
1366 ArrayRef<const uint8_t> reserved_code;
1367 ArrayRef<const uint8_t> reserved_data;
1368 if (!code_cache->Reserve(self,
1369 region,
1370 code_allocator.GetMemory().size(),
1371 stack_map.size(),
1372 /*number_of_roots=*/codegen->GetNumberOfJitRoots(),
1373 method,
1374 /*out*/ &reserved_code,
1375 /*out*/ &reserved_data)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001376 MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kJitOutOfMemoryForCommit);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001377 return false;
1378 }
David Srbeckyadb66f92019-10-10 12:59:43 +00001379 const uint8_t* code = reserved_code.data() + OatQuickMethodHeader::InstructionAlignedSize();
1380 const uint8_t* roots_data = reserved_data.data();
1381
Vladimir Markoac3ac682018-09-20 11:01:43 +01001382 std::vector<Handle<mirror::Object>> roots;
1383 codegen->EmitJitRoots(code_allocator.GetData(), roots_data, &roots);
1384 // The root Handle<>s filled by the codegen reference entries in the VariableSizedHandleScope.
1385 DCHECK(std::all_of(roots.begin(),
1386 roots.end(),
1387 [&handles](Handle<mirror::Object> root){
1388 return handles.Contains(root.GetReference());
1389 }));
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001390
David Srbecky444e9982019-10-02 17:59:23 +01001391 // Add debug info after we know the code location but before we update entry-point.
David Srbecky41617b12020-03-18 21:19:06 +00001392 std::vector<uint8_t> debug_info;
David Srbeckyadb66f92019-10-10 12:59:43 +00001393 if (compiler_options.GenerateAnyDebugInfo()) {
Vladimir Marko1b404a82017-09-01 13:35:26 +01001394 debug::MethodDebugInfo info = {};
David Srbeckyc684f332018-01-19 17:38:06 +00001395 DCHECK(info.custom_name.empty());
David Srbecky197160d2016-03-07 17:33:57 +00001396 info.dex_file = dex_file;
1397 info.class_def_index = class_def_idx;
1398 info.dex_method_index = method_idx;
1399 info.access_flags = access_flags;
1400 info.code_item = code_item;
1401 info.isa = codegen->GetInstructionSet();
1402 info.deduped = false;
1403 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1404 info.is_optimized = true;
1405 info.is_code_address_text_relative = false;
David Srbeckyadb66f92019-10-10 12:59:43 +00001406 info.code_address = reinterpret_cast<uintptr_t>(code);
Vladimir Markoca1e0382018-04-11 09:58:41 +00001407 info.code_size = code_allocator.GetMemory().size();
David Srbeckyadb66f92019-10-10 12:59:43 +00001408 info.frame_size_in_bytes = codegen->GetFrameSize();
1409 info.code_info = stack_map.size() == 0 ? nullptr : stack_map.data();
David Srbecky197160d2016-03-07 17:33:57 +00001410 info.cfi = ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data());
David Srbecky41617b12020-03-18 21:19:06 +00001411 debug_info = GenerateJitDebugInfo(info);
David Srbeckyadb66f92019-10-10 12:59:43 +00001412 }
David Srbecky444e9982019-10-02 17:59:23 +01001413
David Srbeckyadb66f92019-10-10 12:59:43 +00001414 if (!code_cache->Commit(self,
1415 region,
1416 method,
1417 reserved_code,
1418 code_allocator.GetMemory(),
1419 reserved_data,
1420 roots,
1421 ArrayRef<const uint8_t>(stack_map),
David Srbecky41617b12020-03-18 21:19:06 +00001422 debug_info,
1423 /* is_full_debug_info= */ compiler_options.GetGenerateDebugInfo(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001424 compilation_kind,
David Srbeckyadb66f92019-10-10 12:59:43 +00001425 codegen->GetGraph()->HasShouldDeoptimizeFlag(),
1426 codegen->GetGraph()->GetCHASingleImplementationList())) {
1427 code_cache->Free(self, region, reserved_code.data(), reserved_data.data());
David Srbecky444e9982019-10-02 17:59:23 +01001428 return false;
David Srbecky5cc349f2015-12-18 15:04:48 +00001429 }
1430
Vladimir Markoca6fff82017-10-03 14:49:14 +01001431 Runtime::Current()->GetJit()->AddMemoryUsage(method, allocator.BytesUsed());
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001432 if (jit_logger != nullptr) {
Vladimir Markoca1e0382018-04-11 09:58:41 +00001433 jit_logger->WriteLog(code, code_allocator.GetMemory().size(), method);
Nicolas Geoffray01db5f72017-07-19 15:05:49 +01001434 }
Nicolas Geoffraya4f81542016-03-08 16:57:48 +00001435
Vladimir Marko174b2e22017-10-12 13:34:49 +01001436 if (kArenaAllocatorCountAllocations) {
1437 codegen.reset(); // Release codegen's ScopedArenaAllocator for memory accounting.
1438 size_t total_allocated = allocator.BytesAllocated() + arena_stack.PeakBytesAllocated();
1439 if (total_allocated > kArenaAllocatorMemoryReportThreshold) {
1440 MemStats mem_stats(allocator.GetMemStats());
1441 MemStats peak_stats(arena_stack.GetPeakStats());
1442 LOG(INFO) << "Used " << total_allocated << " bytes of arena memory for compiling "
1443 << dex_file->PrettyMethod(method_idx)
1444 << "\n" << Dumpable<MemStats>(mem_stats)
1445 << "\n" << Dumpable<MemStats>(peak_stats);
1446 }
1447 }
1448
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001449 return true;
1450}
1451
David Srbecky41617b12020-03-18 21:19:06 +00001452std::vector<uint8_t> OptimizingCompiler::GenerateJitDebugInfo(const debug::MethodDebugInfo& info) {
Vladimir Marko038924b2019-02-19 15:09:35 +00001453 const CompilerOptions& compiler_options = GetCompilerOptions();
David Srbecky444e9982019-10-02 17:59:23 +01001454 if (compiler_options.GenerateAnyDebugInfo()) {
David Srbecky43ae7792019-01-09 17:34:01 +00001455 // If both flags are passed, generate full debug info.
1456 const bool mini_debug_info = !compiler_options.GetGenerateDebugInfo();
David Srbeckyc684f332018-01-19 17:38:06 +00001457
David Srbecky43ae7792019-01-09 17:34:01 +00001458 // Create entry for the single method that we just compiled.
David Srbecky8fc2f952019-07-31 18:40:09 +01001459 InstructionSet isa = compiler_options.GetInstructionSet();
1460 const InstructionSetFeatures* features = compiler_options.GetInstructionSetFeatures();
David Srbecky41617b12020-03-18 21:19:06 +00001461 return debug::MakeElfFileForJIT(isa, features, mini_debug_info, info);
David Srbecky43ae7792019-01-09 17:34:01 +00001462 }
David Srbecky41617b12020-03-18 21:19:06 +00001463 return std::vector<uint8_t>();
David Srbeckyc684f332018-01-19 17:38:06 +00001464}
1465
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001466} // namespace art