xref: /aosp_15_r20/art/compiler/optimizing/optimizing_compiler.cc (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
1*795d594fSAndroid Build Coastguard Worker /*
2*795d594fSAndroid Build Coastguard Worker  * Copyright (C) 2014 The Android Open Source Project
3*795d594fSAndroid Build Coastguard Worker  *
4*795d594fSAndroid Build Coastguard Worker  * Licensed under the Apache License, Version 2.0 (the "License");
5*795d594fSAndroid Build Coastguard Worker  * you may not use this file except in compliance with the License.
6*795d594fSAndroid Build Coastguard Worker  * You may obtain a copy of the License at
7*795d594fSAndroid Build Coastguard Worker  *
8*795d594fSAndroid Build Coastguard Worker  *      http://www.apache.org/licenses/LICENSE-2.0
9*795d594fSAndroid Build Coastguard Worker  *
10*795d594fSAndroid Build Coastguard Worker  * Unless required by applicable law or agreed to in writing, software
11*795d594fSAndroid Build Coastguard Worker  * distributed under the License is distributed on an "AS IS" BASIS,
12*795d594fSAndroid Build Coastguard Worker  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*795d594fSAndroid Build Coastguard Worker  * See the License for the specific language governing permissions and
14*795d594fSAndroid Build Coastguard Worker  * limitations under the License.
15*795d594fSAndroid Build Coastguard Worker  */
16*795d594fSAndroid Build Coastguard Worker 
17*795d594fSAndroid Build Coastguard Worker #include "optimizing_compiler.h"
18*795d594fSAndroid Build Coastguard Worker 
19*795d594fSAndroid Build Coastguard Worker #include <fstream>
20*795d594fSAndroid Build Coastguard Worker #include <memory>
21*795d594fSAndroid Build Coastguard Worker #include <sstream>
22*795d594fSAndroid Build Coastguard Worker 
23*795d594fSAndroid Build Coastguard Worker #include <stdint.h>
24*795d594fSAndroid Build Coastguard Worker 
25*795d594fSAndroid Build Coastguard Worker #include "art_method-inl.h"
26*795d594fSAndroid Build Coastguard Worker #include "base/arena_allocator.h"
27*795d594fSAndroid Build Coastguard Worker #include "base/arena_containers.h"
28*795d594fSAndroid Build Coastguard Worker #include "base/dumpable.h"
29*795d594fSAndroid Build Coastguard Worker #include "base/logging.h"
30*795d594fSAndroid Build Coastguard Worker #include "base/macros.h"
31*795d594fSAndroid Build Coastguard Worker #include "base/mutex.h"
32*795d594fSAndroid Build Coastguard Worker #include "base/scoped_arena_allocator.h"
33*795d594fSAndroid Build Coastguard Worker #include "base/systrace.h"
34*795d594fSAndroid Build Coastguard Worker #include "base/timing_logger.h"
35*795d594fSAndroid Build Coastguard Worker #include "builder.h"
36*795d594fSAndroid Build Coastguard Worker #include "code_generator.h"
37*795d594fSAndroid Build Coastguard Worker #include "compiler.h"
38*795d594fSAndroid Build Coastguard Worker #include "debug/elf_debug_writer.h"
39*795d594fSAndroid Build Coastguard Worker #include "debug/method_debug_info.h"
40*795d594fSAndroid Build Coastguard Worker #include "dex/dex_file_types.h"
41*795d594fSAndroid Build Coastguard Worker #include "driver/compiled_code_storage.h"
42*795d594fSAndroid Build Coastguard Worker #include "driver/compiler_options.h"
43*795d594fSAndroid Build Coastguard Worker #include "driver/dex_compilation_unit.h"
44*795d594fSAndroid Build Coastguard Worker #include "graph_checker.h"
45*795d594fSAndroid Build Coastguard Worker #include "graph_visualizer.h"
46*795d594fSAndroid Build Coastguard Worker #include "inliner.h"
47*795d594fSAndroid Build Coastguard Worker #include "jit/debugger_interface.h"
48*795d594fSAndroid Build Coastguard Worker #include "jit/jit.h"
49*795d594fSAndroid Build Coastguard Worker #include "jit/jit_code_cache.h"
50*795d594fSAndroid Build Coastguard Worker #include "jit/jit_logger.h"
51*795d594fSAndroid Build Coastguard Worker #include "jni/quick/jni_compiler.h"
52*795d594fSAndroid Build Coastguard Worker #include "linker/linker_patch.h"
53*795d594fSAndroid Build Coastguard Worker #include "nodes.h"
54*795d594fSAndroid Build Coastguard Worker #include "oat/oat_quick_method_header.h"
55*795d594fSAndroid Build Coastguard Worker #include "optimizing/write_barrier_elimination.h"
56*795d594fSAndroid Build Coastguard Worker #include "prepare_for_register_allocation.h"
57*795d594fSAndroid Build Coastguard Worker #include "profiling_info_builder.h"
58*795d594fSAndroid Build Coastguard Worker #include "reference_type_propagation.h"
59*795d594fSAndroid Build Coastguard Worker #include "register_allocator_linear_scan.h"
60*795d594fSAndroid Build Coastguard Worker #include "select_generator.h"
61*795d594fSAndroid Build Coastguard Worker #include "ssa_builder.h"
62*795d594fSAndroid Build Coastguard Worker #include "ssa_liveness_analysis.h"
63*795d594fSAndroid Build Coastguard Worker #include "ssa_phi_elimination.h"
64*795d594fSAndroid Build Coastguard Worker #include "stack_map_stream.h"
65*795d594fSAndroid Build Coastguard Worker #include "utils/assembler.h"
66*795d594fSAndroid Build Coastguard Worker 
67*795d594fSAndroid Build Coastguard Worker namespace art HIDDEN {
68*795d594fSAndroid Build Coastguard Worker 
69*795d594fSAndroid Build Coastguard Worker static constexpr size_t kArenaAllocatorMemoryReportThreshold = 8 * MB;
70*795d594fSAndroid Build Coastguard Worker 
71*795d594fSAndroid Build Coastguard Worker static constexpr const char* kPassNameSeparator = "$";
72*795d594fSAndroid Build Coastguard Worker 
73*795d594fSAndroid Build Coastguard Worker /**
74*795d594fSAndroid Build Coastguard Worker  * Filter to apply to the visualizer. Methods whose name contain that filter will
75*795d594fSAndroid Build Coastguard Worker  * be dumped.
76*795d594fSAndroid Build Coastguard Worker  */
77*795d594fSAndroid Build Coastguard Worker static constexpr const char kStringFilter[] = "";
78*795d594fSAndroid Build Coastguard Worker 
79*795d594fSAndroid Build Coastguard Worker class PassScope;
80*795d594fSAndroid Build Coastguard Worker 
81*795d594fSAndroid Build Coastguard Worker class PassObserver : public ValueObject {
82*795d594fSAndroid Build Coastguard Worker  public:
PassObserver(HGraph * graph,CodeGenerator * codegen,std::ostream * visualizer_output,const CompilerOptions & compiler_options)83*795d594fSAndroid Build Coastguard Worker   PassObserver(HGraph* graph,
84*795d594fSAndroid Build Coastguard Worker                CodeGenerator* codegen,
85*795d594fSAndroid Build Coastguard Worker                std::ostream* visualizer_output,
86*795d594fSAndroid Build Coastguard Worker                const CompilerOptions& compiler_options)
87*795d594fSAndroid Build Coastguard Worker       : graph_(graph),
88*795d594fSAndroid Build Coastguard Worker         last_seen_graph_size_(0),
89*795d594fSAndroid Build Coastguard Worker         cached_method_name_(),
90*795d594fSAndroid Build Coastguard Worker         timing_logger_enabled_(compiler_options.GetDumpPassTimings()),
91*795d594fSAndroid Build Coastguard Worker         timing_logger_(timing_logger_enabled_ ? GetMethodName() : "", true, true),
92*795d594fSAndroid Build Coastguard Worker         disasm_info_(graph->GetAllocator()),
93*795d594fSAndroid Build Coastguard Worker         visualizer_oss_(),
94*795d594fSAndroid Build Coastguard Worker         visualizer_output_(visualizer_output),
95*795d594fSAndroid Build Coastguard Worker         visualizer_enabled_(!compiler_options.GetDumpCfgFileName().empty()),
96*795d594fSAndroid Build Coastguard Worker         visualizer_(&visualizer_oss_, graph, codegen),
97*795d594fSAndroid Build Coastguard Worker         codegen_(codegen),
98*795d594fSAndroid Build Coastguard Worker         graph_in_bad_state_(false) {
99*795d594fSAndroid Build Coastguard Worker     if (timing_logger_enabled_ || visualizer_enabled_) {
100*795d594fSAndroid Build Coastguard Worker       if (!IsVerboseMethod(compiler_options, GetMethodName())) {
101*795d594fSAndroid Build Coastguard Worker         timing_logger_enabled_ = visualizer_enabled_ = false;
102*795d594fSAndroid Build Coastguard Worker       }
103*795d594fSAndroid Build Coastguard Worker       if (visualizer_enabled_) {
104*795d594fSAndroid Build Coastguard Worker         visualizer_.PrintHeader(GetMethodName());
105*795d594fSAndroid Build Coastguard Worker         codegen->SetDisassemblyInformation(&disasm_info_);
106*795d594fSAndroid Build Coastguard Worker       }
107*795d594fSAndroid Build Coastguard Worker     }
108*795d594fSAndroid Build Coastguard Worker   }
109*795d594fSAndroid Build Coastguard Worker 
~PassObserver()110*795d594fSAndroid Build Coastguard Worker   ~PassObserver() {
111*795d594fSAndroid Build Coastguard Worker     if (timing_logger_enabled_) {
112*795d594fSAndroid Build Coastguard Worker       LOG(INFO) << "TIMINGS " << GetMethodName();
113*795d594fSAndroid Build Coastguard Worker       LOG(INFO) << Dumpable<TimingLogger>(timing_logger_);
114*795d594fSAndroid Build Coastguard Worker     }
115*795d594fSAndroid Build Coastguard Worker     if (visualizer_enabled_) {
116*795d594fSAndroid Build Coastguard Worker       FlushVisualizer();
117*795d594fSAndroid Build Coastguard Worker     }
118*795d594fSAndroid Build Coastguard Worker     DCHECK(visualizer_oss_.str().empty());
119*795d594fSAndroid Build Coastguard Worker   }
120*795d594fSAndroid Build Coastguard Worker 
DumpDisassembly()121*795d594fSAndroid Build Coastguard Worker   void DumpDisassembly() {
122*795d594fSAndroid Build Coastguard Worker     if (visualizer_enabled_) {
123*795d594fSAndroid Build Coastguard Worker       visualizer_.DumpGraphWithDisassembly();
124*795d594fSAndroid Build Coastguard Worker       FlushVisualizer();
125*795d594fSAndroid Build Coastguard Worker     }
126*795d594fSAndroid Build Coastguard Worker   }
127*795d594fSAndroid Build Coastguard Worker 
SetGraphInBadState()128*795d594fSAndroid Build Coastguard Worker   void SetGraphInBadState() { graph_in_bad_state_ = true; }
129*795d594fSAndroid Build Coastguard Worker 
GetMethodName()130*795d594fSAndroid Build Coastguard Worker   const char* GetMethodName() {
131*795d594fSAndroid Build Coastguard Worker     // PrettyMethod() is expensive, so we delay calling it until we actually have to.
132*795d594fSAndroid Build Coastguard Worker     if (cached_method_name_.empty()) {
133*795d594fSAndroid Build Coastguard Worker       cached_method_name_ = graph_->GetDexFile().PrettyMethod(graph_->GetMethodIdx());
134*795d594fSAndroid Build Coastguard Worker     }
135*795d594fSAndroid Build Coastguard Worker     return cached_method_name_.c_str();
136*795d594fSAndroid Build Coastguard Worker   }
137*795d594fSAndroid Build Coastguard Worker 
138*795d594fSAndroid Build Coastguard Worker  private:
StartPass(const char * pass_name)139*795d594fSAndroid Build Coastguard Worker   void StartPass(const char* pass_name) {
140*795d594fSAndroid Build Coastguard Worker     VLOG(compiler) << "Starting pass: " << pass_name;
141*795d594fSAndroid Build Coastguard Worker     // Dump graph first, then start timer.
142*795d594fSAndroid Build Coastguard Worker     if (visualizer_enabled_) {
143*795d594fSAndroid Build Coastguard Worker       visualizer_.DumpGraph(pass_name, /* is_after_pass= */ false, graph_in_bad_state_);
144*795d594fSAndroid Build Coastguard Worker       FlushVisualizer();
145*795d594fSAndroid Build Coastguard Worker     }
146*795d594fSAndroid Build Coastguard Worker     if (timing_logger_enabled_) {
147*795d594fSAndroid Build Coastguard Worker       timing_logger_.StartTiming(pass_name);
148*795d594fSAndroid Build Coastguard Worker     }
149*795d594fSAndroid Build Coastguard Worker   }
150*795d594fSAndroid Build Coastguard Worker 
FlushVisualizer()151*795d594fSAndroid Build Coastguard Worker   void FlushVisualizer() {
152*795d594fSAndroid Build Coastguard Worker     *visualizer_output_ << visualizer_oss_.str();
153*795d594fSAndroid Build Coastguard Worker     visualizer_output_->flush();
154*795d594fSAndroid Build Coastguard Worker     visualizer_oss_.str("");
155*795d594fSAndroid Build Coastguard Worker     visualizer_oss_.clear();
156*795d594fSAndroid Build Coastguard Worker   }
157*795d594fSAndroid Build Coastguard Worker 
EndPass(const char * pass_name,bool pass_change)158*795d594fSAndroid Build Coastguard Worker   void EndPass(const char* pass_name, bool pass_change) {
159*795d594fSAndroid Build Coastguard Worker     // Pause timer first, then dump graph.
160*795d594fSAndroid Build Coastguard Worker     if (timing_logger_enabled_) {
161*795d594fSAndroid Build Coastguard Worker       timing_logger_.EndTiming();
162*795d594fSAndroid Build Coastguard Worker     }
163*795d594fSAndroid Build Coastguard Worker     if (visualizer_enabled_) {
164*795d594fSAndroid Build Coastguard Worker       visualizer_.DumpGraph(pass_name, /* is_after_pass= */ true, graph_in_bad_state_);
165*795d594fSAndroid Build Coastguard Worker       FlushVisualizer();
166*795d594fSAndroid Build Coastguard Worker     }
167*795d594fSAndroid Build Coastguard Worker 
168*795d594fSAndroid Build Coastguard Worker     // Validate the HGraph if running in debug mode.
169*795d594fSAndroid Build Coastguard Worker     if (kIsDebugBuild) {
170*795d594fSAndroid Build Coastguard Worker       if (!graph_in_bad_state_) {
171*795d594fSAndroid Build Coastguard Worker         GraphChecker checker(graph_, codegen_);
172*795d594fSAndroid Build Coastguard Worker         last_seen_graph_size_ = checker.Run(pass_change, last_seen_graph_size_);
173*795d594fSAndroid Build Coastguard Worker         if (!checker.IsValid()) {
174*795d594fSAndroid Build Coastguard Worker           std::ostringstream stream;
175*795d594fSAndroid Build Coastguard Worker           graph_->Dump(stream, codegen_);
176*795d594fSAndroid Build Coastguard Worker           LOG(FATAL_WITHOUT_ABORT) << "Error after " << pass_name << "(" << graph_->PrettyMethod()
177*795d594fSAndroid Build Coastguard Worker                                    << "): " << stream.str();
178*795d594fSAndroid Build Coastguard Worker           LOG(FATAL) << "(" << pass_name <<  "): " << Dumpable<GraphChecker>(checker);
179*795d594fSAndroid Build Coastguard Worker         }
180*795d594fSAndroid Build Coastguard Worker       }
181*795d594fSAndroid Build Coastguard Worker     }
182*795d594fSAndroid Build Coastguard Worker   }
183*795d594fSAndroid Build Coastguard Worker 
IsVerboseMethod(const CompilerOptions & compiler_options,const char * method_name)184*795d594fSAndroid Build Coastguard Worker   static bool IsVerboseMethod(const CompilerOptions& compiler_options, const char* method_name) {
185*795d594fSAndroid Build Coastguard Worker     // Test an exact match to --verbose-methods. If verbose-methods is set, this overrides an
186*795d594fSAndroid Build Coastguard Worker     // empty kStringFilter matching all methods.
187*795d594fSAndroid Build Coastguard Worker     if (compiler_options.HasVerboseMethods()) {
188*795d594fSAndroid Build Coastguard Worker       return compiler_options.IsVerboseMethod(method_name);
189*795d594fSAndroid Build Coastguard Worker     }
190*795d594fSAndroid Build Coastguard Worker 
191*795d594fSAndroid Build Coastguard Worker     // Test the kStringFilter sub-string. constexpr helper variable to silence unreachable-code
192*795d594fSAndroid Build Coastguard Worker     // warning when the string is empty.
193*795d594fSAndroid Build Coastguard Worker     constexpr bool kStringFilterEmpty = arraysize(kStringFilter) <= 1;
194*795d594fSAndroid Build Coastguard Worker     if (kStringFilterEmpty || strstr(method_name, kStringFilter) != nullptr) {
195*795d594fSAndroid Build Coastguard Worker       return true;
196*795d594fSAndroid Build Coastguard Worker     }
197*795d594fSAndroid Build Coastguard Worker 
198*795d594fSAndroid Build Coastguard Worker     return false;
199*795d594fSAndroid Build Coastguard Worker   }
200*795d594fSAndroid Build Coastguard Worker 
201*795d594fSAndroid Build Coastguard Worker   HGraph* const graph_;
202*795d594fSAndroid Build Coastguard Worker   size_t last_seen_graph_size_;
203*795d594fSAndroid Build Coastguard Worker 
204*795d594fSAndroid Build Coastguard Worker   std::string cached_method_name_;
205*795d594fSAndroid Build Coastguard Worker 
206*795d594fSAndroid Build Coastguard Worker   bool timing_logger_enabled_;
207*795d594fSAndroid Build Coastguard Worker   TimingLogger timing_logger_;
208*795d594fSAndroid Build Coastguard Worker 
209*795d594fSAndroid Build Coastguard Worker   DisassemblyInformation disasm_info_;
210*795d594fSAndroid Build Coastguard Worker 
211*795d594fSAndroid Build Coastguard Worker   std::ostringstream visualizer_oss_;
212*795d594fSAndroid Build Coastguard Worker   std::ostream* visualizer_output_;
213*795d594fSAndroid Build Coastguard Worker   bool visualizer_enabled_;
214*795d594fSAndroid Build Coastguard Worker   HGraphVisualizer visualizer_;
215*795d594fSAndroid Build Coastguard Worker   CodeGenerator* codegen_;
216*795d594fSAndroid Build Coastguard Worker 
217*795d594fSAndroid Build Coastguard Worker   // Flag to be set by the compiler if the pass failed and the graph is not
218*795d594fSAndroid Build Coastguard Worker   // expected to validate.
219*795d594fSAndroid Build Coastguard Worker   bool graph_in_bad_state_;
220*795d594fSAndroid Build Coastguard Worker 
221*795d594fSAndroid Build Coastguard Worker   friend PassScope;
222*795d594fSAndroid Build Coastguard Worker 
223*795d594fSAndroid Build Coastguard Worker   DISALLOW_COPY_AND_ASSIGN(PassObserver);
224*795d594fSAndroid Build Coastguard Worker };
225*795d594fSAndroid Build Coastguard Worker 
226*795d594fSAndroid Build Coastguard Worker class PassScope : public ValueObject {
227*795d594fSAndroid Build Coastguard Worker  public:
PassScope(const char * pass_name,PassObserver * pass_observer)228*795d594fSAndroid Build Coastguard Worker   PassScope(const char *pass_name, PassObserver* pass_observer)
229*795d594fSAndroid Build Coastguard Worker       : pass_name_(pass_name),
230*795d594fSAndroid Build Coastguard Worker         pass_change_(true),  // assume change
231*795d594fSAndroid Build Coastguard Worker         pass_observer_(pass_observer) {
232*795d594fSAndroid Build Coastguard Worker     pass_observer_->StartPass(pass_name_);
233*795d594fSAndroid Build Coastguard Worker   }
234*795d594fSAndroid Build Coastguard Worker 
SetPassNotChanged()235*795d594fSAndroid Build Coastguard Worker   void SetPassNotChanged() {
236*795d594fSAndroid Build Coastguard Worker     pass_change_ = false;
237*795d594fSAndroid Build Coastguard Worker   }
238*795d594fSAndroid Build Coastguard Worker 
~PassScope()239*795d594fSAndroid Build Coastguard Worker   ~PassScope() {
240*795d594fSAndroid Build Coastguard Worker     pass_observer_->EndPass(pass_name_, pass_change_);
241*795d594fSAndroid Build Coastguard Worker   }
242*795d594fSAndroid Build Coastguard Worker 
243*795d594fSAndroid Build Coastguard Worker  private:
244*795d594fSAndroid Build Coastguard Worker   const char* const pass_name_;
245*795d594fSAndroid Build Coastguard Worker   bool pass_change_;
246*795d594fSAndroid Build Coastguard Worker   PassObserver* const pass_observer_;
247*795d594fSAndroid Build Coastguard Worker };
248*795d594fSAndroid Build Coastguard Worker 
249*795d594fSAndroid Build Coastguard Worker class OptimizingCompiler final : public Compiler {
250*795d594fSAndroid Build Coastguard Worker  public:
251*795d594fSAndroid Build Coastguard Worker   explicit OptimizingCompiler(const CompilerOptions& compiler_options,
252*795d594fSAndroid Build Coastguard Worker                               CompiledCodeStorage* storage);
253*795d594fSAndroid Build Coastguard Worker   ~OptimizingCompiler() override;
254*795d594fSAndroid Build Coastguard Worker 
255*795d594fSAndroid Build Coastguard Worker   bool CanCompileMethod(uint32_t method_idx, const DexFile& dex_file) const override;
256*795d594fSAndroid Build Coastguard Worker 
257*795d594fSAndroid Build Coastguard Worker   CompiledMethod* Compile(const dex::CodeItem* code_item,
258*795d594fSAndroid Build Coastguard Worker                           uint32_t access_flags,
259*795d594fSAndroid Build Coastguard Worker                           uint16_t class_def_idx,
260*795d594fSAndroid Build Coastguard Worker                           uint32_t method_idx,
261*795d594fSAndroid Build Coastguard Worker                           Handle<mirror::ClassLoader> class_loader,
262*795d594fSAndroid Build Coastguard Worker                           const DexFile& dex_file,
263*795d594fSAndroid Build Coastguard Worker                           Handle<mirror::DexCache> dex_cache) const override;
264*795d594fSAndroid Build Coastguard Worker 
265*795d594fSAndroid Build Coastguard Worker   CompiledMethod* JniCompile(uint32_t access_flags,
266*795d594fSAndroid Build Coastguard Worker                              uint32_t method_idx,
267*795d594fSAndroid Build Coastguard Worker                              const DexFile& dex_file,
268*795d594fSAndroid Build Coastguard Worker                              Handle<mirror::DexCache> dex_cache) const override;
269*795d594fSAndroid Build Coastguard Worker 
GetEntryPointOf(ArtMethod * method) const270*795d594fSAndroid Build Coastguard Worker   uintptr_t GetEntryPointOf(ArtMethod* method) const override
271*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
272*795d594fSAndroid Build Coastguard Worker     return reinterpret_cast<uintptr_t>(method->GetEntryPointFromQuickCompiledCodePtrSize(
273*795d594fSAndroid Build Coastguard Worker         InstructionSetPointerSize(GetCompilerOptions().GetInstructionSet())));
274*795d594fSAndroid Build Coastguard Worker   }
275*795d594fSAndroid Build Coastguard Worker 
276*795d594fSAndroid Build Coastguard Worker   bool JitCompile(Thread* self,
277*795d594fSAndroid Build Coastguard Worker                   jit::JitCodeCache* code_cache,
278*795d594fSAndroid Build Coastguard Worker                   jit::JitMemoryRegion* region,
279*795d594fSAndroid Build Coastguard Worker                   ArtMethod* method,
280*795d594fSAndroid Build Coastguard Worker                   CompilationKind compilation_kind,
281*795d594fSAndroid Build Coastguard Worker                   jit::JitLogger* jit_logger)
282*795d594fSAndroid Build Coastguard Worker       override
283*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_);
284*795d594fSAndroid Build Coastguard Worker 
285*795d594fSAndroid Build Coastguard Worker  private:
RunOptimizations(HGraph * graph,CodeGenerator * codegen,const DexCompilationUnit & dex_compilation_unit,PassObserver * pass_observer,const OptimizationDef definitions[],size_t length) const286*795d594fSAndroid Build Coastguard Worker   bool RunOptimizations(HGraph* graph,
287*795d594fSAndroid Build Coastguard Worker                         CodeGenerator* codegen,
288*795d594fSAndroid Build Coastguard Worker                         const DexCompilationUnit& dex_compilation_unit,
289*795d594fSAndroid Build Coastguard Worker                         PassObserver* pass_observer,
290*795d594fSAndroid Build Coastguard Worker                         const OptimizationDef definitions[],
291*795d594fSAndroid Build Coastguard Worker                         size_t length) const {
292*795d594fSAndroid Build Coastguard Worker     // Convert definitions to optimization passes.
293*795d594fSAndroid Build Coastguard Worker     ArenaVector<HOptimization*> optimizations = ConstructOptimizations(
294*795d594fSAndroid Build Coastguard Worker         definitions,
295*795d594fSAndroid Build Coastguard Worker         length,
296*795d594fSAndroid Build Coastguard Worker         graph->GetAllocator(),
297*795d594fSAndroid Build Coastguard Worker         graph,
298*795d594fSAndroid Build Coastguard Worker         compilation_stats_.get(),
299*795d594fSAndroid Build Coastguard Worker         codegen,
300*795d594fSAndroid Build Coastguard Worker         dex_compilation_unit);
301*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(length, optimizations.size());
302*795d594fSAndroid Build Coastguard Worker     // Run the optimization passes one by one. Any "depends_on" pass refers back to
303*795d594fSAndroid Build Coastguard Worker     // the most recent occurrence of that pass, skipped or executed.
304*795d594fSAndroid Build Coastguard Worker     std::bitset<static_cast<size_t>(OptimizationPass::kLast) + 1u> pass_changes;
305*795d594fSAndroid Build Coastguard Worker     pass_changes[static_cast<size_t>(OptimizationPass::kNone)] = true;
306*795d594fSAndroid Build Coastguard Worker     bool change = false;
307*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0; i < length; ++i) {
308*795d594fSAndroid Build Coastguard Worker       if (pass_changes[static_cast<size_t>(definitions[i].depends_on)]) {
309*795d594fSAndroid Build Coastguard Worker         // Execute the pass and record whether it changed anything.
310*795d594fSAndroid Build Coastguard Worker         PassScope scope(optimizations[i]->GetPassName(), pass_observer);
311*795d594fSAndroid Build Coastguard Worker         bool pass_change = optimizations[i]->Run();
312*795d594fSAndroid Build Coastguard Worker         pass_changes[static_cast<size_t>(definitions[i].pass)] = pass_change;
313*795d594fSAndroid Build Coastguard Worker         if (pass_change) {
314*795d594fSAndroid Build Coastguard Worker           change = true;
315*795d594fSAndroid Build Coastguard Worker         } else {
316*795d594fSAndroid Build Coastguard Worker           scope.SetPassNotChanged();
317*795d594fSAndroid Build Coastguard Worker         }
318*795d594fSAndroid Build Coastguard Worker       } else {
319*795d594fSAndroid Build Coastguard Worker         // Skip the pass and record that nothing changed.
320*795d594fSAndroid Build Coastguard Worker         pass_changes[static_cast<size_t>(definitions[i].pass)] = false;
321*795d594fSAndroid Build Coastguard Worker       }
322*795d594fSAndroid Build Coastguard Worker     }
323*795d594fSAndroid Build Coastguard Worker     return change;
324*795d594fSAndroid Build Coastguard Worker   }
325*795d594fSAndroid Build Coastguard Worker 
RunOptimizations(HGraph * graph,CodeGenerator * codegen,const DexCompilationUnit & dex_compilation_unit,PassObserver * pass_observer,const OptimizationDef (& definitions)[length]) const326*795d594fSAndroid Build Coastguard Worker   template <size_t length> bool RunOptimizations(
327*795d594fSAndroid Build Coastguard Worker       HGraph* graph,
328*795d594fSAndroid Build Coastguard Worker       CodeGenerator* codegen,
329*795d594fSAndroid Build Coastguard Worker       const DexCompilationUnit& dex_compilation_unit,
330*795d594fSAndroid Build Coastguard Worker       PassObserver* pass_observer,
331*795d594fSAndroid Build Coastguard Worker       const OptimizationDef (&definitions)[length]) const {
332*795d594fSAndroid Build Coastguard Worker     return RunOptimizations(
333*795d594fSAndroid Build Coastguard Worker         graph, codegen, dex_compilation_unit, pass_observer, definitions, length);
334*795d594fSAndroid Build Coastguard Worker   }
335*795d594fSAndroid Build Coastguard Worker 
336*795d594fSAndroid Build Coastguard Worker   void RunOptimizations(HGraph* graph,
337*795d594fSAndroid Build Coastguard Worker                         CodeGenerator* codegen,
338*795d594fSAndroid Build Coastguard Worker                         const DexCompilationUnit& dex_compilation_unit,
339*795d594fSAndroid Build Coastguard Worker                         PassObserver* pass_observer) const;
340*795d594fSAndroid Build Coastguard Worker 
341*795d594fSAndroid Build Coastguard Worker   // Create a 'CompiledMethod' for an optimized graph.
342*795d594fSAndroid Build Coastguard Worker   CompiledMethod* Emit(ArenaAllocator* allocator,
343*795d594fSAndroid Build Coastguard Worker                        CodeGenerator* codegen,
344*795d594fSAndroid Build Coastguard Worker                        bool is_intrinsic,
345*795d594fSAndroid Build Coastguard Worker                        const dex::CodeItem* item) const;
346*795d594fSAndroid Build Coastguard Worker 
347*795d594fSAndroid Build Coastguard Worker   // Try compiling a method and return the code generator used for
348*795d594fSAndroid Build Coastguard Worker   // compiling it.
349*795d594fSAndroid Build Coastguard Worker   // This method:
350*795d594fSAndroid Build Coastguard Worker   // 1) Builds the graph. Returns null if it failed to build it.
351*795d594fSAndroid Build Coastguard Worker   // 2) Transforms the graph to SSA. Returns null if it failed.
352*795d594fSAndroid Build Coastguard Worker   // 3) Runs optimizations on the graph, including register allocator.
353*795d594fSAndroid Build Coastguard Worker   CodeGenerator* TryCompile(ArenaAllocator* allocator,
354*795d594fSAndroid Build Coastguard Worker                             ArenaStack* arena_stack,
355*795d594fSAndroid Build Coastguard Worker                             const DexCompilationUnit& dex_compilation_unit,
356*795d594fSAndroid Build Coastguard Worker                             ArtMethod* method,
357*795d594fSAndroid Build Coastguard Worker                             CompilationKind compilation_kind,
358*795d594fSAndroid Build Coastguard Worker                             VariableSizedHandleScope* handles) const;
359*795d594fSAndroid Build Coastguard Worker 
360*795d594fSAndroid Build Coastguard Worker   CodeGenerator* TryCompileIntrinsic(ArenaAllocator* allocator,
361*795d594fSAndroid Build Coastguard Worker                                      ArenaStack* arena_stack,
362*795d594fSAndroid Build Coastguard Worker                                      const DexCompilationUnit& dex_compilation_unit,
363*795d594fSAndroid Build Coastguard Worker                                      ArtMethod* method,
364*795d594fSAndroid Build Coastguard Worker                                      VariableSizedHandleScope* handles) const;
365*795d594fSAndroid Build Coastguard Worker 
366*795d594fSAndroid Build Coastguard Worker   bool RunArchOptimizations(HGraph* graph,
367*795d594fSAndroid Build Coastguard Worker                             CodeGenerator* codegen,
368*795d594fSAndroid Build Coastguard Worker                             const DexCompilationUnit& dex_compilation_unit,
369*795d594fSAndroid Build Coastguard Worker                             PassObserver* pass_observer) const;
370*795d594fSAndroid Build Coastguard Worker 
371*795d594fSAndroid Build Coastguard Worker   bool RunRequiredPasses(HGraph* graph,
372*795d594fSAndroid Build Coastguard Worker                          CodeGenerator* codegen,
373*795d594fSAndroid Build Coastguard Worker                          const DexCompilationUnit& dex_compilation_unit,
374*795d594fSAndroid Build Coastguard Worker                          PassObserver* pass_observer) const;
375*795d594fSAndroid Build Coastguard Worker 
376*795d594fSAndroid Build Coastguard Worker   std::vector<uint8_t> GenerateJitDebugInfo(const debug::MethodDebugInfo& method_debug_info);
377*795d594fSAndroid Build Coastguard Worker 
378*795d594fSAndroid Build Coastguard Worker   // This must be called before any other function that dumps data to the cfg
379*795d594fSAndroid Build Coastguard Worker   void DumpInstructionSetFeaturesToCfg() const;
380*795d594fSAndroid Build Coastguard Worker 
381*795d594fSAndroid Build Coastguard Worker   std::unique_ptr<OptimizingCompilerStats> compilation_stats_;
382*795d594fSAndroid Build Coastguard Worker 
383*795d594fSAndroid Build Coastguard Worker   std::unique_ptr<std::ostream> visualizer_output_;
384*795d594fSAndroid Build Coastguard Worker 
385*795d594fSAndroid Build Coastguard Worker   DISALLOW_COPY_AND_ASSIGN(OptimizingCompiler);
386*795d594fSAndroid Build Coastguard Worker };
387*795d594fSAndroid Build Coastguard Worker 
388*795d594fSAndroid Build Coastguard Worker static const int kMaximumCompilationTimeBeforeWarning = 100; /* ms */
389*795d594fSAndroid Build Coastguard Worker 
OptimizingCompiler(const CompilerOptions & compiler_options,CompiledCodeStorage * storage)390*795d594fSAndroid Build Coastguard Worker OptimizingCompiler::OptimizingCompiler(const CompilerOptions& compiler_options,
391*795d594fSAndroid Build Coastguard Worker                                        CompiledCodeStorage* storage)
392*795d594fSAndroid Build Coastguard Worker     : Compiler(compiler_options, storage, kMaximumCompilationTimeBeforeWarning) {
393*795d594fSAndroid Build Coastguard Worker   // Enable C1visualizer output.
394*795d594fSAndroid Build Coastguard Worker   const std::string& cfg_file_name = compiler_options.GetDumpCfgFileName();
395*795d594fSAndroid Build Coastguard Worker   if (!cfg_file_name.empty()) {
396*795d594fSAndroid Build Coastguard Worker     std::ios_base::openmode cfg_file_mode =
397*795d594fSAndroid Build Coastguard Worker         compiler_options.GetDumpCfgAppend() ? std::ofstream::app : std::ofstream::out;
398*795d594fSAndroid Build Coastguard Worker     visualizer_output_.reset(new std::ofstream(cfg_file_name, cfg_file_mode));
399*795d594fSAndroid Build Coastguard Worker     DumpInstructionSetFeaturesToCfg();
400*795d594fSAndroid Build Coastguard Worker   }
401*795d594fSAndroid Build Coastguard Worker   if (compiler_options.GetDumpStats()) {
402*795d594fSAndroid Build Coastguard Worker     compilation_stats_.reset(new OptimizingCompilerStats());
403*795d594fSAndroid Build Coastguard Worker   }
404*795d594fSAndroid Build Coastguard Worker }
405*795d594fSAndroid Build Coastguard Worker 
~OptimizingCompiler()406*795d594fSAndroid Build Coastguard Worker OptimizingCompiler::~OptimizingCompiler() {
407*795d594fSAndroid Build Coastguard Worker   if (compilation_stats_.get() != nullptr) {
408*795d594fSAndroid Build Coastguard Worker     compilation_stats_->Log();
409*795d594fSAndroid Build Coastguard Worker   }
410*795d594fSAndroid Build Coastguard Worker }
411*795d594fSAndroid Build Coastguard Worker 
DumpInstructionSetFeaturesToCfg() const412*795d594fSAndroid Build Coastguard Worker void OptimizingCompiler::DumpInstructionSetFeaturesToCfg() const {
413*795d594fSAndroid Build Coastguard Worker   const CompilerOptions& compiler_options = GetCompilerOptions();
414*795d594fSAndroid Build Coastguard Worker   const InstructionSetFeatures* features = compiler_options.GetInstructionSetFeatures();
415*795d594fSAndroid Build Coastguard Worker   std::string isa_string =
416*795d594fSAndroid Build Coastguard Worker       std::string("isa:") + GetInstructionSetString(features->GetInstructionSet());
417*795d594fSAndroid Build Coastguard Worker   std::string features_string = "isa_features:" + features->GetFeatureString();
418*795d594fSAndroid Build Coastguard Worker   std::string read_barrier_type = "none";
419*795d594fSAndroid Build Coastguard Worker   if (compiler_options.EmitReadBarrier()) {
420*795d594fSAndroid Build Coastguard Worker     if (art::kUseBakerReadBarrier)
421*795d594fSAndroid Build Coastguard Worker       read_barrier_type = "baker";
422*795d594fSAndroid Build Coastguard Worker     else if (art::kUseTableLookupReadBarrier)
423*795d594fSAndroid Build Coastguard Worker       read_barrier_type = "tablelookup";
424*795d594fSAndroid Build Coastguard Worker   }
425*795d594fSAndroid Build Coastguard Worker   std::string read_barrier_string = ART_FORMAT("read_barrier_type:{}", read_barrier_type);
426*795d594fSAndroid Build Coastguard Worker   // It is assumed that visualizer_output_ is empty when calling this function, hence the fake
427*795d594fSAndroid Build Coastguard Worker   // compilation block containing the ISA features will be printed at the beginning of the .cfg
428*795d594fSAndroid Build Coastguard Worker   // file.
429*795d594fSAndroid Build Coastguard Worker   *visualizer_output_ << HGraphVisualizer::InsertMetaDataAsCompilationBlock(
430*795d594fSAndroid Build Coastguard Worker       isa_string + ' ' + features_string + ' ' + read_barrier_string);
431*795d594fSAndroid Build Coastguard Worker }
432*795d594fSAndroid Build Coastguard Worker 
CanCompileMethod(uint32_t method_idx,const DexFile & dex_file) const433*795d594fSAndroid Build Coastguard Worker bool OptimizingCompiler::CanCompileMethod([[maybe_unused]] uint32_t method_idx,
434*795d594fSAndroid Build Coastguard Worker                                           [[maybe_unused]] const DexFile& dex_file) const {
435*795d594fSAndroid Build Coastguard Worker   return true;
436*795d594fSAndroid Build Coastguard Worker }
437*795d594fSAndroid Build Coastguard Worker 
IsInstructionSetSupported(InstructionSet instruction_set)438*795d594fSAndroid Build Coastguard Worker static bool IsInstructionSetSupported(InstructionSet instruction_set) {
439*795d594fSAndroid Build Coastguard Worker   return instruction_set == InstructionSet::kArm ||
440*795d594fSAndroid Build Coastguard Worker          instruction_set == InstructionSet::kArm64 ||
441*795d594fSAndroid Build Coastguard Worker          instruction_set == InstructionSet::kThumb2 ||
442*795d594fSAndroid Build Coastguard Worker          instruction_set == InstructionSet::kRiscv64 ||
443*795d594fSAndroid Build Coastguard Worker          instruction_set == InstructionSet::kX86 ||
444*795d594fSAndroid Build Coastguard Worker          instruction_set == InstructionSet::kX86_64;
445*795d594fSAndroid Build Coastguard Worker }
446*795d594fSAndroid Build Coastguard Worker 
RunRequiredPasses(HGraph * graph,CodeGenerator * codegen,const DexCompilationUnit & dex_compilation_unit,PassObserver * pass_observer) const447*795d594fSAndroid Build Coastguard Worker bool OptimizingCompiler::RunRequiredPasses(HGraph* graph,
448*795d594fSAndroid Build Coastguard Worker                                            CodeGenerator* codegen,
449*795d594fSAndroid Build Coastguard Worker                                            const DexCompilationUnit& dex_compilation_unit,
450*795d594fSAndroid Build Coastguard Worker                                            PassObserver* pass_observer) const {
451*795d594fSAndroid Build Coastguard Worker   switch (codegen->GetCompilerOptions().GetInstructionSet()) {
452*795d594fSAndroid Build Coastguard Worker #if defined(ART_ENABLE_CODEGEN_arm)
453*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kThumb2:
454*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kArm: {
455*795d594fSAndroid Build Coastguard Worker       OptimizationDef arm_optimizations[] = {
456*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kCriticalNativeAbiFixupArm),
457*795d594fSAndroid Build Coastguard Worker       };
458*795d594fSAndroid Build Coastguard Worker       return RunOptimizations(graph,
459*795d594fSAndroid Build Coastguard Worker                               codegen,
460*795d594fSAndroid Build Coastguard Worker                               dex_compilation_unit,
461*795d594fSAndroid Build Coastguard Worker                               pass_observer,
462*795d594fSAndroid Build Coastguard Worker                               arm_optimizations);
463*795d594fSAndroid Build Coastguard Worker     }
464*795d594fSAndroid Build Coastguard Worker #endif
465*795d594fSAndroid Build Coastguard Worker #if defined(ART_ENABLE_CODEGEN_riscv64)
466*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kRiscv64: {
467*795d594fSAndroid Build Coastguard Worker       OptimizationDef riscv64_optimizations[] = {
468*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kCriticalNativeAbiFixupRiscv64),
469*795d594fSAndroid Build Coastguard Worker       };
470*795d594fSAndroid Build Coastguard Worker       return RunOptimizations(graph,
471*795d594fSAndroid Build Coastguard Worker                               codegen,
472*795d594fSAndroid Build Coastguard Worker                               dex_compilation_unit,
473*795d594fSAndroid Build Coastguard Worker                               pass_observer,
474*795d594fSAndroid Build Coastguard Worker                               riscv64_optimizations);
475*795d594fSAndroid Build Coastguard Worker     }
476*795d594fSAndroid Build Coastguard Worker #endif
477*795d594fSAndroid Build Coastguard Worker #ifdef ART_ENABLE_CODEGEN_x86
478*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kX86: {
479*795d594fSAndroid Build Coastguard Worker       OptimizationDef x86_optimizations[] = {
480*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kPcRelativeFixupsX86),
481*795d594fSAndroid Build Coastguard Worker       };
482*795d594fSAndroid Build Coastguard Worker       return RunOptimizations(graph,
483*795d594fSAndroid Build Coastguard Worker                               codegen,
484*795d594fSAndroid Build Coastguard Worker                               dex_compilation_unit,
485*795d594fSAndroid Build Coastguard Worker                               pass_observer,
486*795d594fSAndroid Build Coastguard Worker                               x86_optimizations);
487*795d594fSAndroid Build Coastguard Worker     }
488*795d594fSAndroid Build Coastguard Worker #endif
489*795d594fSAndroid Build Coastguard Worker     default:
490*795d594fSAndroid Build Coastguard Worker       UNUSED(graph);
491*795d594fSAndroid Build Coastguard Worker       UNUSED(codegen);
492*795d594fSAndroid Build Coastguard Worker       UNUSED(dex_compilation_unit);
493*795d594fSAndroid Build Coastguard Worker       UNUSED(pass_observer);
494*795d594fSAndroid Build Coastguard Worker       return false;
495*795d594fSAndroid Build Coastguard Worker   }
496*795d594fSAndroid Build Coastguard Worker }
497*795d594fSAndroid Build Coastguard Worker 
RunArchOptimizations(HGraph * graph,CodeGenerator * codegen,const DexCompilationUnit & dex_compilation_unit,PassObserver * pass_observer) const498*795d594fSAndroid Build Coastguard Worker bool OptimizingCompiler::RunArchOptimizations(HGraph* graph,
499*795d594fSAndroid Build Coastguard Worker                                               CodeGenerator* codegen,
500*795d594fSAndroid Build Coastguard Worker                                               const DexCompilationUnit& dex_compilation_unit,
501*795d594fSAndroid Build Coastguard Worker                                               PassObserver* pass_observer) const {
502*795d594fSAndroid Build Coastguard Worker   switch (codegen->GetCompilerOptions().GetInstructionSet()) {
503*795d594fSAndroid Build Coastguard Worker #if defined(ART_ENABLE_CODEGEN_arm)
504*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kThumb2:
505*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kArm: {
506*795d594fSAndroid Build Coastguard Worker       OptimizationDef arm_optimizations[] = {
507*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kInstructionSimplifierArm),
508*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kSideEffectsAnalysis),
509*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
510*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kCriticalNativeAbiFixupArm),
511*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kScheduling)
512*795d594fSAndroid Build Coastguard Worker       };
513*795d594fSAndroid Build Coastguard Worker       return RunOptimizations(graph,
514*795d594fSAndroid Build Coastguard Worker                               codegen,
515*795d594fSAndroid Build Coastguard Worker                               dex_compilation_unit,
516*795d594fSAndroid Build Coastguard Worker                               pass_observer,
517*795d594fSAndroid Build Coastguard Worker                               arm_optimizations);
518*795d594fSAndroid Build Coastguard Worker     }
519*795d594fSAndroid Build Coastguard Worker #endif
520*795d594fSAndroid Build Coastguard Worker #ifdef ART_ENABLE_CODEGEN_arm64
521*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kArm64: {
522*795d594fSAndroid Build Coastguard Worker       OptimizationDef arm64_optimizations[] = {
523*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kInstructionSimplifierArm64),
524*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kSideEffectsAnalysis),
525*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
526*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kScheduling)
527*795d594fSAndroid Build Coastguard Worker       };
528*795d594fSAndroid Build Coastguard Worker       return RunOptimizations(graph,
529*795d594fSAndroid Build Coastguard Worker                               codegen,
530*795d594fSAndroid Build Coastguard Worker                               dex_compilation_unit,
531*795d594fSAndroid Build Coastguard Worker                               pass_observer,
532*795d594fSAndroid Build Coastguard Worker                               arm64_optimizations);
533*795d594fSAndroid Build Coastguard Worker     }
534*795d594fSAndroid Build Coastguard Worker #endif
535*795d594fSAndroid Build Coastguard Worker #if defined(ART_ENABLE_CODEGEN_riscv64)
536*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kRiscv64: {
537*795d594fSAndroid Build Coastguard Worker       OptimizationDef riscv64_optimizations[] = {
538*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kInstructionSimplifierRiscv64),
539*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kSideEffectsAnalysis),
540*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
541*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kCriticalNativeAbiFixupRiscv64)
542*795d594fSAndroid Build Coastguard Worker       };
543*795d594fSAndroid Build Coastguard Worker       return RunOptimizations(graph,
544*795d594fSAndroid Build Coastguard Worker                               codegen,
545*795d594fSAndroid Build Coastguard Worker                               dex_compilation_unit,
546*795d594fSAndroid Build Coastguard Worker                               pass_observer,
547*795d594fSAndroid Build Coastguard Worker                               riscv64_optimizations);
548*795d594fSAndroid Build Coastguard Worker     }
549*795d594fSAndroid Build Coastguard Worker #endif
550*795d594fSAndroid Build Coastguard Worker #ifdef ART_ENABLE_CODEGEN_x86
551*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kX86: {
552*795d594fSAndroid Build Coastguard Worker       OptimizationDef x86_optimizations[] = {
553*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kInstructionSimplifierX86),
554*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kSideEffectsAnalysis),
555*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
556*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kPcRelativeFixupsX86),
557*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kX86MemoryOperandGeneration)
558*795d594fSAndroid Build Coastguard Worker       };
559*795d594fSAndroid Build Coastguard Worker       return RunOptimizations(graph,
560*795d594fSAndroid Build Coastguard Worker                               codegen,
561*795d594fSAndroid Build Coastguard Worker                               dex_compilation_unit,
562*795d594fSAndroid Build Coastguard Worker                               pass_observer,
563*795d594fSAndroid Build Coastguard Worker                               x86_optimizations);
564*795d594fSAndroid Build Coastguard Worker     }
565*795d594fSAndroid Build Coastguard Worker #endif
566*795d594fSAndroid Build Coastguard Worker #ifdef ART_ENABLE_CODEGEN_x86_64
567*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kX86_64: {
568*795d594fSAndroid Build Coastguard Worker       OptimizationDef x86_64_optimizations[] = {
569*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kInstructionSimplifierX86_64),
570*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kSideEffectsAnalysis),
571*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kGlobalValueNumbering, "GVN$after_arch"),
572*795d594fSAndroid Build Coastguard Worker           OptDef(OptimizationPass::kX86MemoryOperandGeneration)
573*795d594fSAndroid Build Coastguard Worker       };
574*795d594fSAndroid Build Coastguard Worker       return RunOptimizations(graph,
575*795d594fSAndroid Build Coastguard Worker                               codegen,
576*795d594fSAndroid Build Coastguard Worker                               dex_compilation_unit,
577*795d594fSAndroid Build Coastguard Worker                               pass_observer,
578*795d594fSAndroid Build Coastguard Worker                               x86_64_optimizations);
579*795d594fSAndroid Build Coastguard Worker     }
580*795d594fSAndroid Build Coastguard Worker #endif
581*795d594fSAndroid Build Coastguard Worker     default:
582*795d594fSAndroid Build Coastguard Worker       UNUSED(graph);
583*795d594fSAndroid Build Coastguard Worker       UNUSED(dex_compilation_unit);
584*795d594fSAndroid Build Coastguard Worker       UNUSED(pass_observer);
585*795d594fSAndroid Build Coastguard Worker       return false;
586*795d594fSAndroid Build Coastguard Worker   }
587*795d594fSAndroid Build Coastguard Worker }
588*795d594fSAndroid Build Coastguard Worker 
589*795d594fSAndroid Build Coastguard Worker NO_INLINE  // Avoid increasing caller's frame size by large stack-allocated objects.
AllocateRegisters(HGraph * graph,CodeGenerator * codegen,PassObserver * pass_observer,OptimizingCompilerStats * stats)590*795d594fSAndroid Build Coastguard Worker static void AllocateRegisters(HGraph* graph,
591*795d594fSAndroid Build Coastguard Worker                               CodeGenerator* codegen,
592*795d594fSAndroid Build Coastguard Worker                               PassObserver* pass_observer,
593*795d594fSAndroid Build Coastguard Worker                               OptimizingCompilerStats* stats) {
594*795d594fSAndroid Build Coastguard Worker   {
595*795d594fSAndroid Build Coastguard Worker     PassScope scope(PrepareForRegisterAllocation::kPrepareForRegisterAllocationPassName,
596*795d594fSAndroid Build Coastguard Worker                     pass_observer);
597*795d594fSAndroid Build Coastguard Worker     PrepareForRegisterAllocation(graph, codegen->GetCompilerOptions(), stats).Run();
598*795d594fSAndroid Build Coastguard Worker   }
599*795d594fSAndroid Build Coastguard Worker   // Use local allocator shared by SSA liveness analysis and register allocator.
600*795d594fSAndroid Build Coastguard Worker   // (Register allocator creates new objects in the liveness data.)
601*795d594fSAndroid Build Coastguard Worker   ScopedArenaAllocator local_allocator(graph->GetArenaStack());
602*795d594fSAndroid Build Coastguard Worker   SsaLivenessAnalysis liveness(graph, codegen, &local_allocator);
603*795d594fSAndroid Build Coastguard Worker   {
604*795d594fSAndroid Build Coastguard Worker     PassScope scope(SsaLivenessAnalysis::kLivenessPassName, pass_observer);
605*795d594fSAndroid Build Coastguard Worker     liveness.Analyze();
606*795d594fSAndroid Build Coastguard Worker   }
607*795d594fSAndroid Build Coastguard Worker   {
608*795d594fSAndroid Build Coastguard Worker     PassScope scope(RegisterAllocator::kRegisterAllocatorPassName, pass_observer);
609*795d594fSAndroid Build Coastguard Worker     std::unique_ptr<RegisterAllocator> register_allocator =
610*795d594fSAndroid Build Coastguard Worker         RegisterAllocator::Create(&local_allocator, codegen, liveness);
611*795d594fSAndroid Build Coastguard Worker     register_allocator->AllocateRegisters();
612*795d594fSAndroid Build Coastguard Worker   }
613*795d594fSAndroid Build Coastguard Worker }
614*795d594fSAndroid Build Coastguard Worker 
615*795d594fSAndroid Build Coastguard Worker // Strip pass name suffix to get optimization name.
ConvertPassNameToOptimizationName(const std::string & pass_name)616*795d594fSAndroid Build Coastguard Worker static std::string ConvertPassNameToOptimizationName(const std::string& pass_name) {
617*795d594fSAndroid Build Coastguard Worker   size_t pos = pass_name.find(kPassNameSeparator);
618*795d594fSAndroid Build Coastguard Worker   return pos == std::string::npos ? pass_name : pass_name.substr(0, pos);
619*795d594fSAndroid Build Coastguard Worker }
620*795d594fSAndroid Build Coastguard Worker 
RunOptimizations(HGraph * graph,CodeGenerator * codegen,const DexCompilationUnit & dex_compilation_unit,PassObserver * pass_observer) const621*795d594fSAndroid Build Coastguard Worker void OptimizingCompiler::RunOptimizations(HGraph* graph,
622*795d594fSAndroid Build Coastguard Worker                                           CodeGenerator* codegen,
623*795d594fSAndroid Build Coastguard Worker                                           const DexCompilationUnit& dex_compilation_unit,
624*795d594fSAndroid Build Coastguard Worker                                           PassObserver* pass_observer) const {
625*795d594fSAndroid Build Coastguard Worker   const std::vector<std::string>* pass_names = GetCompilerOptions().GetPassesToRun();
626*795d594fSAndroid Build Coastguard Worker   if (pass_names != nullptr) {
627*795d594fSAndroid Build Coastguard Worker     // If passes were defined on command-line, build the optimization
628*795d594fSAndroid Build Coastguard Worker     // passes and run these instead of the built-in optimizations.
629*795d594fSAndroid Build Coastguard Worker     // TODO: a way to define depends_on via command-line?
630*795d594fSAndroid Build Coastguard Worker     const size_t length = pass_names->size();
631*795d594fSAndroid Build Coastguard Worker     std::vector<OptimizationDef> optimizations;
632*795d594fSAndroid Build Coastguard Worker     for (const std::string& pass_name : *pass_names) {
633*795d594fSAndroid Build Coastguard Worker       std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
634*795d594fSAndroid Build Coastguard Worker       optimizations.push_back(OptDef(OptimizationPassByName(opt_name), pass_name.c_str()));
635*795d594fSAndroid Build Coastguard Worker     }
636*795d594fSAndroid Build Coastguard Worker     RunOptimizations(graph,
637*795d594fSAndroid Build Coastguard Worker                      codegen,
638*795d594fSAndroid Build Coastguard Worker                      dex_compilation_unit,
639*795d594fSAndroid Build Coastguard Worker                      pass_observer,
640*795d594fSAndroid Build Coastguard Worker                      optimizations.data(),
641*795d594fSAndroid Build Coastguard Worker                      length);
642*795d594fSAndroid Build Coastguard Worker     return;
643*795d594fSAndroid Build Coastguard Worker   }
644*795d594fSAndroid Build Coastguard Worker 
645*795d594fSAndroid Build Coastguard Worker   OptimizationDef optimizations[] = {
646*795d594fSAndroid Build Coastguard Worker       // Initial optimizations.
647*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kConstantFolding),
648*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kInstructionSimplifier),
649*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kDeadCodeElimination,
650*795d594fSAndroid Build Coastguard Worker              "dead_code_elimination$initial"),
651*795d594fSAndroid Build Coastguard Worker       // Inlining.
652*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kInliner),
653*795d594fSAndroid Build Coastguard Worker       // Simplification (if inlining occurred, or if we analyzed the invoke as "always throwing").
654*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kConstantFolding,
655*795d594fSAndroid Build Coastguard Worker              "constant_folding$after_inlining",
656*795d594fSAndroid Build Coastguard Worker              OptimizationPass::kInliner),
657*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kInstructionSimplifier,
658*795d594fSAndroid Build Coastguard Worker              "instruction_simplifier$after_inlining",
659*795d594fSAndroid Build Coastguard Worker              OptimizationPass::kInliner),
660*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kDeadCodeElimination,
661*795d594fSAndroid Build Coastguard Worker              "dead_code_elimination$after_inlining",
662*795d594fSAndroid Build Coastguard Worker              OptimizationPass::kInliner),
663*795d594fSAndroid Build Coastguard Worker       // GVN.
664*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kSideEffectsAnalysis,
665*795d594fSAndroid Build Coastguard Worker              "side_effects$before_gvn"),
666*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kGlobalValueNumbering),
667*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kReferenceTypePropagation,
668*795d594fSAndroid Build Coastguard Worker              "reference_type_propagation$after_gvn",
669*795d594fSAndroid Build Coastguard Worker              OptimizationPass::kGlobalValueNumbering),
670*795d594fSAndroid Build Coastguard Worker       // Simplification (TODO: only if GVN occurred).
671*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kSelectGenerator),
672*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kConstantFolding,
673*795d594fSAndroid Build Coastguard Worker              "constant_folding$after_gvn"),
674*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kInstructionSimplifier,
675*795d594fSAndroid Build Coastguard Worker              "instruction_simplifier$after_gvn"),
676*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kDeadCodeElimination,
677*795d594fSAndroid Build Coastguard Worker              "dead_code_elimination$after_gvn"),
678*795d594fSAndroid Build Coastguard Worker       // High-level optimizations.
679*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kSideEffectsAnalysis,
680*795d594fSAndroid Build Coastguard Worker              "side_effects$before_licm"),
681*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kInvariantCodeMotion),
682*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kInductionVarAnalysis),
683*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kBoundsCheckElimination),
684*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kLoopOptimization),
685*795d594fSAndroid Build Coastguard Worker       // Simplification.
686*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kConstantFolding,
687*795d594fSAndroid Build Coastguard Worker              "constant_folding$after_loop_opt"),
688*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kAggressiveInstructionSimplifier,
689*795d594fSAndroid Build Coastguard Worker              "instruction_simplifier$after_loop_opt"),
690*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kDeadCodeElimination,
691*795d594fSAndroid Build Coastguard Worker              "dead_code_elimination$after_loop_opt"),
692*795d594fSAndroid Build Coastguard Worker       // Other high-level optimizations.
693*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kLoadStoreElimination),
694*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kCHAGuardOptimization),
695*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kCodeSinking),
696*795d594fSAndroid Build Coastguard Worker       // Simplification.
697*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kConstantFolding,
698*795d594fSAndroid Build Coastguard Worker              "constant_folding$before_codegen"),
699*795d594fSAndroid Build Coastguard Worker       // The codegen has a few assumptions that only the instruction simplifier
700*795d594fSAndroid Build Coastguard Worker       // can satisfy. For example, the code generator does not expect to see a
701*795d594fSAndroid Build Coastguard Worker       // HTypeConversion from a type to the same type.
702*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kAggressiveInstructionSimplifier,
703*795d594fSAndroid Build Coastguard Worker              "instruction_simplifier$before_codegen"),
704*795d594fSAndroid Build Coastguard Worker       // Simplification may result in dead code that should be removed prior to
705*795d594fSAndroid Build Coastguard Worker       // code generation.
706*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kDeadCodeElimination,
707*795d594fSAndroid Build Coastguard Worker              "dead_code_elimination$before_codegen"),
708*795d594fSAndroid Build Coastguard Worker       // Eliminate constructor fences after code sinking to avoid
709*795d594fSAndroid Build Coastguard Worker       // complicated sinking logic to split a fence with many inputs.
710*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kConstructorFenceRedundancyElimination)
711*795d594fSAndroid Build Coastguard Worker   };
712*795d594fSAndroid Build Coastguard Worker   RunOptimizations(graph,
713*795d594fSAndroid Build Coastguard Worker                    codegen,
714*795d594fSAndroid Build Coastguard Worker                    dex_compilation_unit,
715*795d594fSAndroid Build Coastguard Worker                    pass_observer,
716*795d594fSAndroid Build Coastguard Worker                    optimizations);
717*795d594fSAndroid Build Coastguard Worker 
718*795d594fSAndroid Build Coastguard Worker   RunArchOptimizations(graph, codegen, dex_compilation_unit, pass_observer);
719*795d594fSAndroid Build Coastguard Worker }
720*795d594fSAndroid Build Coastguard Worker 
EmitAndSortLinkerPatches(CodeGenerator * codegen)721*795d594fSAndroid Build Coastguard Worker static ArenaVector<linker::LinkerPatch> EmitAndSortLinkerPatches(CodeGenerator* codegen) {
722*795d594fSAndroid Build Coastguard Worker   ArenaVector<linker::LinkerPatch> linker_patches(codegen->GetGraph()->GetAllocator()->Adapter());
723*795d594fSAndroid Build Coastguard Worker   codegen->EmitLinkerPatches(&linker_patches);
724*795d594fSAndroid Build Coastguard Worker 
725*795d594fSAndroid Build Coastguard Worker   // Sort patches by literal offset. Required for .oat_patches encoding.
726*795d594fSAndroid Build Coastguard Worker   std::sort(linker_patches.begin(), linker_patches.end(),
727*795d594fSAndroid Build Coastguard Worker             [](const linker::LinkerPatch& lhs, const linker::LinkerPatch& rhs) {
728*795d594fSAndroid Build Coastguard Worker     return lhs.LiteralOffset() < rhs.LiteralOffset();
729*795d594fSAndroid Build Coastguard Worker   });
730*795d594fSAndroid Build Coastguard Worker 
731*795d594fSAndroid Build Coastguard Worker   return linker_patches;
732*795d594fSAndroid Build Coastguard Worker }
733*795d594fSAndroid Build Coastguard Worker 
Emit(ArenaAllocator * allocator,CodeGenerator * codegen,bool is_intrinsic,const dex::CodeItem * code_item_for_osr_check) const734*795d594fSAndroid Build Coastguard Worker CompiledMethod* OptimizingCompiler::Emit(ArenaAllocator* allocator,
735*795d594fSAndroid Build Coastguard Worker                                          CodeGenerator* codegen,
736*795d594fSAndroid Build Coastguard Worker                                          bool is_intrinsic,
737*795d594fSAndroid Build Coastguard Worker                                          const dex::CodeItem* code_item_for_osr_check) const {
738*795d594fSAndroid Build Coastguard Worker   ArenaVector<linker::LinkerPatch> linker_patches = EmitAndSortLinkerPatches(codegen);
739*795d594fSAndroid Build Coastguard Worker   ScopedArenaVector<uint8_t> stack_map = codegen->BuildStackMaps(code_item_for_osr_check);
740*795d594fSAndroid Build Coastguard Worker 
741*795d594fSAndroid Build Coastguard Worker   CompiledCodeStorage* storage = GetCompiledCodeStorage();
742*795d594fSAndroid Build Coastguard Worker   CompiledMethod* compiled_method = storage->CreateCompiledMethod(
743*795d594fSAndroid Build Coastguard Worker       codegen->GetInstructionSet(),
744*795d594fSAndroid Build Coastguard Worker       codegen->GetCode(),
745*795d594fSAndroid Build Coastguard Worker       ArrayRef<const uint8_t>(stack_map),
746*795d594fSAndroid Build Coastguard Worker       ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data()),
747*795d594fSAndroid Build Coastguard Worker       ArrayRef<const linker::LinkerPatch>(linker_patches),
748*795d594fSAndroid Build Coastguard Worker       is_intrinsic);
749*795d594fSAndroid Build Coastguard Worker 
750*795d594fSAndroid Build Coastguard Worker   for (const linker::LinkerPatch& patch : linker_patches) {
751*795d594fSAndroid Build Coastguard Worker     if (codegen->NeedsThunkCode(patch) && storage->GetThunkCode(patch).empty()) {
752*795d594fSAndroid Build Coastguard Worker       ArenaVector<uint8_t> code(allocator->Adapter());
753*795d594fSAndroid Build Coastguard Worker       std::string debug_name;
754*795d594fSAndroid Build Coastguard Worker       codegen->EmitThunkCode(patch, &code, &debug_name);
755*795d594fSAndroid Build Coastguard Worker       storage->SetThunkCode(patch, ArrayRef<const uint8_t>(code), debug_name);
756*795d594fSAndroid Build Coastguard Worker     }
757*795d594fSAndroid Build Coastguard Worker   }
758*795d594fSAndroid Build Coastguard Worker 
759*795d594fSAndroid Build Coastguard Worker   return compiled_method;
760*795d594fSAndroid Build Coastguard Worker }
761*795d594fSAndroid Build Coastguard Worker 
TryCompile(ArenaAllocator * allocator,ArenaStack * arena_stack,const DexCompilationUnit & dex_compilation_unit,ArtMethod * method,CompilationKind compilation_kind,VariableSizedHandleScope * handles) const762*795d594fSAndroid Build Coastguard Worker CodeGenerator* OptimizingCompiler::TryCompile(ArenaAllocator* allocator,
763*795d594fSAndroid Build Coastguard Worker                                               ArenaStack* arena_stack,
764*795d594fSAndroid Build Coastguard Worker                                               const DexCompilationUnit& dex_compilation_unit,
765*795d594fSAndroid Build Coastguard Worker                                               ArtMethod* method,
766*795d594fSAndroid Build Coastguard Worker                                               CompilationKind compilation_kind,
767*795d594fSAndroid Build Coastguard Worker                                               VariableSizedHandleScope* handles) const {
768*795d594fSAndroid Build Coastguard Worker   MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kAttemptBytecodeCompilation);
769*795d594fSAndroid Build Coastguard Worker   const CompilerOptions& compiler_options = GetCompilerOptions();
770*795d594fSAndroid Build Coastguard Worker   InstructionSet instruction_set = compiler_options.GetInstructionSet();
771*795d594fSAndroid Build Coastguard Worker   const DexFile& dex_file = *dex_compilation_unit.GetDexFile();
772*795d594fSAndroid Build Coastguard Worker   uint32_t method_idx = dex_compilation_unit.GetDexMethodIndex();
773*795d594fSAndroid Build Coastguard Worker   const dex::CodeItem* code_item = dex_compilation_unit.GetCodeItem();
774*795d594fSAndroid Build Coastguard Worker 
775*795d594fSAndroid Build Coastguard Worker   // Always use the Thumb-2 assembler: some runtime functionality
776*795d594fSAndroid Build Coastguard Worker   // (like implicit stack overflow checks) assume Thumb-2.
777*795d594fSAndroid Build Coastguard Worker   DCHECK_NE(instruction_set, InstructionSet::kArm);
778*795d594fSAndroid Build Coastguard Worker 
779*795d594fSAndroid Build Coastguard Worker   // Do not attempt to compile on architectures we do not support.
780*795d594fSAndroid Build Coastguard Worker   if (!IsInstructionSetSupported(instruction_set)) {
781*795d594fSAndroid Build Coastguard Worker     MaybeRecordStat(compilation_stats_.get(),
782*795d594fSAndroid Build Coastguard Worker                     MethodCompilationStat::kNotCompiledUnsupportedIsa);
783*795d594fSAndroid Build Coastguard Worker     return nullptr;
784*795d594fSAndroid Build Coastguard Worker   }
785*795d594fSAndroid Build Coastguard Worker 
786*795d594fSAndroid Build Coastguard Worker   if (Compiler::IsPathologicalCase(*code_item, method_idx, dex_file)) {
787*795d594fSAndroid Build Coastguard Worker     SCOPED_TRACE << "Not compiling because of pathological case";
788*795d594fSAndroid Build Coastguard Worker     MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledPathological);
789*795d594fSAndroid Build Coastguard Worker     return nullptr;
790*795d594fSAndroid Build Coastguard Worker   }
791*795d594fSAndroid Build Coastguard Worker 
792*795d594fSAndroid Build Coastguard Worker   // Implementation of the space filter: do not compile a code item whose size in
793*795d594fSAndroid Build Coastguard Worker   // code units is bigger than 128.
794*795d594fSAndroid Build Coastguard Worker   static constexpr size_t kSpaceFilterOptimizingThreshold = 128;
795*795d594fSAndroid Build Coastguard Worker   if ((compiler_options.GetCompilerFilter() == CompilerFilter::kSpace)
796*795d594fSAndroid Build Coastguard Worker       && (CodeItemInstructionAccessor(dex_file, code_item).InsnsSizeInCodeUnits() >
797*795d594fSAndroid Build Coastguard Worker           kSpaceFilterOptimizingThreshold)) {
798*795d594fSAndroid Build Coastguard Worker     SCOPED_TRACE << "Not compiling because of space filter";
799*795d594fSAndroid Build Coastguard Worker     MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledSpaceFilter);
800*795d594fSAndroid Build Coastguard Worker     return nullptr;
801*795d594fSAndroid Build Coastguard Worker   }
802*795d594fSAndroid Build Coastguard Worker 
803*795d594fSAndroid Build Coastguard Worker   CodeItemDebugInfoAccessor code_item_accessor(dex_file, code_item, method_idx);
804*795d594fSAndroid Build Coastguard Worker 
805*795d594fSAndroid Build Coastguard Worker   bool dead_reference_safe;
806*795d594fSAndroid Build Coastguard Worker   // For AOT compilation, we may not get a method, for example if its class is erroneous,
807*795d594fSAndroid Build Coastguard Worker   // possibly due to an unavailable superclass.  JIT should always have a method.
808*795d594fSAndroid Build Coastguard Worker   DCHECK(Runtime::Current()->IsAotCompiler() || method != nullptr);
809*795d594fSAndroid Build Coastguard Worker   if (method != nullptr) {
810*795d594fSAndroid Build Coastguard Worker     const dex::ClassDef* containing_class;
811*795d594fSAndroid Build Coastguard Worker     {
812*795d594fSAndroid Build Coastguard Worker       ScopedObjectAccess soa(Thread::Current());
813*795d594fSAndroid Build Coastguard Worker       containing_class = &method->GetClassDef();
814*795d594fSAndroid Build Coastguard Worker     }
815*795d594fSAndroid Build Coastguard Worker     // MethodContainsRSensitiveAccess is currently slow, but HasDeadReferenceSafeAnnotation()
816*795d594fSAndroid Build Coastguard Worker     // is currently rarely true.
817*795d594fSAndroid Build Coastguard Worker     dead_reference_safe =
818*795d594fSAndroid Build Coastguard Worker         annotations::HasDeadReferenceSafeAnnotation(dex_file, *containing_class)
819*795d594fSAndroid Build Coastguard Worker         && !annotations::MethodContainsRSensitiveAccess(dex_file, *containing_class, method_idx);
820*795d594fSAndroid Build Coastguard Worker   } else {
821*795d594fSAndroid Build Coastguard Worker     // If we could not resolve the class, conservatively assume it's dead-reference unsafe.
822*795d594fSAndroid Build Coastguard Worker     dead_reference_safe = false;
823*795d594fSAndroid Build Coastguard Worker   }
824*795d594fSAndroid Build Coastguard Worker 
825*795d594fSAndroid Build Coastguard Worker   HGraph* graph = new (allocator) HGraph(
826*795d594fSAndroid Build Coastguard Worker       allocator,
827*795d594fSAndroid Build Coastguard Worker       arena_stack,
828*795d594fSAndroid Build Coastguard Worker       handles,
829*795d594fSAndroid Build Coastguard Worker       dex_file,
830*795d594fSAndroid Build Coastguard Worker       method_idx,
831*795d594fSAndroid Build Coastguard Worker       compiler_options.GetInstructionSet(),
832*795d594fSAndroid Build Coastguard Worker       kInvalidInvokeType,
833*795d594fSAndroid Build Coastguard Worker       dead_reference_safe,
834*795d594fSAndroid Build Coastguard Worker       compiler_options.GetDebuggable(),
835*795d594fSAndroid Build Coastguard Worker       compilation_kind);
836*795d594fSAndroid Build Coastguard Worker 
837*795d594fSAndroid Build Coastguard Worker   if (method != nullptr) {
838*795d594fSAndroid Build Coastguard Worker     graph->SetArtMethod(method);
839*795d594fSAndroid Build Coastguard Worker   }
840*795d594fSAndroid Build Coastguard Worker 
841*795d594fSAndroid Build Coastguard Worker   jit::Jit* jit = Runtime::Current()->GetJit();
842*795d594fSAndroid Build Coastguard Worker   if (jit != nullptr) {
843*795d594fSAndroid Build Coastguard Worker     ProfilingInfo* info = jit->GetCodeCache()->GetProfilingInfo(method, Thread::Current());
844*795d594fSAndroid Build Coastguard Worker     graph->SetProfilingInfo(info);
845*795d594fSAndroid Build Coastguard Worker   }
846*795d594fSAndroid Build Coastguard Worker 
847*795d594fSAndroid Build Coastguard Worker   std::unique_ptr<CodeGenerator> codegen(
848*795d594fSAndroid Build Coastguard Worker       CodeGenerator::Create(graph,
849*795d594fSAndroid Build Coastguard Worker                             compiler_options,
850*795d594fSAndroid Build Coastguard Worker                             compilation_stats_.get()));
851*795d594fSAndroid Build Coastguard Worker   if (codegen.get() == nullptr) {
852*795d594fSAndroid Build Coastguard Worker     MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledNoCodegen);
853*795d594fSAndroid Build Coastguard Worker     return nullptr;
854*795d594fSAndroid Build Coastguard Worker   }
855*795d594fSAndroid Build Coastguard Worker   codegen->GetAssembler()->cfi().SetEnabled(compiler_options.GenerateAnyDebugInfo());
856*795d594fSAndroid Build Coastguard Worker 
857*795d594fSAndroid Build Coastguard Worker   PassObserver pass_observer(graph,
858*795d594fSAndroid Build Coastguard Worker                              codegen.get(),
859*795d594fSAndroid Build Coastguard Worker                              visualizer_output_.get(),
860*795d594fSAndroid Build Coastguard Worker                              compiler_options);
861*795d594fSAndroid Build Coastguard Worker 
862*795d594fSAndroid Build Coastguard Worker   {
863*795d594fSAndroid Build Coastguard Worker     VLOG(compiler) << "Building " << pass_observer.GetMethodName();
864*795d594fSAndroid Build Coastguard Worker     PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
865*795d594fSAndroid Build Coastguard Worker     HGraphBuilder builder(graph,
866*795d594fSAndroid Build Coastguard Worker                           code_item_accessor,
867*795d594fSAndroid Build Coastguard Worker                           &dex_compilation_unit,
868*795d594fSAndroid Build Coastguard Worker                           &dex_compilation_unit,
869*795d594fSAndroid Build Coastguard Worker                           codegen.get(),
870*795d594fSAndroid Build Coastguard Worker                           compilation_stats_.get());
871*795d594fSAndroid Build Coastguard Worker     GraphAnalysisResult result = builder.BuildGraph();
872*795d594fSAndroid Build Coastguard Worker     if (result != kAnalysisSuccess) {
873*795d594fSAndroid Build Coastguard Worker       // Don't try recompiling this method again.
874*795d594fSAndroid Build Coastguard Worker       if (method != nullptr) {
875*795d594fSAndroid Build Coastguard Worker         ScopedObjectAccess soa(Thread::Current());
876*795d594fSAndroid Build Coastguard Worker         method->SetDontCompile();
877*795d594fSAndroid Build Coastguard Worker       }
878*795d594fSAndroid Build Coastguard Worker       SCOPED_TRACE << "Not compiling because of " << result;
879*795d594fSAndroid Build Coastguard Worker       switch (result) {
880*795d594fSAndroid Build Coastguard Worker         case kAnalysisSkipped: {
881*795d594fSAndroid Build Coastguard Worker           MaybeRecordStat(compilation_stats_.get(),
882*795d594fSAndroid Build Coastguard Worker                           MethodCompilationStat::kNotCompiledSkipped);
883*795d594fSAndroid Build Coastguard Worker           break;
884*795d594fSAndroid Build Coastguard Worker         }
885*795d594fSAndroid Build Coastguard Worker         case kAnalysisInvalidBytecode: {
886*795d594fSAndroid Build Coastguard Worker           MaybeRecordStat(compilation_stats_.get(),
887*795d594fSAndroid Build Coastguard Worker                           MethodCompilationStat::kNotCompiledInvalidBytecode);
888*795d594fSAndroid Build Coastguard Worker           break;
889*795d594fSAndroid Build Coastguard Worker         }
890*795d594fSAndroid Build Coastguard Worker         case kAnalysisFailThrowCatchLoop: {
891*795d594fSAndroid Build Coastguard Worker           MaybeRecordStat(compilation_stats_.get(),
892*795d594fSAndroid Build Coastguard Worker                           MethodCompilationStat::kNotCompiledThrowCatchLoop);
893*795d594fSAndroid Build Coastguard Worker           break;
894*795d594fSAndroid Build Coastguard Worker         }
895*795d594fSAndroid Build Coastguard Worker         case kAnalysisFailAmbiguousArrayOp: {
896*795d594fSAndroid Build Coastguard Worker           MaybeRecordStat(compilation_stats_.get(),
897*795d594fSAndroid Build Coastguard Worker                           MethodCompilationStat::kNotCompiledAmbiguousArrayOp);
898*795d594fSAndroid Build Coastguard Worker           break;
899*795d594fSAndroid Build Coastguard Worker         }
900*795d594fSAndroid Build Coastguard Worker         case kAnalysisFailIrreducibleLoopAndStringInit: {
901*795d594fSAndroid Build Coastguard Worker           MaybeRecordStat(compilation_stats_.get(),
902*795d594fSAndroid Build Coastguard Worker                           MethodCompilationStat::kNotCompiledIrreducibleLoopAndStringInit);
903*795d594fSAndroid Build Coastguard Worker           break;
904*795d594fSAndroid Build Coastguard Worker         }
905*795d594fSAndroid Build Coastguard Worker         case kAnalysisFailPhiEquivalentInOsr: {
906*795d594fSAndroid Build Coastguard Worker           MaybeRecordStat(compilation_stats_.get(),
907*795d594fSAndroid Build Coastguard Worker                           MethodCompilationStat::kNotCompiledPhiEquivalentInOsr);
908*795d594fSAndroid Build Coastguard Worker           break;
909*795d594fSAndroid Build Coastguard Worker         }
910*795d594fSAndroid Build Coastguard Worker         case kAnalysisSuccess:
911*795d594fSAndroid Build Coastguard Worker           LOG(FATAL) << "Unreachable";
912*795d594fSAndroid Build Coastguard Worker           UNREACHABLE();
913*795d594fSAndroid Build Coastguard Worker       }
914*795d594fSAndroid Build Coastguard Worker       pass_observer.SetGraphInBadState();
915*795d594fSAndroid Build Coastguard Worker       return nullptr;
916*795d594fSAndroid Build Coastguard Worker     }
917*795d594fSAndroid Build Coastguard Worker   }
918*795d594fSAndroid Build Coastguard Worker 
919*795d594fSAndroid Build Coastguard Worker   if (compilation_kind == CompilationKind::kBaseline && compiler_options.ProfileBranches()) {
920*795d594fSAndroid Build Coastguard Worker     graph->SetUsefulOptimizing();
921*795d594fSAndroid Build Coastguard Worker     // Branch profiling currently doesn't support running optimizations.
922*795d594fSAndroid Build Coastguard Worker     RunRequiredPasses(graph, codegen.get(), dex_compilation_unit, &pass_observer);
923*795d594fSAndroid Build Coastguard Worker   } else {
924*795d594fSAndroid Build Coastguard Worker     RunOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer);
925*795d594fSAndroid Build Coastguard Worker     PassScope scope(WriteBarrierElimination::kWBEPassName, &pass_observer);
926*795d594fSAndroid Build Coastguard Worker     WriteBarrierElimination(graph, compilation_stats_.get()).Run();
927*795d594fSAndroid Build Coastguard Worker   }
928*795d594fSAndroid Build Coastguard Worker 
929*795d594fSAndroid Build Coastguard Worker   // If we are compiling baseline and we haven't created a profiling info for
930*795d594fSAndroid Build Coastguard Worker   // this method already, do it now.
931*795d594fSAndroid Build Coastguard Worker   if (jit != nullptr &&
932*795d594fSAndroid Build Coastguard Worker       compilation_kind == CompilationKind::kBaseline &&
933*795d594fSAndroid Build Coastguard Worker       graph->IsUsefulOptimizing() &&
934*795d594fSAndroid Build Coastguard Worker       graph->GetProfilingInfo() == nullptr) {
935*795d594fSAndroid Build Coastguard Worker     ProfilingInfoBuilder(
936*795d594fSAndroid Build Coastguard Worker         graph, codegen->GetCompilerOptions(), codegen.get(), compilation_stats_.get()).Run();
937*795d594fSAndroid Build Coastguard Worker     // We expect a profiling info to be created and attached to the graph.
938*795d594fSAndroid Build Coastguard Worker     // However, we may have run out of memory trying to create it, so in this
939*795d594fSAndroid Build Coastguard Worker     // case just abort the compilation.
940*795d594fSAndroid Build Coastguard Worker     if (graph->GetProfilingInfo() == nullptr) {
941*795d594fSAndroid Build Coastguard Worker       SCOPED_TRACE << "Not compiling because of out of memory";
942*795d594fSAndroid Build Coastguard Worker       MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kJitOutOfMemoryForCommit);
943*795d594fSAndroid Build Coastguard Worker       return nullptr;
944*795d594fSAndroid Build Coastguard Worker     }
945*795d594fSAndroid Build Coastguard Worker   }
946*795d594fSAndroid Build Coastguard Worker 
947*795d594fSAndroid Build Coastguard Worker   AllocateRegisters(graph,
948*795d594fSAndroid Build Coastguard Worker                     codegen.get(),
949*795d594fSAndroid Build Coastguard Worker                     &pass_observer,
950*795d594fSAndroid Build Coastguard Worker                     compilation_stats_.get());
951*795d594fSAndroid Build Coastguard Worker 
952*795d594fSAndroid Build Coastguard Worker   if (UNLIKELY(codegen->GetFrameSize() > codegen->GetMaximumFrameSize())) {
953*795d594fSAndroid Build Coastguard Worker     SCOPED_TRACE << "Not compiling because of stack frame too large";
954*795d594fSAndroid Build Coastguard Worker     LOG(WARNING) << "Stack frame size is " << codegen->GetFrameSize()
955*795d594fSAndroid Build Coastguard Worker                  << " which is larger than the maximum of " << codegen->GetMaximumFrameSize()
956*795d594fSAndroid Build Coastguard Worker                  << " bytes. Method: " << graph->PrettyMethod();
957*795d594fSAndroid Build Coastguard Worker     MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kNotCompiledFrameTooBig);
958*795d594fSAndroid Build Coastguard Worker     return nullptr;
959*795d594fSAndroid Build Coastguard Worker   }
960*795d594fSAndroid Build Coastguard Worker 
961*795d594fSAndroid Build Coastguard Worker   codegen->Compile();
962*795d594fSAndroid Build Coastguard Worker   pass_observer.DumpDisassembly();
963*795d594fSAndroid Build Coastguard Worker 
964*795d594fSAndroid Build Coastguard Worker   MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledBytecode);
965*795d594fSAndroid Build Coastguard Worker   return codegen.release();
966*795d594fSAndroid Build Coastguard Worker }
967*795d594fSAndroid Build Coastguard Worker 
TryCompileIntrinsic(ArenaAllocator * allocator,ArenaStack * arena_stack,const DexCompilationUnit & dex_compilation_unit,ArtMethod * method,VariableSizedHandleScope * handles) const968*795d594fSAndroid Build Coastguard Worker CodeGenerator* OptimizingCompiler::TryCompileIntrinsic(
969*795d594fSAndroid Build Coastguard Worker     ArenaAllocator* allocator,
970*795d594fSAndroid Build Coastguard Worker     ArenaStack* arena_stack,
971*795d594fSAndroid Build Coastguard Worker     const DexCompilationUnit& dex_compilation_unit,
972*795d594fSAndroid Build Coastguard Worker     ArtMethod* method,
973*795d594fSAndroid Build Coastguard Worker     VariableSizedHandleScope* handles) const {
974*795d594fSAndroid Build Coastguard Worker   MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kAttemptIntrinsicCompilation);
975*795d594fSAndroid Build Coastguard Worker   const CompilerOptions& compiler_options = GetCompilerOptions();
976*795d594fSAndroid Build Coastguard Worker   InstructionSet instruction_set = compiler_options.GetInstructionSet();
977*795d594fSAndroid Build Coastguard Worker   const DexFile& dex_file = *dex_compilation_unit.GetDexFile();
978*795d594fSAndroid Build Coastguard Worker   uint32_t method_idx = dex_compilation_unit.GetDexMethodIndex();
979*795d594fSAndroid Build Coastguard Worker 
980*795d594fSAndroid Build Coastguard Worker   // Always use the Thumb-2 assembler: some runtime functionality
981*795d594fSAndroid Build Coastguard Worker   // (like implicit stack overflow checks) assume Thumb-2.
982*795d594fSAndroid Build Coastguard Worker   DCHECK_NE(instruction_set, InstructionSet::kArm);
983*795d594fSAndroid Build Coastguard Worker 
984*795d594fSAndroid Build Coastguard Worker   // Do not attempt to compile on architectures we do not support.
985*795d594fSAndroid Build Coastguard Worker   if (!IsInstructionSetSupported(instruction_set)) {
986*795d594fSAndroid Build Coastguard Worker     return nullptr;
987*795d594fSAndroid Build Coastguard Worker   }
988*795d594fSAndroid Build Coastguard Worker 
989*795d594fSAndroid Build Coastguard Worker   HGraph* graph = new (allocator) HGraph(
990*795d594fSAndroid Build Coastguard Worker       allocator,
991*795d594fSAndroid Build Coastguard Worker       arena_stack,
992*795d594fSAndroid Build Coastguard Worker       handles,
993*795d594fSAndroid Build Coastguard Worker       dex_file,
994*795d594fSAndroid Build Coastguard Worker       method_idx,
995*795d594fSAndroid Build Coastguard Worker       compiler_options.GetInstructionSet(),
996*795d594fSAndroid Build Coastguard Worker       kInvalidInvokeType,
997*795d594fSAndroid Build Coastguard Worker       /* dead_reference_safe= */ true,  // Intrinsics don't affect dead reference safety.
998*795d594fSAndroid Build Coastguard Worker       compiler_options.GetDebuggable(),
999*795d594fSAndroid Build Coastguard Worker       CompilationKind::kOptimized);
1000*795d594fSAndroid Build Coastguard Worker 
1001*795d594fSAndroid Build Coastguard Worker   DCHECK(Runtime::Current()->IsAotCompiler());
1002*795d594fSAndroid Build Coastguard Worker   DCHECK(method != nullptr);
1003*795d594fSAndroid Build Coastguard Worker   graph->SetArtMethod(method);
1004*795d594fSAndroid Build Coastguard Worker 
1005*795d594fSAndroid Build Coastguard Worker   std::unique_ptr<CodeGenerator> codegen(
1006*795d594fSAndroid Build Coastguard Worker       CodeGenerator::Create(graph,
1007*795d594fSAndroid Build Coastguard Worker                             compiler_options,
1008*795d594fSAndroid Build Coastguard Worker                             compilation_stats_.get()));
1009*795d594fSAndroid Build Coastguard Worker   if (codegen.get() == nullptr) {
1010*795d594fSAndroid Build Coastguard Worker     return nullptr;
1011*795d594fSAndroid Build Coastguard Worker   }
1012*795d594fSAndroid Build Coastguard Worker   codegen->GetAssembler()->cfi().SetEnabled(compiler_options.GenerateAnyDebugInfo());
1013*795d594fSAndroid Build Coastguard Worker 
1014*795d594fSAndroid Build Coastguard Worker   PassObserver pass_observer(graph,
1015*795d594fSAndroid Build Coastguard Worker                              codegen.get(),
1016*795d594fSAndroid Build Coastguard Worker                              visualizer_output_.get(),
1017*795d594fSAndroid Build Coastguard Worker                              compiler_options);
1018*795d594fSAndroid Build Coastguard Worker 
1019*795d594fSAndroid Build Coastguard Worker   {
1020*795d594fSAndroid Build Coastguard Worker     VLOG(compiler) << "Building intrinsic graph " << pass_observer.GetMethodName();
1021*795d594fSAndroid Build Coastguard Worker     PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
1022*795d594fSAndroid Build Coastguard Worker     HGraphBuilder builder(graph,
1023*795d594fSAndroid Build Coastguard Worker                           CodeItemDebugInfoAccessor(),  // Null code item.
1024*795d594fSAndroid Build Coastguard Worker                           &dex_compilation_unit,
1025*795d594fSAndroid Build Coastguard Worker                           &dex_compilation_unit,
1026*795d594fSAndroid Build Coastguard Worker                           codegen.get(),
1027*795d594fSAndroid Build Coastguard Worker                           compilation_stats_.get());
1028*795d594fSAndroid Build Coastguard Worker     builder.BuildIntrinsicGraph(method);
1029*795d594fSAndroid Build Coastguard Worker   }
1030*795d594fSAndroid Build Coastguard Worker 
1031*795d594fSAndroid Build Coastguard Worker   OptimizationDef optimizations[] = {
1032*795d594fSAndroid Build Coastguard Worker       // The codegen has a few assumptions that only the instruction simplifier
1033*795d594fSAndroid Build Coastguard Worker       // can satisfy.
1034*795d594fSAndroid Build Coastguard Worker       OptDef(OptimizationPass::kInstructionSimplifier),
1035*795d594fSAndroid Build Coastguard Worker   };
1036*795d594fSAndroid Build Coastguard Worker   RunOptimizations(graph,
1037*795d594fSAndroid Build Coastguard Worker                    codegen.get(),
1038*795d594fSAndroid Build Coastguard Worker                    dex_compilation_unit,
1039*795d594fSAndroid Build Coastguard Worker                    &pass_observer,
1040*795d594fSAndroid Build Coastguard Worker                    optimizations);
1041*795d594fSAndroid Build Coastguard Worker 
1042*795d594fSAndroid Build Coastguard Worker   RunArchOptimizations(graph, codegen.get(), dex_compilation_unit, &pass_observer);
1043*795d594fSAndroid Build Coastguard Worker   {
1044*795d594fSAndroid Build Coastguard Worker     PassScope scope(WriteBarrierElimination::kWBEPassName, &pass_observer);
1045*795d594fSAndroid Build Coastguard Worker     WriteBarrierElimination(graph, compilation_stats_.get()).Run();
1046*795d594fSAndroid Build Coastguard Worker   }
1047*795d594fSAndroid Build Coastguard Worker 
1048*795d594fSAndroid Build Coastguard Worker   AllocateRegisters(graph,
1049*795d594fSAndroid Build Coastguard Worker                     codegen.get(),
1050*795d594fSAndroid Build Coastguard Worker                     &pass_observer,
1051*795d594fSAndroid Build Coastguard Worker                     compilation_stats_.get());
1052*795d594fSAndroid Build Coastguard Worker   if (!codegen->IsLeafMethod()) {
1053*795d594fSAndroid Build Coastguard Worker     VLOG(compiler) << "Intrinsic method is not leaf: " << method->GetIntrinsic()
1054*795d594fSAndroid Build Coastguard Worker         << " " << graph->PrettyMethod();
1055*795d594fSAndroid Build Coastguard Worker     return nullptr;
1056*795d594fSAndroid Build Coastguard Worker   }
1057*795d594fSAndroid Build Coastguard Worker 
1058*795d594fSAndroid Build Coastguard Worker   CHECK_LE(codegen->GetFrameSize(), codegen->GetMaximumFrameSize());
1059*795d594fSAndroid Build Coastguard Worker   codegen->Compile();
1060*795d594fSAndroid Build Coastguard Worker   pass_observer.DumpDisassembly();
1061*795d594fSAndroid Build Coastguard Worker 
1062*795d594fSAndroid Build Coastguard Worker   VLOG(compiler) << "Compiled intrinsic: " << method->GetIntrinsic()
1063*795d594fSAndroid Build Coastguard Worker       << " " << graph->PrettyMethod();
1064*795d594fSAndroid Build Coastguard Worker   MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledIntrinsic);
1065*795d594fSAndroid Build Coastguard Worker   return codegen.release();
1066*795d594fSAndroid Build Coastguard Worker }
1067*795d594fSAndroid Build Coastguard Worker 
Compile(const dex::CodeItem * code_item,uint32_t access_flags,uint16_t class_def_idx,uint32_t method_idx,Handle<mirror::ClassLoader> jclass_loader,const DexFile & dex_file,Handle<mirror::DexCache> dex_cache) const1068*795d594fSAndroid Build Coastguard Worker CompiledMethod* OptimizingCompiler::Compile(const dex::CodeItem* code_item,
1069*795d594fSAndroid Build Coastguard Worker                                             uint32_t access_flags,
1070*795d594fSAndroid Build Coastguard Worker                                             uint16_t class_def_idx,
1071*795d594fSAndroid Build Coastguard Worker                                             uint32_t method_idx,
1072*795d594fSAndroid Build Coastguard Worker                                             Handle<mirror::ClassLoader> jclass_loader,
1073*795d594fSAndroid Build Coastguard Worker                                             const DexFile& dex_file,
1074*795d594fSAndroid Build Coastguard Worker                                             Handle<mirror::DexCache> dex_cache) const {
1075*795d594fSAndroid Build Coastguard Worker   const CompilerOptions& compiler_options = GetCompilerOptions();
1076*795d594fSAndroid Build Coastguard Worker   DCHECK(compiler_options.IsAotCompiler());
1077*795d594fSAndroid Build Coastguard Worker   CompiledMethod* compiled_method = nullptr;
1078*795d594fSAndroid Build Coastguard Worker   Runtime* runtime = Runtime::Current();
1079*795d594fSAndroid Build Coastguard Worker   DCHECK(runtime->IsAotCompiler());
1080*795d594fSAndroid Build Coastguard Worker   ArenaAllocator allocator(runtime->GetArenaPool());
1081*795d594fSAndroid Build Coastguard Worker   ArenaStack arena_stack(runtime->GetArenaPool());
1082*795d594fSAndroid Build Coastguard Worker   std::unique_ptr<CodeGenerator> codegen;
1083*795d594fSAndroid Build Coastguard Worker   bool compiled_intrinsic = false;
1084*795d594fSAndroid Build Coastguard Worker   {
1085*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(Thread::Current());
1086*795d594fSAndroid Build Coastguard Worker     ArtMethod* method =
1087*795d594fSAndroid Build Coastguard Worker         runtime->GetClassLinker()->ResolveMethodId(method_idx, dex_cache, jclass_loader);
1088*795d594fSAndroid Build Coastguard Worker     soa.Self()->ClearException();  // Suppress exception if any.
1089*795d594fSAndroid Build Coastguard Worker     VariableSizedHandleScope handles(soa.Self());
1090*795d594fSAndroid Build Coastguard Worker     Handle<mirror::Class> compiling_class =
1091*795d594fSAndroid Build Coastguard Worker         handles.NewHandle(method != nullptr ? method->GetDeclaringClass() : nullptr);
1092*795d594fSAndroid Build Coastguard Worker     DexCompilationUnit dex_compilation_unit(
1093*795d594fSAndroid Build Coastguard Worker         jclass_loader,
1094*795d594fSAndroid Build Coastguard Worker         runtime->GetClassLinker(),
1095*795d594fSAndroid Build Coastguard Worker         dex_file,
1096*795d594fSAndroid Build Coastguard Worker         code_item,
1097*795d594fSAndroid Build Coastguard Worker         class_def_idx,
1098*795d594fSAndroid Build Coastguard Worker         method_idx,
1099*795d594fSAndroid Build Coastguard Worker         access_flags,
1100*795d594fSAndroid Build Coastguard Worker         /*verified_method=*/ nullptr,  // Not needed by the Optimizing compiler.
1101*795d594fSAndroid Build Coastguard Worker         dex_cache,
1102*795d594fSAndroid Build Coastguard Worker         compiling_class);
1103*795d594fSAndroid Build Coastguard Worker     // All signature polymorphic methods are native.
1104*795d594fSAndroid Build Coastguard Worker     DCHECK(method == nullptr || !method->IsSignaturePolymorphic());
1105*795d594fSAndroid Build Coastguard Worker     // Go to native so that we don't block GC during compilation.
1106*795d594fSAndroid Build Coastguard Worker     ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
1107*795d594fSAndroid Build Coastguard Worker     // Try to compile a fully intrinsified implementation.
1108*795d594fSAndroid Build Coastguard Worker     if (method != nullptr && UNLIKELY(method->IsIntrinsic())) {
1109*795d594fSAndroid Build Coastguard Worker       DCHECK(compiler_options.IsBootImage());
1110*795d594fSAndroid Build Coastguard Worker       codegen.reset(
1111*795d594fSAndroid Build Coastguard Worker           TryCompileIntrinsic(&allocator,
1112*795d594fSAndroid Build Coastguard Worker                               &arena_stack,
1113*795d594fSAndroid Build Coastguard Worker                               dex_compilation_unit,
1114*795d594fSAndroid Build Coastguard Worker                               method,
1115*795d594fSAndroid Build Coastguard Worker                               &handles));
1116*795d594fSAndroid Build Coastguard Worker       if (codegen != nullptr) {
1117*795d594fSAndroid Build Coastguard Worker         compiled_intrinsic = true;
1118*795d594fSAndroid Build Coastguard Worker       }
1119*795d594fSAndroid Build Coastguard Worker     }
1120*795d594fSAndroid Build Coastguard Worker     if (codegen == nullptr) {
1121*795d594fSAndroid Build Coastguard Worker       codegen.reset(
1122*795d594fSAndroid Build Coastguard Worker           TryCompile(&allocator,
1123*795d594fSAndroid Build Coastguard Worker                      &arena_stack,
1124*795d594fSAndroid Build Coastguard Worker                      dex_compilation_unit,
1125*795d594fSAndroid Build Coastguard Worker                      method,
1126*795d594fSAndroid Build Coastguard Worker                      compiler_options.IsBaseline()
1127*795d594fSAndroid Build Coastguard Worker                         ? CompilationKind::kBaseline
1128*795d594fSAndroid Build Coastguard Worker                         : CompilationKind::kOptimized,
1129*795d594fSAndroid Build Coastguard Worker                      &handles));
1130*795d594fSAndroid Build Coastguard Worker     }
1131*795d594fSAndroid Build Coastguard Worker   }
1132*795d594fSAndroid Build Coastguard Worker   if (codegen.get() != nullptr) {
1133*795d594fSAndroid Build Coastguard Worker     compiled_method = Emit(&allocator,
1134*795d594fSAndroid Build Coastguard Worker                            codegen.get(),
1135*795d594fSAndroid Build Coastguard Worker                            compiled_intrinsic,
1136*795d594fSAndroid Build Coastguard Worker                            compiled_intrinsic ? nullptr : code_item);
1137*795d594fSAndroid Build Coastguard Worker 
1138*795d594fSAndroid Build Coastguard Worker     if (kArenaAllocatorCountAllocations) {
1139*795d594fSAndroid Build Coastguard Worker       codegen.reset();  // Release codegen's ScopedArenaAllocator for memory accounting.
1140*795d594fSAndroid Build Coastguard Worker       size_t total_allocated = allocator.BytesAllocated() + arena_stack.PeakBytesAllocated();
1141*795d594fSAndroid Build Coastguard Worker       if (total_allocated > kArenaAllocatorMemoryReportThreshold) {
1142*795d594fSAndroid Build Coastguard Worker         MemStats mem_stats(allocator.GetMemStats());
1143*795d594fSAndroid Build Coastguard Worker         MemStats peak_stats(arena_stack.GetPeakStats());
1144*795d594fSAndroid Build Coastguard Worker         LOG(INFO) << "Used " << total_allocated << " bytes of arena memory for compiling "
1145*795d594fSAndroid Build Coastguard Worker                   << dex_file.PrettyMethod(method_idx)
1146*795d594fSAndroid Build Coastguard Worker                   << "\n" << Dumpable<MemStats>(mem_stats)
1147*795d594fSAndroid Build Coastguard Worker                   << "\n" << Dumpable<MemStats>(peak_stats);
1148*795d594fSAndroid Build Coastguard Worker       }
1149*795d594fSAndroid Build Coastguard Worker     }
1150*795d594fSAndroid Build Coastguard Worker   }
1151*795d594fSAndroid Build Coastguard Worker 
1152*795d594fSAndroid Build Coastguard Worker   if (kIsDebugBuild &&
1153*795d594fSAndroid Build Coastguard Worker       compiler_options.CompileArtTest() &&
1154*795d594fSAndroid Build Coastguard Worker       IsInstructionSetSupported(compiler_options.GetInstructionSet())) {
1155*795d594fSAndroid Build Coastguard Worker     // For testing purposes, we put a special marker on method names
1156*795d594fSAndroid Build Coastguard Worker     // that should be compiled with this compiler (when the
1157*795d594fSAndroid Build Coastguard Worker     // instruction set is supported). This makes sure we're not
1158*795d594fSAndroid Build Coastguard Worker     // regressing.
1159*795d594fSAndroid Build Coastguard Worker     std::string method_name = dex_file.PrettyMethod(method_idx);
1160*795d594fSAndroid Build Coastguard Worker     bool shouldCompile = method_name.find("$opt$") != std::string::npos;
1161*795d594fSAndroid Build Coastguard Worker     DCHECK_IMPLIES(compiled_method == nullptr, !shouldCompile) << "Didn't compile " << method_name;
1162*795d594fSAndroid Build Coastguard Worker   }
1163*795d594fSAndroid Build Coastguard Worker 
1164*795d594fSAndroid Build Coastguard Worker   return compiled_method;
1165*795d594fSAndroid Build Coastguard Worker }
1166*795d594fSAndroid Build Coastguard Worker 
CreateJniStackMap(ScopedArenaAllocator * allocator,const JniCompiledMethod & jni_compiled_method,size_t code_size,bool debuggable)1167*795d594fSAndroid Build Coastguard Worker static ScopedArenaVector<uint8_t> CreateJniStackMap(ScopedArenaAllocator* allocator,
1168*795d594fSAndroid Build Coastguard Worker                                                     const JniCompiledMethod& jni_compiled_method,
1169*795d594fSAndroid Build Coastguard Worker                                                     size_t code_size,
1170*795d594fSAndroid Build Coastguard Worker                                                     bool debuggable) {
1171*795d594fSAndroid Build Coastguard Worker   // StackMapStream is quite large, so allocate it using the ScopedArenaAllocator
1172*795d594fSAndroid Build Coastguard Worker   // to stay clear of the frame size limit.
1173*795d594fSAndroid Build Coastguard Worker   std::unique_ptr<StackMapStream> stack_map_stream(
1174*795d594fSAndroid Build Coastguard Worker       new (allocator) StackMapStream(allocator, jni_compiled_method.GetInstructionSet()));
1175*795d594fSAndroid Build Coastguard Worker   stack_map_stream->BeginMethod(jni_compiled_method.GetFrameSize(),
1176*795d594fSAndroid Build Coastguard Worker                                 jni_compiled_method.GetCoreSpillMask(),
1177*795d594fSAndroid Build Coastguard Worker                                 jni_compiled_method.GetFpSpillMask(),
1178*795d594fSAndroid Build Coastguard Worker                                 /* num_dex_registers= */ 0,
1179*795d594fSAndroid Build Coastguard Worker                                 /* baseline= */ false,
1180*795d594fSAndroid Build Coastguard Worker                                 debuggable);
1181*795d594fSAndroid Build Coastguard Worker   stack_map_stream->EndMethod(code_size);
1182*795d594fSAndroid Build Coastguard Worker   return stack_map_stream->Encode();
1183*795d594fSAndroid Build Coastguard Worker }
1184*795d594fSAndroid Build Coastguard Worker 
JniCompile(uint32_t access_flags,uint32_t method_idx,const DexFile & dex_file,Handle<mirror::DexCache> dex_cache) const1185*795d594fSAndroid Build Coastguard Worker CompiledMethod* OptimizingCompiler::JniCompile(uint32_t access_flags,
1186*795d594fSAndroid Build Coastguard Worker                                                uint32_t method_idx,
1187*795d594fSAndroid Build Coastguard Worker                                                const DexFile& dex_file,
1188*795d594fSAndroid Build Coastguard Worker                                                Handle<mirror::DexCache> dex_cache) const {
1189*795d594fSAndroid Build Coastguard Worker   Runtime* runtime = Runtime::Current();
1190*795d594fSAndroid Build Coastguard Worker   ArenaAllocator allocator(runtime->GetArenaPool());
1191*795d594fSAndroid Build Coastguard Worker   ArenaStack arena_stack(runtime->GetArenaPool());
1192*795d594fSAndroid Build Coastguard Worker 
1193*795d594fSAndroid Build Coastguard Worker   const CompilerOptions& compiler_options = GetCompilerOptions();
1194*795d594fSAndroid Build Coastguard Worker   if (compiler_options.IsBootImage()) {
1195*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(Thread::Current());
1196*795d594fSAndroid Build Coastguard Worker     ArtMethod* method = runtime->GetClassLinker()->LookupResolvedMethod(
1197*795d594fSAndroid Build Coastguard Worker         method_idx, dex_cache.Get(), /*class_loader=*/ nullptr);
1198*795d594fSAndroid Build Coastguard Worker     // Try to compile a fully intrinsified implementation. Do not try to do this for
1199*795d594fSAndroid Build Coastguard Worker     // signature polymorphic methods as the InstructionBuilder cannot handle them;
1200*795d594fSAndroid Build Coastguard Worker     // and it would be useless as they always have a slow path for type conversions.
1201*795d594fSAndroid Build Coastguard Worker     if (method != nullptr && UNLIKELY(method->IsIntrinsic()) && !method->IsSignaturePolymorphic()) {
1202*795d594fSAndroid Build Coastguard Worker       VariableSizedHandleScope handles(soa.Self());
1203*795d594fSAndroid Build Coastguard Worker       ScopedNullHandle<mirror::ClassLoader> class_loader;  // null means boot class path loader.
1204*795d594fSAndroid Build Coastguard Worker       Handle<mirror::Class> compiling_class = handles.NewHandle(method->GetDeclaringClass());
1205*795d594fSAndroid Build Coastguard Worker       DexCompilationUnit dex_compilation_unit(
1206*795d594fSAndroid Build Coastguard Worker           class_loader,
1207*795d594fSAndroid Build Coastguard Worker           runtime->GetClassLinker(),
1208*795d594fSAndroid Build Coastguard Worker           dex_file,
1209*795d594fSAndroid Build Coastguard Worker           /*code_item=*/ nullptr,
1210*795d594fSAndroid Build Coastguard Worker           /*class_def_idx=*/ DexFile::kDexNoIndex16,
1211*795d594fSAndroid Build Coastguard Worker           method_idx,
1212*795d594fSAndroid Build Coastguard Worker           access_flags,
1213*795d594fSAndroid Build Coastguard Worker           /*verified_method=*/ nullptr,
1214*795d594fSAndroid Build Coastguard Worker           dex_cache,
1215*795d594fSAndroid Build Coastguard Worker           compiling_class);
1216*795d594fSAndroid Build Coastguard Worker       // Go to native so that we don't block GC during compilation.
1217*795d594fSAndroid Build Coastguard Worker       ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
1218*795d594fSAndroid Build Coastguard Worker       std::unique_ptr<CodeGenerator> codegen(
1219*795d594fSAndroid Build Coastguard Worker           TryCompileIntrinsic(&allocator,
1220*795d594fSAndroid Build Coastguard Worker                               &arena_stack,
1221*795d594fSAndroid Build Coastguard Worker                               dex_compilation_unit,
1222*795d594fSAndroid Build Coastguard Worker                               method,
1223*795d594fSAndroid Build Coastguard Worker                               &handles));
1224*795d594fSAndroid Build Coastguard Worker       if (codegen != nullptr) {
1225*795d594fSAndroid Build Coastguard Worker         return Emit(&allocator,
1226*795d594fSAndroid Build Coastguard Worker                     codegen.get(),
1227*795d594fSAndroid Build Coastguard Worker                     /*is_intrinsic=*/ true,
1228*795d594fSAndroid Build Coastguard Worker                     /*item=*/ nullptr);
1229*795d594fSAndroid Build Coastguard Worker       }
1230*795d594fSAndroid Build Coastguard Worker     }
1231*795d594fSAndroid Build Coastguard Worker   }
1232*795d594fSAndroid Build Coastguard Worker 
1233*795d594fSAndroid Build Coastguard Worker   JniCompiledMethod jni_compiled_method = ArtQuickJniCompileMethod(
1234*795d594fSAndroid Build Coastguard Worker       compiler_options, dex_file.GetMethodShortyView(method_idx), access_flags, &allocator);
1235*795d594fSAndroid Build Coastguard Worker   MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kCompiledNativeStub);
1236*795d594fSAndroid Build Coastguard Worker 
1237*795d594fSAndroid Build Coastguard Worker   ScopedArenaAllocator stack_map_allocator(&arena_stack);  // Will hold the stack map.
1238*795d594fSAndroid Build Coastguard Worker   ScopedArenaVector<uint8_t> stack_map =
1239*795d594fSAndroid Build Coastguard Worker       CreateJniStackMap(&stack_map_allocator,
1240*795d594fSAndroid Build Coastguard Worker                         jni_compiled_method,
1241*795d594fSAndroid Build Coastguard Worker                         jni_compiled_method.GetCode().size(),
1242*795d594fSAndroid Build Coastguard Worker                         compiler_options.GetDebuggable() && compiler_options.IsJitCompiler());
1243*795d594fSAndroid Build Coastguard Worker   return GetCompiledCodeStorage()->CreateCompiledMethod(
1244*795d594fSAndroid Build Coastguard Worker       jni_compiled_method.GetInstructionSet(),
1245*795d594fSAndroid Build Coastguard Worker       jni_compiled_method.GetCode(),
1246*795d594fSAndroid Build Coastguard Worker       ArrayRef<const uint8_t>(stack_map),
1247*795d594fSAndroid Build Coastguard Worker       jni_compiled_method.GetCfi(),
1248*795d594fSAndroid Build Coastguard Worker       /*patches=*/ ArrayRef<const linker::LinkerPatch>(),
1249*795d594fSAndroid Build Coastguard Worker       /*is_intrinsic=*/ false);
1250*795d594fSAndroid Build Coastguard Worker }
1251*795d594fSAndroid Build Coastguard Worker 
CreateOptimizingCompiler(const CompilerOptions & compiler_options,CompiledCodeStorage * storage)1252*795d594fSAndroid Build Coastguard Worker Compiler* CreateOptimizingCompiler(const CompilerOptions& compiler_options,
1253*795d594fSAndroid Build Coastguard Worker                                    CompiledCodeStorage* storage) {
1254*795d594fSAndroid Build Coastguard Worker   return new OptimizingCompiler(compiler_options, storage);
1255*795d594fSAndroid Build Coastguard Worker }
1256*795d594fSAndroid Build Coastguard Worker 
EncodeArtMethodInInlineInfo(ArtMethod * method)1257*795d594fSAndroid Build Coastguard Worker bool EncodeArtMethodInInlineInfo([[maybe_unused]] ArtMethod* method) {
1258*795d594fSAndroid Build Coastguard Worker   // Note: the runtime is null only for unit testing.
1259*795d594fSAndroid Build Coastguard Worker   return Runtime::Current() == nullptr || !Runtime::Current()->IsAotCompiler();
1260*795d594fSAndroid Build Coastguard Worker }
1261*795d594fSAndroid Build Coastguard Worker 
JitCompile(Thread * self,jit::JitCodeCache * code_cache,jit::JitMemoryRegion * region,ArtMethod * method,CompilationKind compilation_kind,jit::JitLogger * jit_logger)1262*795d594fSAndroid Build Coastguard Worker bool OptimizingCompiler::JitCompile(Thread* self,
1263*795d594fSAndroid Build Coastguard Worker                                     jit::JitCodeCache* code_cache,
1264*795d594fSAndroid Build Coastguard Worker                                     jit::JitMemoryRegion* region,
1265*795d594fSAndroid Build Coastguard Worker                                     ArtMethod* method,
1266*795d594fSAndroid Build Coastguard Worker                                     CompilationKind compilation_kind,
1267*795d594fSAndroid Build Coastguard Worker                                     jit::JitLogger* jit_logger) {
1268*795d594fSAndroid Build Coastguard Worker   const CompilerOptions& compiler_options = GetCompilerOptions();
1269*795d594fSAndroid Build Coastguard Worker   DCHECK(compiler_options.IsJitCompiler());
1270*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(compiler_options.IsJitCompilerForSharedCode(), code_cache->IsSharedRegion(*region));
1271*795d594fSAndroid Build Coastguard Worker   StackHandleScope<3> hs(self);
1272*795d594fSAndroid Build Coastguard Worker   Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1273*795d594fSAndroid Build Coastguard Worker       method->GetDeclaringClass()->GetClassLoader()));
1274*795d594fSAndroid Build Coastguard Worker   Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
1275*795d594fSAndroid Build Coastguard Worker   DCHECK(method->IsCompilable());
1276*795d594fSAndroid Build Coastguard Worker 
1277*795d594fSAndroid Build Coastguard Worker   const DexFile* dex_file = method->GetDexFile();
1278*795d594fSAndroid Build Coastguard Worker   const uint16_t class_def_idx = method->GetClassDefIndex();
1279*795d594fSAndroid Build Coastguard Worker   const dex::CodeItem* code_item = method->GetCodeItem();
1280*795d594fSAndroid Build Coastguard Worker   const uint32_t method_idx = method->GetDexMethodIndex();
1281*795d594fSAndroid Build Coastguard Worker   const uint32_t access_flags = method->GetAccessFlags();
1282*795d594fSAndroid Build Coastguard Worker 
1283*795d594fSAndroid Build Coastguard Worker   Runtime* runtime = Runtime::Current();
1284*795d594fSAndroid Build Coastguard Worker   ArenaAllocator allocator(runtime->GetJitArenaPool());
1285*795d594fSAndroid Build Coastguard Worker 
1286*795d594fSAndroid Build Coastguard Worker   if (UNLIKELY(method->IsNative())) {
1287*795d594fSAndroid Build Coastguard Worker     // Use GenericJniTrampoline for critical native methods in debuggable runtimes. We don't
1288*795d594fSAndroid Build Coastguard Worker     // support calling method entry / exit hooks for critical native methods yet.
1289*795d594fSAndroid Build Coastguard Worker     // TODO(mythria): Add support for calling method entry / exit hooks in JITed stubs for critical
1290*795d594fSAndroid Build Coastguard Worker     // native methods too.
1291*795d594fSAndroid Build Coastguard Worker     if (compiler_options.GetDebuggable() && method->IsCriticalNative()) {
1292*795d594fSAndroid Build Coastguard Worker       DCHECK(compiler_options.IsJitCompiler());
1293*795d594fSAndroid Build Coastguard Worker       return false;
1294*795d594fSAndroid Build Coastguard Worker     }
1295*795d594fSAndroid Build Coastguard Worker     // Java debuggable runtimes should set compiler options to debuggable, so that we either
1296*795d594fSAndroid Build Coastguard Worker     // generate method entry / exit hooks or skip JITing. For critical native methods we don't
1297*795d594fSAndroid Build Coastguard Worker     // generate method entry / exit hooks so we shouldn't JIT them in debuggable runtimes.
1298*795d594fSAndroid Build Coastguard Worker     DCHECK_IMPLIES(method->IsCriticalNative(), !runtime->IsJavaDebuggable());
1299*795d594fSAndroid Build Coastguard Worker 
1300*795d594fSAndroid Build Coastguard Worker     JniCompiledMethod jni_compiled_method = ArtQuickJniCompileMethod(
1301*795d594fSAndroid Build Coastguard Worker         compiler_options, dex_file->GetMethodShortyView(method_idx), access_flags, &allocator);
1302*795d594fSAndroid Build Coastguard Worker     std::vector<Handle<mirror::Object>> roots;
1303*795d594fSAndroid Build Coastguard Worker     ArenaSet<ArtMethod*, std::less<ArtMethod*>> cha_single_implementation_list(
1304*795d594fSAndroid Build Coastguard Worker         allocator.Adapter(kArenaAllocCHA));
1305*795d594fSAndroid Build Coastguard Worker     ArenaStack arena_stack(runtime->GetJitArenaPool());
1306*795d594fSAndroid Build Coastguard Worker     // StackMapStream is large and it does not fit into this frame, so we need helper method.
1307*795d594fSAndroid Build Coastguard Worker     ScopedArenaAllocator stack_map_allocator(&arena_stack);  // Will hold the stack map.
1308*795d594fSAndroid Build Coastguard Worker     ScopedArenaVector<uint8_t> stack_map =
1309*795d594fSAndroid Build Coastguard Worker         CreateJniStackMap(&stack_map_allocator,
1310*795d594fSAndroid Build Coastguard Worker                           jni_compiled_method,
1311*795d594fSAndroid Build Coastguard Worker                           jni_compiled_method.GetCode().size(),
1312*795d594fSAndroid Build Coastguard Worker                           compiler_options.GetDebuggable() && compiler_options.IsJitCompiler());
1313*795d594fSAndroid Build Coastguard Worker 
1314*795d594fSAndroid Build Coastguard Worker     ArrayRef<const uint8_t> reserved_code;
1315*795d594fSAndroid Build Coastguard Worker     ArrayRef<const uint8_t> reserved_data;
1316*795d594fSAndroid Build Coastguard Worker     if (!code_cache->Reserve(self,
1317*795d594fSAndroid Build Coastguard Worker                              region,
1318*795d594fSAndroid Build Coastguard Worker                              jni_compiled_method.GetCode().size(),
1319*795d594fSAndroid Build Coastguard Worker                              stack_map.size(),
1320*795d594fSAndroid Build Coastguard Worker                              /* number_of_roots= */ 0,
1321*795d594fSAndroid Build Coastguard Worker                              method,
1322*795d594fSAndroid Build Coastguard Worker                              /*out*/ &reserved_code,
1323*795d594fSAndroid Build Coastguard Worker                              /*out*/ &reserved_data)) {
1324*795d594fSAndroid Build Coastguard Worker       MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kJitOutOfMemoryForCommit);
1325*795d594fSAndroid Build Coastguard Worker       return false;
1326*795d594fSAndroid Build Coastguard Worker     }
1327*795d594fSAndroid Build Coastguard Worker     const uint8_t* code = reserved_code.data() + OatQuickMethodHeader::InstructionAlignedSize();
1328*795d594fSAndroid Build Coastguard Worker 
1329*795d594fSAndroid Build Coastguard Worker     // Add debug info after we know the code location but before we update entry-point.
1330*795d594fSAndroid Build Coastguard Worker     std::vector<uint8_t> debug_info;
1331*795d594fSAndroid Build Coastguard Worker     if (compiler_options.GenerateAnyDebugInfo()) {
1332*795d594fSAndroid Build Coastguard Worker       debug::MethodDebugInfo info = {};
1333*795d594fSAndroid Build Coastguard Worker       // Simpleperf relies on art_jni_trampoline to detect jni methods.
1334*795d594fSAndroid Build Coastguard Worker       info.custom_name = "art_jni_trampoline";
1335*795d594fSAndroid Build Coastguard Worker       info.dex_file = dex_file;
1336*795d594fSAndroid Build Coastguard Worker       info.class_def_index = class_def_idx;
1337*795d594fSAndroid Build Coastguard Worker       info.dex_method_index = method_idx;
1338*795d594fSAndroid Build Coastguard Worker       info.access_flags = access_flags;
1339*795d594fSAndroid Build Coastguard Worker       info.code_item = code_item;
1340*795d594fSAndroid Build Coastguard Worker       info.isa = jni_compiled_method.GetInstructionSet();
1341*795d594fSAndroid Build Coastguard Worker       info.deduped = false;
1342*795d594fSAndroid Build Coastguard Worker       info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1343*795d594fSAndroid Build Coastguard Worker       info.is_optimized = true;
1344*795d594fSAndroid Build Coastguard Worker       info.is_code_address_text_relative = false;
1345*795d594fSAndroid Build Coastguard Worker       info.code_address = reinterpret_cast<uintptr_t>(code);
1346*795d594fSAndroid Build Coastguard Worker       info.code_size = jni_compiled_method.GetCode().size();
1347*795d594fSAndroid Build Coastguard Worker       info.frame_size_in_bytes = jni_compiled_method.GetFrameSize();
1348*795d594fSAndroid Build Coastguard Worker       info.code_info = nullptr;
1349*795d594fSAndroid Build Coastguard Worker       info.cfi = jni_compiled_method.GetCfi();
1350*795d594fSAndroid Build Coastguard Worker       debug_info = GenerateJitDebugInfo(info);
1351*795d594fSAndroid Build Coastguard Worker     }
1352*795d594fSAndroid Build Coastguard Worker 
1353*795d594fSAndroid Build Coastguard Worker     if (!code_cache->Commit(self,
1354*795d594fSAndroid Build Coastguard Worker                             region,
1355*795d594fSAndroid Build Coastguard Worker                             method,
1356*795d594fSAndroid Build Coastguard Worker                             reserved_code,
1357*795d594fSAndroid Build Coastguard Worker                             jni_compiled_method.GetCode(),
1358*795d594fSAndroid Build Coastguard Worker                             reserved_data,
1359*795d594fSAndroid Build Coastguard Worker                             roots,
1360*795d594fSAndroid Build Coastguard Worker                             ArrayRef<const uint8_t>(stack_map),
1361*795d594fSAndroid Build Coastguard Worker                             debug_info,
1362*795d594fSAndroid Build Coastguard Worker                             /* is_full_debug_info= */ compiler_options.GetGenerateDebugInfo(),
1363*795d594fSAndroid Build Coastguard Worker                             compilation_kind,
1364*795d594fSAndroid Build Coastguard Worker                             cha_single_implementation_list)) {
1365*795d594fSAndroid Build Coastguard Worker       code_cache->Free(self, region, reserved_code.data(), reserved_data.data());
1366*795d594fSAndroid Build Coastguard Worker       return false;
1367*795d594fSAndroid Build Coastguard Worker     }
1368*795d594fSAndroid Build Coastguard Worker 
1369*795d594fSAndroid Build Coastguard Worker     Runtime::Current()->GetJit()->AddMemoryUsage(method, allocator.BytesUsed());
1370*795d594fSAndroid Build Coastguard Worker     if (jit_logger != nullptr) {
1371*795d594fSAndroid Build Coastguard Worker       jit_logger->WriteLog(code, jni_compiled_method.GetCode().size(), method);
1372*795d594fSAndroid Build Coastguard Worker     }
1373*795d594fSAndroid Build Coastguard Worker     return true;
1374*795d594fSAndroid Build Coastguard Worker   }
1375*795d594fSAndroid Build Coastguard Worker 
1376*795d594fSAndroid Build Coastguard Worker   ArenaStack arena_stack(runtime->GetJitArenaPool());
1377*795d594fSAndroid Build Coastguard Worker   VariableSizedHandleScope handles(self);
1378*795d594fSAndroid Build Coastguard Worker 
1379*795d594fSAndroid Build Coastguard Worker   std::unique_ptr<CodeGenerator> codegen;
1380*795d594fSAndroid Build Coastguard Worker   {
1381*795d594fSAndroid Build Coastguard Worker     Handle<mirror::Class> compiling_class = handles.NewHandle(method->GetDeclaringClass());
1382*795d594fSAndroid Build Coastguard Worker     DexCompilationUnit dex_compilation_unit(
1383*795d594fSAndroid Build Coastguard Worker         class_loader,
1384*795d594fSAndroid Build Coastguard Worker         runtime->GetClassLinker(),
1385*795d594fSAndroid Build Coastguard Worker         *dex_file,
1386*795d594fSAndroid Build Coastguard Worker         code_item,
1387*795d594fSAndroid Build Coastguard Worker         class_def_idx,
1388*795d594fSAndroid Build Coastguard Worker         method_idx,
1389*795d594fSAndroid Build Coastguard Worker         access_flags,
1390*795d594fSAndroid Build Coastguard Worker         /*verified_method=*/ nullptr,
1391*795d594fSAndroid Build Coastguard Worker         dex_cache,
1392*795d594fSAndroid Build Coastguard Worker         compiling_class);
1393*795d594fSAndroid Build Coastguard Worker 
1394*795d594fSAndroid Build Coastguard Worker     // Go to native so that we don't block GC during compilation.
1395*795d594fSAndroid Build Coastguard Worker     ScopedThreadSuspension sts(self, ThreadState::kNative);
1396*795d594fSAndroid Build Coastguard Worker     codegen.reset(
1397*795d594fSAndroid Build Coastguard Worker         TryCompile(&allocator,
1398*795d594fSAndroid Build Coastguard Worker                    &arena_stack,
1399*795d594fSAndroid Build Coastguard Worker                    dex_compilation_unit,
1400*795d594fSAndroid Build Coastguard Worker                    method,
1401*795d594fSAndroid Build Coastguard Worker                    compilation_kind,
1402*795d594fSAndroid Build Coastguard Worker                    &handles));
1403*795d594fSAndroid Build Coastguard Worker     if (codegen.get() == nullptr) {
1404*795d594fSAndroid Build Coastguard Worker       return false;
1405*795d594fSAndroid Build Coastguard Worker     }
1406*795d594fSAndroid Build Coastguard Worker   }
1407*795d594fSAndroid Build Coastguard Worker 
1408*795d594fSAndroid Build Coastguard Worker   ScopedArenaVector<uint8_t> stack_map = codegen->BuildStackMaps(code_item);
1409*795d594fSAndroid Build Coastguard Worker 
1410*795d594fSAndroid Build Coastguard Worker   ArrayRef<const uint8_t> reserved_code;
1411*795d594fSAndroid Build Coastguard Worker   ArrayRef<const uint8_t> reserved_data;
1412*795d594fSAndroid Build Coastguard Worker   if (!code_cache->Reserve(self,
1413*795d594fSAndroid Build Coastguard Worker                            region,
1414*795d594fSAndroid Build Coastguard Worker                            codegen->GetAssembler()->CodeSize(),
1415*795d594fSAndroid Build Coastguard Worker                            stack_map.size(),
1416*795d594fSAndroid Build Coastguard Worker                            /*number_of_roots=*/codegen->GetNumberOfJitRoots(),
1417*795d594fSAndroid Build Coastguard Worker                            method,
1418*795d594fSAndroid Build Coastguard Worker                            /*out*/ &reserved_code,
1419*795d594fSAndroid Build Coastguard Worker                            /*out*/ &reserved_data)) {
1420*795d594fSAndroid Build Coastguard Worker     MaybeRecordStat(compilation_stats_.get(), MethodCompilationStat::kJitOutOfMemoryForCommit);
1421*795d594fSAndroid Build Coastguard Worker     return false;
1422*795d594fSAndroid Build Coastguard Worker   }
1423*795d594fSAndroid Build Coastguard Worker   const uint8_t* code = reserved_code.data() + OatQuickMethodHeader::InstructionAlignedSize();
1424*795d594fSAndroid Build Coastguard Worker   const uint8_t* roots_data = reserved_data.data();
1425*795d594fSAndroid Build Coastguard Worker 
1426*795d594fSAndroid Build Coastguard Worker   std::vector<Handle<mirror::Object>> roots;
1427*795d594fSAndroid Build Coastguard Worker   codegen->EmitJitRoots(const_cast<uint8_t*>(codegen->GetAssembler()->CodeBufferBaseAddress()),
1428*795d594fSAndroid Build Coastguard Worker                         roots_data,
1429*795d594fSAndroid Build Coastguard Worker                         &roots);
1430*795d594fSAndroid Build Coastguard Worker   // The root Handle<>s filled by the codegen reference entries in the VariableSizedHandleScope.
1431*795d594fSAndroid Build Coastguard Worker   DCHECK(std::all_of(roots.begin(),
1432*795d594fSAndroid Build Coastguard Worker                      roots.end(),
1433*795d594fSAndroid Build Coastguard Worker                      [&handles](Handle<mirror::Object> root){
1434*795d594fSAndroid Build Coastguard Worker                        return handles.Contains(root.GetReference());
1435*795d594fSAndroid Build Coastguard Worker                      }));
1436*795d594fSAndroid Build Coastguard Worker 
1437*795d594fSAndroid Build Coastguard Worker   // Add debug info after we know the code location but before we update entry-point.
1438*795d594fSAndroid Build Coastguard Worker   std::vector<uint8_t> debug_info;
1439*795d594fSAndroid Build Coastguard Worker   if (compiler_options.GenerateAnyDebugInfo()) {
1440*795d594fSAndroid Build Coastguard Worker     debug::MethodDebugInfo info = {};
1441*795d594fSAndroid Build Coastguard Worker     DCHECK(info.custom_name.empty());
1442*795d594fSAndroid Build Coastguard Worker     info.dex_file = dex_file;
1443*795d594fSAndroid Build Coastguard Worker     info.class_def_index = class_def_idx;
1444*795d594fSAndroid Build Coastguard Worker     info.dex_method_index = method_idx;
1445*795d594fSAndroid Build Coastguard Worker     info.access_flags = access_flags;
1446*795d594fSAndroid Build Coastguard Worker     info.code_item = code_item;
1447*795d594fSAndroid Build Coastguard Worker     info.isa = codegen->GetInstructionSet();
1448*795d594fSAndroid Build Coastguard Worker     info.deduped = false;
1449*795d594fSAndroid Build Coastguard Worker     info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1450*795d594fSAndroid Build Coastguard Worker     info.is_optimized = true;
1451*795d594fSAndroid Build Coastguard Worker     info.is_code_address_text_relative = false;
1452*795d594fSAndroid Build Coastguard Worker     info.code_address = reinterpret_cast<uintptr_t>(code);
1453*795d594fSAndroid Build Coastguard Worker     info.code_size = codegen->GetAssembler()->CodeSize(),
1454*795d594fSAndroid Build Coastguard Worker     info.frame_size_in_bytes = codegen->GetFrameSize();
1455*795d594fSAndroid Build Coastguard Worker     info.code_info = stack_map.size() == 0 ? nullptr : stack_map.data();
1456*795d594fSAndroid Build Coastguard Worker     info.cfi = ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data());
1457*795d594fSAndroid Build Coastguard Worker     debug_info = GenerateJitDebugInfo(info);
1458*795d594fSAndroid Build Coastguard Worker   }
1459*795d594fSAndroid Build Coastguard Worker 
1460*795d594fSAndroid Build Coastguard Worker   if (compilation_kind == CompilationKind::kBaseline &&
1461*795d594fSAndroid Build Coastguard Worker       !codegen->GetGraph()->IsUsefulOptimizing()) {
1462*795d594fSAndroid Build Coastguard Worker     compilation_kind = CompilationKind::kOptimized;
1463*795d594fSAndroid Build Coastguard Worker   }
1464*795d594fSAndroid Build Coastguard Worker 
1465*795d594fSAndroid Build Coastguard Worker   if (!code_cache->Commit(self,
1466*795d594fSAndroid Build Coastguard Worker                           region,
1467*795d594fSAndroid Build Coastguard Worker                           method,
1468*795d594fSAndroid Build Coastguard Worker                           reserved_code,
1469*795d594fSAndroid Build Coastguard Worker                           codegen->GetCode(),
1470*795d594fSAndroid Build Coastguard Worker                           reserved_data,
1471*795d594fSAndroid Build Coastguard Worker                           roots,
1472*795d594fSAndroid Build Coastguard Worker                           ArrayRef<const uint8_t>(stack_map),
1473*795d594fSAndroid Build Coastguard Worker                           debug_info,
1474*795d594fSAndroid Build Coastguard Worker                           /* is_full_debug_info= */ compiler_options.GetGenerateDebugInfo(),
1475*795d594fSAndroid Build Coastguard Worker                           compilation_kind,
1476*795d594fSAndroid Build Coastguard Worker                           codegen->GetGraph()->GetCHASingleImplementationList())) {
1477*795d594fSAndroid Build Coastguard Worker     CHECK_EQ(CodeInfo::HasShouldDeoptimizeFlag(stack_map.data()),
1478*795d594fSAndroid Build Coastguard Worker              codegen->GetGraph()->HasShouldDeoptimizeFlag());
1479*795d594fSAndroid Build Coastguard Worker     code_cache->Free(self, region, reserved_code.data(), reserved_data.data());
1480*795d594fSAndroid Build Coastguard Worker     return false;
1481*795d594fSAndroid Build Coastguard Worker   }
1482*795d594fSAndroid Build Coastguard Worker 
1483*795d594fSAndroid Build Coastguard Worker   Runtime::Current()->GetJit()->AddMemoryUsage(method, allocator.BytesUsed());
1484*795d594fSAndroid Build Coastguard Worker   if (jit_logger != nullptr) {
1485*795d594fSAndroid Build Coastguard Worker     jit_logger->WriteLog(code, codegen->GetAssembler()->CodeSize(), method);
1486*795d594fSAndroid Build Coastguard Worker   }
1487*795d594fSAndroid Build Coastguard Worker 
1488*795d594fSAndroid Build Coastguard Worker   if (kArenaAllocatorCountAllocations) {
1489*795d594fSAndroid Build Coastguard Worker     codegen.reset();  // Release codegen's ScopedArenaAllocator for memory accounting.
1490*795d594fSAndroid Build Coastguard Worker     size_t total_allocated = allocator.BytesAllocated() + arena_stack.PeakBytesAllocated();
1491*795d594fSAndroid Build Coastguard Worker     if (total_allocated > kArenaAllocatorMemoryReportThreshold) {
1492*795d594fSAndroid Build Coastguard Worker       MemStats mem_stats(allocator.GetMemStats());
1493*795d594fSAndroid Build Coastguard Worker       MemStats peak_stats(arena_stack.GetPeakStats());
1494*795d594fSAndroid Build Coastguard Worker       LOG(INFO) << "Used " << total_allocated << " bytes of arena memory for compiling "
1495*795d594fSAndroid Build Coastguard Worker                 << dex_file->PrettyMethod(method_idx)
1496*795d594fSAndroid Build Coastguard Worker                 << "\n" << Dumpable<MemStats>(mem_stats)
1497*795d594fSAndroid Build Coastguard Worker                 << "\n" << Dumpable<MemStats>(peak_stats);
1498*795d594fSAndroid Build Coastguard Worker     }
1499*795d594fSAndroid Build Coastguard Worker   }
1500*795d594fSAndroid Build Coastguard Worker 
1501*795d594fSAndroid Build Coastguard Worker   return true;
1502*795d594fSAndroid Build Coastguard Worker }
1503*795d594fSAndroid Build Coastguard Worker 
GenerateJitDebugInfo(const debug::MethodDebugInfo & info)1504*795d594fSAndroid Build Coastguard Worker std::vector<uint8_t> OptimizingCompiler::GenerateJitDebugInfo(const debug::MethodDebugInfo& info) {
1505*795d594fSAndroid Build Coastguard Worker   const CompilerOptions& compiler_options = GetCompilerOptions();
1506*795d594fSAndroid Build Coastguard Worker   if (compiler_options.GenerateAnyDebugInfo()) {
1507*795d594fSAndroid Build Coastguard Worker     // If both flags are passed, generate full debug info.
1508*795d594fSAndroid Build Coastguard Worker     const bool mini_debug_info = !compiler_options.GetGenerateDebugInfo();
1509*795d594fSAndroid Build Coastguard Worker 
1510*795d594fSAndroid Build Coastguard Worker     // Create entry for the single method that we just compiled.
1511*795d594fSAndroid Build Coastguard Worker     InstructionSet isa = compiler_options.GetInstructionSet();
1512*795d594fSAndroid Build Coastguard Worker     const InstructionSetFeatures* features = compiler_options.GetInstructionSetFeatures();
1513*795d594fSAndroid Build Coastguard Worker     return debug::MakeElfFileForJIT(isa, features, mini_debug_info, info);
1514*795d594fSAndroid Build Coastguard Worker   }
1515*795d594fSAndroid Build Coastguard Worker   return std::vector<uint8_t>();
1516*795d594fSAndroid Build Coastguard Worker }
1517*795d594fSAndroid Build Coastguard Worker 
1518*795d594fSAndroid Build Coastguard Worker }  // namespace art
1519