• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "code_generator.h"
18 #include "base/globals.h"
19 
20 #ifdef ART_ENABLE_CODEGEN_arm
21 #include "code_generator_arm_vixl.h"
22 #endif
23 
24 #ifdef ART_ENABLE_CODEGEN_arm64
25 #include "code_generator_arm64.h"
26 #endif
27 
28 #ifdef ART_ENABLE_CODEGEN_riscv64
29 #include "code_generator_riscv64.h"
30 #endif
31 
32 #ifdef ART_ENABLE_CODEGEN_x86
33 #include "code_generator_x86.h"
34 #endif
35 
36 #ifdef ART_ENABLE_CODEGEN_x86_64
37 #include "code_generator_x86_64.h"
38 #endif
39 
40 #include "art_method-inl.h"
41 #include "base/bit_utils.h"
42 #include "base/bit_utils_iterator.h"
43 #include "base/casts.h"
44 #include "base/leb128.h"
45 #include "class_linker.h"
46 #include "class_root-inl.h"
47 #include "dex/bytecode_utils.h"
48 #include "dex/code_item_accessors-inl.h"
49 #include "graph_visualizer.h"
50 #include "image.h"
51 #include "gc/space/image_space.h"
52 #include "intern_table.h"
53 #include "intrinsics.h"
54 #include "mirror/array-inl.h"
55 #include "mirror/object_array-inl.h"
56 #include "mirror/object_reference.h"
57 #include "mirror/reference.h"
58 #include "mirror/string.h"
59 #include "parallel_move_resolver.h"
60 #include "scoped_thread_state_change-inl.h"
61 #include "ssa_liveness_analysis.h"
62 #include "stack_map.h"
63 #include "stack_map_stream.h"
64 #include "string_builder_append.h"
65 #include "thread-current-inl.h"
66 #include "utils/assembler.h"
67 
68 namespace art HIDDEN {
69 
70 // Return whether a location is consistent with a type.
CheckType(DataType::Type type,Location location)71 static bool CheckType(DataType::Type type, Location location) {
72   if (location.IsFpuRegister()
73       || (location.IsUnallocated() && (location.GetPolicy() == Location::kRequiresFpuRegister))) {
74     return (type == DataType::Type::kFloat32) || (type == DataType::Type::kFloat64);
75   } else if (location.IsRegister() ||
76              (location.IsUnallocated() && (location.GetPolicy() == Location::kRequiresRegister))) {
77     return DataType::IsIntegralType(type) || (type == DataType::Type::kReference);
78   } else if (location.IsRegisterPair()) {
79     return type == DataType::Type::kInt64;
80   } else if (location.IsFpuRegisterPair()) {
81     return type == DataType::Type::kFloat64;
82   } else if (location.IsStackSlot()) {
83     return (DataType::IsIntegralType(type) && type != DataType::Type::kInt64)
84            || (type == DataType::Type::kFloat32)
85            || (type == DataType::Type::kReference);
86   } else if (location.IsDoubleStackSlot()) {
87     return (type == DataType::Type::kInt64) || (type == DataType::Type::kFloat64);
88   } else if (location.IsConstant()) {
89     if (location.GetConstant()->IsIntConstant()) {
90       return DataType::IsIntegralType(type) && (type != DataType::Type::kInt64);
91     } else if (location.GetConstant()->IsNullConstant()) {
92       return type == DataType::Type::kReference;
93     } else if (location.GetConstant()->IsLongConstant()) {
94       return type == DataType::Type::kInt64;
95     } else if (location.GetConstant()->IsFloatConstant()) {
96       return type == DataType::Type::kFloat32;
97     } else {
98       return location.GetConstant()->IsDoubleConstant()
99           && (type == DataType::Type::kFloat64);
100     }
101   } else {
102     return location.IsInvalid() || (location.GetPolicy() == Location::kAny);
103   }
104 }
105 
106 // Check that a location summary is consistent with an instruction.
CheckTypeConsistency(HInstruction * instruction)107 static bool CheckTypeConsistency(HInstruction* instruction) {
108   LocationSummary* locations = instruction->GetLocations();
109   if (locations == nullptr) {
110     return true;
111   }
112 
113   if (locations->Out().IsUnallocated()
114       && (locations->Out().GetPolicy() == Location::kSameAsFirstInput)) {
115     DCHECK(CheckType(instruction->GetType(), locations->InAt(0)))
116         << instruction->GetType()
117         << " " << locations->InAt(0);
118   } else {
119     DCHECK(CheckType(instruction->GetType(), locations->Out()))
120         << instruction->GetType()
121         << " " << locations->Out();
122   }
123 
124   HConstInputsRef inputs = instruction->GetInputs();
125   for (size_t i = 0; i < inputs.size(); ++i) {
126     DCHECK(CheckType(inputs[i]->GetType(), locations->InAt(i)))
127       << inputs[i]->GetType() << " " << locations->InAt(i);
128   }
129 
130   HEnvironment* environment = instruction->GetEnvironment();
131   for (size_t i = 0; i < instruction->EnvironmentSize(); ++i) {
132     if (environment->GetInstructionAt(i) != nullptr) {
133       DataType::Type type = environment->GetInstructionAt(i)->GetType();
134       DCHECK(CheckType(type, environment->GetLocationAt(i)))
135         << type << " " << environment->GetLocationAt(i);
136     } else {
137       DCHECK(environment->GetLocationAt(i).IsInvalid())
138         << environment->GetLocationAt(i);
139     }
140   }
141   return true;
142 }
143 
144 class CodeGenerator::CodeGenerationData : public DeletableArenaObject<kArenaAllocCodeGenerator> {
145  public:
Create(ArenaStack * arena_stack,InstructionSet instruction_set)146   static std::unique_ptr<CodeGenerationData> Create(ArenaStack* arena_stack,
147                                                     InstructionSet instruction_set) {
148     ScopedArenaAllocator allocator(arena_stack);
149     void* memory = allocator.Alloc<CodeGenerationData>(kArenaAllocCodeGenerator);
150     return std::unique_ptr<CodeGenerationData>(
151         ::new (memory) CodeGenerationData(std::move(allocator), instruction_set));
152   }
153 
GetScopedAllocator()154   ScopedArenaAllocator* GetScopedAllocator() {
155     return &allocator_;
156   }
157 
AddSlowPath(SlowPathCode * slow_path)158   void AddSlowPath(SlowPathCode* slow_path) {
159     slow_paths_.emplace_back(std::unique_ptr<SlowPathCode>(slow_path));
160   }
161 
GetSlowPaths() const162   ArrayRef<const std::unique_ptr<SlowPathCode>> GetSlowPaths() const {
163     return ArrayRef<const std::unique_ptr<SlowPathCode>>(slow_paths_);
164   }
165 
GetStackMapStream()166   StackMapStream* GetStackMapStream() { return &stack_map_stream_; }
167 
ReserveJitStringRoot(StringReference string_reference,Handle<mirror::String> string)168   void ReserveJitStringRoot(StringReference string_reference, Handle<mirror::String> string) {
169     jit_string_roots_.Overwrite(string_reference,
170                                 reinterpret_cast64<uint64_t>(string.GetReference()));
171   }
172 
GetJitStringRootIndex(StringReference string_reference) const173   uint64_t GetJitStringRootIndex(StringReference string_reference) const {
174     return jit_string_roots_.Get(string_reference);
175   }
176 
GetNumberOfJitStringRoots() const177   size_t GetNumberOfJitStringRoots() const {
178     return jit_string_roots_.size();
179   }
180 
ReserveJitClassRoot(TypeReference type_reference,Handle<mirror::Class> klass)181   void ReserveJitClassRoot(TypeReference type_reference, Handle<mirror::Class> klass) {
182     jit_class_roots_.Overwrite(type_reference, reinterpret_cast64<uint64_t>(klass.GetReference()));
183   }
184 
GetJitClassRootIndex(TypeReference type_reference) const185   uint64_t GetJitClassRootIndex(TypeReference type_reference) const {
186     return jit_class_roots_.Get(type_reference);
187   }
188 
GetNumberOfJitClassRoots() const189   size_t GetNumberOfJitClassRoots() const {
190     return jit_class_roots_.size();
191   }
192 
GetNumberOfJitRoots() const193   size_t GetNumberOfJitRoots() const {
194     return GetNumberOfJitStringRoots() + GetNumberOfJitClassRoots();
195   }
196 
197   void EmitJitRoots(/*out*/std::vector<Handle<mirror::Object>>* roots)
198       REQUIRES_SHARED(Locks::mutator_lock_);
199 
200  private:
CodeGenerationData(ScopedArenaAllocator && allocator,InstructionSet instruction_set)201   CodeGenerationData(ScopedArenaAllocator&& allocator, InstructionSet instruction_set)
202       : allocator_(std::move(allocator)),
203         stack_map_stream_(&allocator_, instruction_set),
204         slow_paths_(allocator_.Adapter(kArenaAllocCodeGenerator)),
205         jit_string_roots_(StringReferenceValueComparator(),
206                           allocator_.Adapter(kArenaAllocCodeGenerator)),
207         jit_class_roots_(TypeReferenceValueComparator(),
208                          allocator_.Adapter(kArenaAllocCodeGenerator)) {
209     slow_paths_.reserve(kDefaultSlowPathsCapacity);
210   }
211 
212   static constexpr size_t kDefaultSlowPathsCapacity = 8;
213 
214   ScopedArenaAllocator allocator_;
215   StackMapStream stack_map_stream_;
216   ScopedArenaVector<std::unique_ptr<SlowPathCode>> slow_paths_;
217 
218   // Maps a StringReference (dex_file, string_index) to the index in the literal table.
219   // Entries are intially added with a pointer in the handle zone, and `EmitJitRoots`
220   // will compute all the indices.
221   ScopedArenaSafeMap<StringReference, uint64_t, StringReferenceValueComparator> jit_string_roots_;
222 
223   // Maps a ClassReference (dex_file, type_index) to the index in the literal table.
224   // Entries are intially added with a pointer in the handle zone, and `EmitJitRoots`
225   // will compute all the indices.
226   ScopedArenaSafeMap<TypeReference, uint64_t, TypeReferenceValueComparator> jit_class_roots_;
227 };
228 
EmitJitRoots(std::vector<Handle<mirror::Object>> * roots)229 void CodeGenerator::CodeGenerationData::EmitJitRoots(
230     /*out*/std::vector<Handle<mirror::Object>>* roots) {
231   DCHECK(roots->empty());
232   roots->reserve(GetNumberOfJitRoots());
233   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
234   size_t index = 0;
235   for (auto& entry : jit_string_roots_) {
236     // Update the `roots` with the string, and replace the address temporarily
237     // stored to the index in the table.
238     uint64_t address = entry.second;
239     roots->emplace_back(reinterpret_cast<StackReference<mirror::Object>*>(address));
240     DCHECK(roots->back() != nullptr);
241     DCHECK(roots->back()->IsString());
242     entry.second = index;
243     // Ensure the string is strongly interned. This is a requirement on how the JIT
244     // handles strings. b/32995596
245     class_linker->GetInternTable()->InternStrong(roots->back()->AsString());
246     ++index;
247   }
248   for (auto& entry : jit_class_roots_) {
249     // Update the `roots` with the class, and replace the address temporarily
250     // stored to the index in the table.
251     uint64_t address = entry.second;
252     roots->emplace_back(reinterpret_cast<StackReference<mirror::Object>*>(address));
253     DCHECK(roots->back() != nullptr);
254     DCHECK(roots->back()->IsClass());
255     entry.second = index;
256     ++index;
257   }
258 }
259 
GetScopedAllocator()260 ScopedArenaAllocator* CodeGenerator::GetScopedAllocator() {
261   DCHECK(code_generation_data_ != nullptr);
262   return code_generation_data_->GetScopedAllocator();
263 }
264 
GetStackMapStream()265 StackMapStream* CodeGenerator::GetStackMapStream() {
266   DCHECK(code_generation_data_ != nullptr);
267   return code_generation_data_->GetStackMapStream();
268 }
269 
ReserveJitStringRoot(StringReference string_reference,Handle<mirror::String> string)270 void CodeGenerator::ReserveJitStringRoot(StringReference string_reference,
271                                          Handle<mirror::String> string) {
272   DCHECK(code_generation_data_ != nullptr);
273   code_generation_data_->ReserveJitStringRoot(string_reference, string);
274 }
275 
GetJitStringRootIndex(StringReference string_reference)276 uint64_t CodeGenerator::GetJitStringRootIndex(StringReference string_reference) {
277   DCHECK(code_generation_data_ != nullptr);
278   return code_generation_data_->GetJitStringRootIndex(string_reference);
279 }
280 
ReserveJitClassRoot(TypeReference type_reference,Handle<mirror::Class> klass)281 void CodeGenerator::ReserveJitClassRoot(TypeReference type_reference, Handle<mirror::Class> klass) {
282   DCHECK(code_generation_data_ != nullptr);
283   code_generation_data_->ReserveJitClassRoot(type_reference, klass);
284 }
285 
GetJitClassRootIndex(TypeReference type_reference)286 uint64_t CodeGenerator::GetJitClassRootIndex(TypeReference type_reference) {
287   DCHECK(code_generation_data_ != nullptr);
288   return code_generation_data_->GetJitClassRootIndex(type_reference);
289 }
290 
EmitJitRootPatches(uint8_t * code ATTRIBUTE_UNUSED,const uint8_t * roots_data ATTRIBUTE_UNUSED)291 void CodeGenerator::EmitJitRootPatches(uint8_t* code ATTRIBUTE_UNUSED,
292                                        const uint8_t* roots_data ATTRIBUTE_UNUSED) {
293   DCHECK(code_generation_data_ != nullptr);
294   DCHECK_EQ(code_generation_data_->GetNumberOfJitStringRoots(), 0u);
295   DCHECK_EQ(code_generation_data_->GetNumberOfJitClassRoots(), 0u);
296 }
297 
GetArrayLengthOffset(HArrayLength * array_length)298 uint32_t CodeGenerator::GetArrayLengthOffset(HArrayLength* array_length) {
299   return array_length->IsStringLength()
300       ? mirror::String::CountOffset().Uint32Value()
301       : mirror::Array::LengthOffset().Uint32Value();
302 }
303 
GetArrayDataOffset(HArrayGet * array_get)304 uint32_t CodeGenerator::GetArrayDataOffset(HArrayGet* array_get) {
305   DCHECK(array_get->GetType() == DataType::Type::kUint16 || !array_get->IsStringCharAt());
306   return array_get->IsStringCharAt()
307       ? mirror::String::ValueOffset().Uint32Value()
308       : mirror::Array::DataOffset(DataType::Size(array_get->GetType())).Uint32Value();
309 }
310 
GoesToNextBlock(HBasicBlock * current,HBasicBlock * next) const311 bool CodeGenerator::GoesToNextBlock(HBasicBlock* current, HBasicBlock* next) const {
312   DCHECK_EQ((*block_order_)[current_block_index_], current);
313   return GetNextBlockToEmit() == FirstNonEmptyBlock(next);
314 }
315 
GetNextBlockToEmit() const316 HBasicBlock* CodeGenerator::GetNextBlockToEmit() const {
317   for (size_t i = current_block_index_ + 1; i < block_order_->size(); ++i) {
318     HBasicBlock* block = (*block_order_)[i];
319     if (!block->IsSingleJump()) {
320       return block;
321     }
322   }
323   return nullptr;
324 }
325 
FirstNonEmptyBlock(HBasicBlock * block) const326 HBasicBlock* CodeGenerator::FirstNonEmptyBlock(HBasicBlock* block) const {
327   while (block->IsSingleJump()) {
328     block = block->GetSuccessors()[0];
329   }
330   return block;
331 }
332 
333 class DisassemblyScope {
334  public:
DisassemblyScope(HInstruction * instruction,const CodeGenerator & codegen)335   DisassemblyScope(HInstruction* instruction, const CodeGenerator& codegen)
336       : codegen_(codegen), instruction_(instruction), start_offset_(static_cast<size_t>(-1)) {
337     if (codegen_.GetDisassemblyInformation() != nullptr) {
338       start_offset_ = codegen_.GetAssembler().CodeSize();
339     }
340   }
341 
~DisassemblyScope()342   ~DisassemblyScope() {
343     // We avoid building this data when we know it will not be used.
344     if (codegen_.GetDisassemblyInformation() != nullptr) {
345       codegen_.GetDisassemblyInformation()->AddInstructionInterval(
346           instruction_, start_offset_, codegen_.GetAssembler().CodeSize());
347     }
348   }
349 
350  private:
351   const CodeGenerator& codegen_;
352   HInstruction* instruction_;
353   size_t start_offset_;
354 };
355 
356 
GenerateSlowPaths()357 void CodeGenerator::GenerateSlowPaths() {
358   DCHECK(code_generation_data_ != nullptr);
359   size_t code_start = 0;
360   for (const std::unique_ptr<SlowPathCode>& slow_path_ptr : code_generation_data_->GetSlowPaths()) {
361     SlowPathCode* slow_path = slow_path_ptr.get();
362     current_slow_path_ = slow_path;
363     if (disasm_info_ != nullptr) {
364       code_start = GetAssembler()->CodeSize();
365     }
366     // Record the dex pc at start of slow path (required for java line number mapping).
367     MaybeRecordNativeDebugInfo(slow_path->GetInstruction(), slow_path->GetDexPc(), slow_path);
368     slow_path->EmitNativeCode(this);
369     if (disasm_info_ != nullptr) {
370       disasm_info_->AddSlowPathInterval(slow_path, code_start, GetAssembler()->CodeSize());
371     }
372   }
373   current_slow_path_ = nullptr;
374 }
375 
InitializeCodeGenerationData()376 void CodeGenerator::InitializeCodeGenerationData() {
377   DCHECK(code_generation_data_ == nullptr);
378   code_generation_data_ = CodeGenerationData::Create(graph_->GetArenaStack(), GetInstructionSet());
379 }
380 
Compile(CodeAllocator * allocator)381 void CodeGenerator::Compile(CodeAllocator* allocator) {
382   InitializeCodeGenerationData();
383 
384   // The register allocator already called `InitializeCodeGeneration`,
385   // where the frame size has been computed.
386   DCHECK(block_order_ != nullptr);
387   Initialize();
388 
389   HGraphVisitor* instruction_visitor = GetInstructionVisitor();
390   DCHECK_EQ(current_block_index_, 0u);
391 
392   GetStackMapStream()->BeginMethod(HasEmptyFrame() ? 0 : frame_size_,
393                                    core_spill_mask_,
394                                    fpu_spill_mask_,
395                                    GetGraph()->GetNumberOfVRegs(),
396                                    GetGraph()->IsCompilingBaseline(),
397                                    GetGraph()->IsDebuggable());
398 
399   size_t frame_start = GetAssembler()->CodeSize();
400   GenerateFrameEntry();
401   DCHECK_EQ(GetAssembler()->cfi().GetCurrentCFAOffset(), static_cast<int>(frame_size_));
402   if (disasm_info_ != nullptr) {
403     disasm_info_->SetFrameEntryInterval(frame_start, GetAssembler()->CodeSize());
404   }
405 
406   for (size_t e = block_order_->size(); current_block_index_ < e; ++current_block_index_) {
407     HBasicBlock* block = (*block_order_)[current_block_index_];
408     // Don't generate code for an empty block. Its predecessors will branch to its successor
409     // directly. Also, the label of that block will not be emitted, so this helps catch
410     // errors where we reference that label.
411     if (block->IsSingleJump()) continue;
412     Bind(block);
413     // This ensures that we have correct native line mapping for all native instructions.
414     // It is necessary to make stepping over a statement work. Otherwise, any initial
415     // instructions (e.g. moves) would be assumed to be the start of next statement.
416     MaybeRecordNativeDebugInfo(/* instruction= */ nullptr, block->GetDexPc());
417     for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
418       HInstruction* current = it.Current();
419       if (current->HasEnvironment()) {
420         // Catch StackMaps are dealt with later on in `RecordCatchBlockInfo`.
421         if (block->IsCatchBlock() && block->GetFirstInstruction() == current) {
422           DCHECK(current->IsNop());
423           continue;
424         }
425 
426         // Create stackmap for HNop or any instruction which calls native code.
427         // Note that we need correct mapping for the native PC of the call instruction,
428         // so the runtime's stackmap is not sufficient since it is at PC after the call.
429         MaybeRecordNativeDebugInfo(current, block->GetDexPc());
430       }
431       DisassemblyScope disassembly_scope(current, *this);
432       DCHECK(CheckTypeConsistency(current));
433       current->Accept(instruction_visitor);
434     }
435   }
436 
437   GenerateSlowPaths();
438 
439   // Emit catch stack maps at the end of the stack map stream as expected by the
440   // runtime exception handler.
441   if (graph_->HasTryCatch()) {
442     RecordCatchBlockInfo();
443   }
444 
445   // Finalize instructions in assember;
446   Finalize(allocator);
447 
448   GetStackMapStream()->EndMethod(GetAssembler()->CodeSize());
449 }
450 
Finalize(CodeAllocator * allocator)451 void CodeGenerator::Finalize(CodeAllocator* allocator) {
452   size_t code_size = GetAssembler()->CodeSize();
453   uint8_t* buffer = allocator->Allocate(code_size);
454 
455   MemoryRegion code(buffer, code_size);
456   GetAssembler()->FinalizeInstructions(code);
457 }
458 
EmitLinkerPatches(ArenaVector<linker::LinkerPatch> * linker_patches ATTRIBUTE_UNUSED)459 void CodeGenerator::EmitLinkerPatches(
460     ArenaVector<linker::LinkerPatch>* linker_patches ATTRIBUTE_UNUSED) {
461   // No linker patches by default.
462 }
463 
NeedsThunkCode(const linker::LinkerPatch & patch ATTRIBUTE_UNUSED) const464 bool CodeGenerator::NeedsThunkCode(const linker::LinkerPatch& patch ATTRIBUTE_UNUSED) const {
465   // Code generators that create patches requiring thunk compilation should override this function.
466   return false;
467 }
468 
EmitThunkCode(const linker::LinkerPatch & patch ATTRIBUTE_UNUSED,ArenaVector<uint8_t> * code ATTRIBUTE_UNUSED,std::string * debug_name ATTRIBUTE_UNUSED)469 void CodeGenerator::EmitThunkCode(const linker::LinkerPatch& patch ATTRIBUTE_UNUSED,
470                                   /*out*/ ArenaVector<uint8_t>* code ATTRIBUTE_UNUSED,
471                                   /*out*/ std::string* debug_name ATTRIBUTE_UNUSED) {
472   // Code generators that create patches requiring thunk compilation should override this function.
473   LOG(FATAL) << "Unexpected call to EmitThunkCode().";
474 }
475 
InitializeCodeGeneration(size_t number_of_spill_slots,size_t maximum_safepoint_spill_size,size_t number_of_out_slots,const ArenaVector<HBasicBlock * > & block_order)476 void CodeGenerator::InitializeCodeGeneration(size_t number_of_spill_slots,
477                                              size_t maximum_safepoint_spill_size,
478                                              size_t number_of_out_slots,
479                                              const ArenaVector<HBasicBlock*>& block_order) {
480   block_order_ = &block_order;
481   DCHECK(!block_order.empty());
482   DCHECK(block_order[0] == GetGraph()->GetEntryBlock());
483   ComputeSpillMask();
484   first_register_slot_in_slow_path_ = RoundUp(
485       (number_of_out_slots + number_of_spill_slots) * kVRegSize, GetPreferredSlotsAlignment());
486 
487   if (number_of_spill_slots == 0
488       && !HasAllocatedCalleeSaveRegisters()
489       && IsLeafMethod()
490       && !RequiresCurrentMethod()) {
491     DCHECK_EQ(maximum_safepoint_spill_size, 0u);
492     SetFrameSize(CallPushesPC() ? GetWordSize() : 0);
493   } else {
494     SetFrameSize(RoundUp(
495         first_register_slot_in_slow_path_
496         + maximum_safepoint_spill_size
497         + (GetGraph()->HasShouldDeoptimizeFlag() ? kShouldDeoptimizeFlagSize : 0)
498         + FrameEntrySpillSize(),
499         kStackAlignment));
500   }
501 }
502 
CreateCommonInvokeLocationSummary(HInvoke * invoke,InvokeDexCallingConventionVisitor * visitor)503 void CodeGenerator::CreateCommonInvokeLocationSummary(
504     HInvoke* invoke, InvokeDexCallingConventionVisitor* visitor) {
505   ArenaAllocator* allocator = invoke->GetBlock()->GetGraph()->GetAllocator();
506   LocationSummary* locations = new (allocator) LocationSummary(invoke,
507                                                                LocationSummary::kCallOnMainOnly);
508 
509   for (size_t i = 0; i < invoke->GetNumberOfArguments(); i++) {
510     HInstruction* input = invoke->InputAt(i);
511     locations->SetInAt(i, visitor->GetNextLocation(input->GetType()));
512   }
513 
514   locations->SetOut(visitor->GetReturnLocation(invoke->GetType()));
515 
516   if (invoke->IsInvokeStaticOrDirect()) {
517     HInvokeStaticOrDirect* call = invoke->AsInvokeStaticOrDirect();
518     MethodLoadKind method_load_kind = call->GetMethodLoadKind();
519     CodePtrLocation code_ptr_location = call->GetCodePtrLocation();
520     if (code_ptr_location == CodePtrLocation::kCallCriticalNative) {
521       locations->AddTemp(Location::RequiresRegister());  // For target method.
522     }
523     if (code_ptr_location == CodePtrLocation::kCallCriticalNative ||
524         method_load_kind == MethodLoadKind::kRecursive) {
525       // For `kCallCriticalNative` we need the current method as the hidden argument
526       // if we reach the dlsym lookup stub for @CriticalNative.
527       locations->SetInAt(call->GetCurrentMethodIndex(), visitor->GetMethodLocation());
528     } else {
529       locations->AddTemp(visitor->GetMethodLocation());
530       if (method_load_kind == MethodLoadKind::kRuntimeCall) {
531         locations->SetInAt(call->GetCurrentMethodIndex(), Location::RequiresRegister());
532       }
533     }
534   } else if (!invoke->IsInvokePolymorphic()) {
535     locations->AddTemp(visitor->GetMethodLocation());
536   }
537 }
538 
PrepareCriticalNativeArgumentMoves(HInvokeStaticOrDirect * invoke,InvokeDexCallingConventionVisitor * visitor,HParallelMove * parallel_move)539 void CodeGenerator::PrepareCriticalNativeArgumentMoves(
540     HInvokeStaticOrDirect* invoke,
541     /*inout*/InvokeDexCallingConventionVisitor* visitor,
542     /*out*/HParallelMove* parallel_move) {
543   LocationSummary* locations = invoke->GetLocations();
544   for (size_t i = 0, num = invoke->GetNumberOfArguments(); i != num; ++i) {
545     Location in_location = locations->InAt(i);
546     DataType::Type type = invoke->InputAt(i)->GetType();
547     DCHECK_NE(type, DataType::Type::kReference);
548     Location out_location = visitor->GetNextLocation(type);
549     if (out_location.IsStackSlot() || out_location.IsDoubleStackSlot()) {
550       // Stack arguments will need to be moved after adjusting the SP.
551       parallel_move->AddMove(in_location, out_location, type, /*instruction=*/ nullptr);
552     } else {
553       // Register arguments should have been assigned their final locations for register allocation.
554       DCHECK(out_location.Equals(in_location)) << in_location << " -> " << out_location;
555     }
556   }
557 }
558 
FinishCriticalNativeFrameSetup(size_t out_frame_size,HParallelMove * parallel_move)559 void CodeGenerator::FinishCriticalNativeFrameSetup(size_t out_frame_size,
560                                                    /*inout*/HParallelMove* parallel_move) {
561   DCHECK_NE(out_frame_size, 0u);
562   IncreaseFrame(out_frame_size);
563   // Adjust the source stack offsets by `out_frame_size`, i.e. the additional
564   // frame size needed for outgoing stack arguments.
565   for (size_t i = 0, num = parallel_move->NumMoves(); i != num; ++i) {
566     MoveOperands* operands = parallel_move->MoveOperandsAt(i);
567     Location source = operands->GetSource();
568     if (operands->GetSource().IsStackSlot()) {
569       operands->SetSource(Location::StackSlot(source.GetStackIndex() +  out_frame_size));
570     } else if (operands->GetSource().IsDoubleStackSlot()) {
571       operands->SetSource(Location::DoubleStackSlot(source.GetStackIndex() +  out_frame_size));
572     }
573   }
574   // Emit the moves.
575   GetMoveResolver()->EmitNativeCode(parallel_move);
576 }
577 
GetCriticalNativeShorty(HInvokeStaticOrDirect * invoke,uint32_t * shorty_len)578 const char* CodeGenerator::GetCriticalNativeShorty(HInvokeStaticOrDirect* invoke,
579                                                    uint32_t* shorty_len) {
580   ScopedObjectAccess soa(Thread::Current());
581   DCHECK(invoke->GetResolvedMethod()->IsCriticalNative());
582   return invoke->GetResolvedMethod()->GetShorty(shorty_len);
583 }
584 
GenerateInvokeStaticOrDirectRuntimeCall(HInvokeStaticOrDirect * invoke,Location temp,SlowPathCode * slow_path)585 void CodeGenerator::GenerateInvokeStaticOrDirectRuntimeCall(
586     HInvokeStaticOrDirect* invoke, Location temp, SlowPathCode* slow_path) {
587   MethodReference method_reference(invoke->GetMethodReference());
588   MoveConstant(temp, method_reference.index);
589 
590   // The access check is unnecessary but we do not want to introduce
591   // extra entrypoints for the codegens that do not support some
592   // invoke type and fall back to the runtime call.
593 
594   // Initialize to anything to silent compiler warnings.
595   QuickEntrypointEnum entrypoint = kQuickInvokeStaticTrampolineWithAccessCheck;
596   switch (invoke->GetInvokeType()) {
597     case kStatic:
598       entrypoint = kQuickInvokeStaticTrampolineWithAccessCheck;
599       break;
600     case kDirect:
601       entrypoint = kQuickInvokeDirectTrampolineWithAccessCheck;
602       break;
603     case kSuper:
604       entrypoint = kQuickInvokeSuperTrampolineWithAccessCheck;
605       break;
606     case kVirtual:
607     case kInterface:
608     case kPolymorphic:
609     case kCustom:
610       LOG(FATAL) << "Unexpected invoke type: " << invoke->GetInvokeType();
611       UNREACHABLE();
612   }
613 
614   InvokeRuntime(entrypoint, invoke, invoke->GetDexPc(), slow_path);
615 }
GenerateInvokeUnresolvedRuntimeCall(HInvokeUnresolved * invoke)616 void CodeGenerator::GenerateInvokeUnresolvedRuntimeCall(HInvokeUnresolved* invoke) {
617   MethodReference method_reference(invoke->GetMethodReference());
618   MoveConstant(invoke->GetLocations()->GetTemp(0), method_reference.index);
619 
620   // Initialize to anything to silent compiler warnings.
621   QuickEntrypointEnum entrypoint = kQuickInvokeStaticTrampolineWithAccessCheck;
622   switch (invoke->GetInvokeType()) {
623     case kStatic:
624       entrypoint = kQuickInvokeStaticTrampolineWithAccessCheck;
625       break;
626     case kDirect:
627       entrypoint = kQuickInvokeDirectTrampolineWithAccessCheck;
628       break;
629     case kVirtual:
630       entrypoint = kQuickInvokeVirtualTrampolineWithAccessCheck;
631       break;
632     case kSuper:
633       entrypoint = kQuickInvokeSuperTrampolineWithAccessCheck;
634       break;
635     case kInterface:
636       entrypoint = kQuickInvokeInterfaceTrampolineWithAccessCheck;
637       break;
638     case kPolymorphic:
639     case kCustom:
640       LOG(FATAL) << "Unexpected invoke type: " << invoke->GetInvokeType();
641       UNREACHABLE();
642   }
643   InvokeRuntime(entrypoint, invoke, invoke->GetDexPc(), nullptr);
644 }
645 
GenerateInvokePolymorphicCall(HInvokePolymorphic * invoke,SlowPathCode * slow_path)646 void CodeGenerator::GenerateInvokePolymorphicCall(HInvokePolymorphic* invoke,
647                                                   SlowPathCode* slow_path) {
648   // invoke-polymorphic does not use a temporary to convey any additional information (e.g. a
649   // method index) since it requires multiple info from the instruction (registers A, B, H). Not
650   // using the reservation has no effect on the registers used in the runtime call.
651   QuickEntrypointEnum entrypoint = kQuickInvokePolymorphic;
652   InvokeRuntime(entrypoint, invoke, invoke->GetDexPc(), slow_path);
653 }
654 
GenerateInvokeCustomCall(HInvokeCustom * invoke)655 void CodeGenerator::GenerateInvokeCustomCall(HInvokeCustom* invoke) {
656   MoveConstant(invoke->GetLocations()->GetTemp(0), invoke->GetCallSiteIndex());
657   QuickEntrypointEnum entrypoint = kQuickInvokeCustom;
658   InvokeRuntime(entrypoint, invoke, invoke->GetDexPc(), nullptr);
659 }
660 
CreateStringBuilderAppendLocations(HStringBuilderAppend * instruction,Location out)661 void CodeGenerator::CreateStringBuilderAppendLocations(HStringBuilderAppend* instruction,
662                                                        Location out) {
663   ArenaAllocator* allocator = GetGraph()->GetAllocator();
664   LocationSummary* locations =
665       new (allocator) LocationSummary(instruction, LocationSummary::kCallOnMainOnly);
666   locations->SetOut(out);
667   instruction->GetLocations()->SetInAt(instruction->FormatIndex(),
668                                        Location::ConstantLocation(instruction->GetFormat()));
669 
670   uint32_t format = static_cast<uint32_t>(instruction->GetFormat()->GetValue());
671   uint32_t f = format;
672   PointerSize pointer_size = InstructionSetPointerSize(GetInstructionSet());
673   size_t stack_offset = static_cast<size_t>(pointer_size);  // Start after the ArtMethod*.
674   for (size_t i = 0, num_args = instruction->GetNumberOfArguments(); i != num_args; ++i) {
675     StringBuilderAppend::Argument arg_type =
676         static_cast<StringBuilderAppend::Argument>(f & StringBuilderAppend::kArgMask);
677     switch (arg_type) {
678       case StringBuilderAppend::Argument::kStringBuilder:
679       case StringBuilderAppend::Argument::kString:
680       case StringBuilderAppend::Argument::kCharArray:
681         static_assert(sizeof(StackReference<mirror::Object>) == sizeof(uint32_t), "Size check.");
682         FALLTHROUGH_INTENDED;
683       case StringBuilderAppend::Argument::kBoolean:
684       case StringBuilderAppend::Argument::kChar:
685       case StringBuilderAppend::Argument::kInt:
686       case StringBuilderAppend::Argument::kFloat:
687         locations->SetInAt(i, Location::StackSlot(stack_offset));
688         break;
689       case StringBuilderAppend::Argument::kLong:
690       case StringBuilderAppend::Argument::kDouble:
691         stack_offset = RoundUp(stack_offset, sizeof(uint64_t));
692         locations->SetInAt(i, Location::DoubleStackSlot(stack_offset));
693         // Skip the low word, let the common code skip the high word.
694         stack_offset += sizeof(uint32_t);
695         break;
696       default:
697         LOG(FATAL) << "Unexpected arg format: 0x" << std::hex
698             << (f & StringBuilderAppend::kArgMask) << " full format: 0x" << format;
699         UNREACHABLE();
700     }
701     f >>= StringBuilderAppend::kBitsPerArg;
702     stack_offset += sizeof(uint32_t);
703   }
704   DCHECK_EQ(f, 0u);
705 
706   size_t param_size = stack_offset - static_cast<size_t>(pointer_size);
707   DCHECK_ALIGNED(param_size, kVRegSize);
708   size_t num_vregs = param_size / kVRegSize;
709   graph_->UpdateMaximumNumberOfOutVRegs(num_vregs);
710 }
711 
CreateUnresolvedFieldLocationSummary(HInstruction * field_access,DataType::Type field_type,const FieldAccessCallingConvention & calling_convention)712 void CodeGenerator::CreateUnresolvedFieldLocationSummary(
713     HInstruction* field_access,
714     DataType::Type field_type,
715     const FieldAccessCallingConvention& calling_convention) {
716   bool is_instance = field_access->IsUnresolvedInstanceFieldGet()
717       || field_access->IsUnresolvedInstanceFieldSet();
718   bool is_get = field_access->IsUnresolvedInstanceFieldGet()
719       || field_access->IsUnresolvedStaticFieldGet();
720 
721   ArenaAllocator* allocator = field_access->GetBlock()->GetGraph()->GetAllocator();
722   LocationSummary* locations =
723       new (allocator) LocationSummary(field_access, LocationSummary::kCallOnMainOnly);
724 
725   locations->AddTemp(calling_convention.GetFieldIndexLocation());
726 
727   if (is_instance) {
728     // Add the `this` object for instance field accesses.
729     locations->SetInAt(0, calling_convention.GetObjectLocation());
730   }
731 
732   // Note that pSetXXStatic/pGetXXStatic always takes/returns an int or int64
733   // regardless of the the type. Because of that we forced to special case
734   // the access to floating point values.
735   if (is_get) {
736     if (DataType::IsFloatingPointType(field_type)) {
737       // The return value will be stored in regular registers while register
738       // allocator expects it in a floating point register.
739       // Note We don't need to request additional temps because the return
740       // register(s) are already blocked due the call and they may overlap with
741       // the input or field index.
742       // The transfer between the two will be done at codegen level.
743       locations->SetOut(calling_convention.GetFpuLocation(field_type));
744     } else {
745       locations->SetOut(calling_convention.GetReturnLocation(field_type));
746     }
747   } else {
748      size_t set_index = is_instance ? 1 : 0;
749      if (DataType::IsFloatingPointType(field_type)) {
750       // The set value comes from a float location while the calling convention
751       // expects it in a regular register location. Allocate a temp for it and
752       // make the transfer at codegen.
753       AddLocationAsTemp(calling_convention.GetSetValueLocation(field_type, is_instance), locations);
754       locations->SetInAt(set_index, calling_convention.GetFpuLocation(field_type));
755     } else {
756       locations->SetInAt(set_index,
757           calling_convention.GetSetValueLocation(field_type, is_instance));
758     }
759   }
760 }
761 
GenerateUnresolvedFieldAccess(HInstruction * field_access,DataType::Type field_type,uint32_t field_index,uint32_t dex_pc,const FieldAccessCallingConvention & calling_convention)762 void CodeGenerator::GenerateUnresolvedFieldAccess(
763     HInstruction* field_access,
764     DataType::Type field_type,
765     uint32_t field_index,
766     uint32_t dex_pc,
767     const FieldAccessCallingConvention& calling_convention) {
768   LocationSummary* locations = field_access->GetLocations();
769 
770   MoveConstant(locations->GetTemp(0), field_index);
771 
772   bool is_instance = field_access->IsUnresolvedInstanceFieldGet()
773       || field_access->IsUnresolvedInstanceFieldSet();
774   bool is_get = field_access->IsUnresolvedInstanceFieldGet()
775       || field_access->IsUnresolvedStaticFieldGet();
776 
777   if (!is_get && DataType::IsFloatingPointType(field_type)) {
778     // Copy the float value to be set into the calling convention register.
779     // Note that using directly the temp location is problematic as we don't
780     // support temp register pairs. To avoid boilerplate conversion code, use
781     // the location from the calling convention.
782     MoveLocation(calling_convention.GetSetValueLocation(field_type, is_instance),
783                  locations->InAt(is_instance ? 1 : 0),
784                  (DataType::Is64BitType(field_type) ? DataType::Type::kInt64
785                                                     : DataType::Type::kInt32));
786   }
787 
788   QuickEntrypointEnum entrypoint = kQuickSet8Static;  // Initialize to anything to avoid warnings.
789   switch (field_type) {
790     case DataType::Type::kBool:
791       entrypoint = is_instance
792           ? (is_get ? kQuickGetBooleanInstance : kQuickSet8Instance)
793           : (is_get ? kQuickGetBooleanStatic : kQuickSet8Static);
794       break;
795     case DataType::Type::kInt8:
796       entrypoint = is_instance
797           ? (is_get ? kQuickGetByteInstance : kQuickSet8Instance)
798           : (is_get ? kQuickGetByteStatic : kQuickSet8Static);
799       break;
800     case DataType::Type::kInt16:
801       entrypoint = is_instance
802           ? (is_get ? kQuickGetShortInstance : kQuickSet16Instance)
803           : (is_get ? kQuickGetShortStatic : kQuickSet16Static);
804       break;
805     case DataType::Type::kUint16:
806       entrypoint = is_instance
807           ? (is_get ? kQuickGetCharInstance : kQuickSet16Instance)
808           : (is_get ? kQuickGetCharStatic : kQuickSet16Static);
809       break;
810     case DataType::Type::kInt32:
811     case DataType::Type::kFloat32:
812       entrypoint = is_instance
813           ? (is_get ? kQuickGet32Instance : kQuickSet32Instance)
814           : (is_get ? kQuickGet32Static : kQuickSet32Static);
815       break;
816     case DataType::Type::kReference:
817       entrypoint = is_instance
818           ? (is_get ? kQuickGetObjInstance : kQuickSetObjInstance)
819           : (is_get ? kQuickGetObjStatic : kQuickSetObjStatic);
820       break;
821     case DataType::Type::kInt64:
822     case DataType::Type::kFloat64:
823       entrypoint = is_instance
824           ? (is_get ? kQuickGet64Instance : kQuickSet64Instance)
825           : (is_get ? kQuickGet64Static : kQuickSet64Static);
826       break;
827     default:
828       LOG(FATAL) << "Invalid type " << field_type;
829   }
830   InvokeRuntime(entrypoint, field_access, dex_pc, nullptr);
831 
832   if (is_get && DataType::IsFloatingPointType(field_type)) {
833     MoveLocation(locations->Out(), calling_convention.GetReturnLocation(field_type), field_type);
834   }
835 }
836 
CreateLoadClassRuntimeCallLocationSummary(HLoadClass * cls,Location runtime_type_index_location,Location runtime_return_location)837 void CodeGenerator::CreateLoadClassRuntimeCallLocationSummary(HLoadClass* cls,
838                                                               Location runtime_type_index_location,
839                                                               Location runtime_return_location) {
840   DCHECK_EQ(cls->GetLoadKind(), HLoadClass::LoadKind::kRuntimeCall);
841   DCHECK_EQ(cls->InputCount(), 1u);
842   LocationSummary* locations = new (cls->GetBlock()->GetGraph()->GetAllocator()) LocationSummary(
843       cls, LocationSummary::kCallOnMainOnly);
844   locations->SetInAt(0, Location::NoLocation());
845   locations->AddTemp(runtime_type_index_location);
846   locations->SetOut(runtime_return_location);
847 }
848 
GenerateLoadClassRuntimeCall(HLoadClass * cls)849 void CodeGenerator::GenerateLoadClassRuntimeCall(HLoadClass* cls) {
850   DCHECK_EQ(cls->GetLoadKind(), HLoadClass::LoadKind::kRuntimeCall);
851   DCHECK(!cls->MustGenerateClinitCheck());
852   LocationSummary* locations = cls->GetLocations();
853   MoveConstant(locations->GetTemp(0), cls->GetTypeIndex().index_);
854   if (cls->NeedsAccessCheck()) {
855     CheckEntrypointTypes<kQuickResolveTypeAndVerifyAccess, void*, uint32_t>();
856     InvokeRuntime(kQuickResolveTypeAndVerifyAccess, cls, cls->GetDexPc());
857   } else {
858     CheckEntrypointTypes<kQuickResolveType, void*, uint32_t>();
859     InvokeRuntime(kQuickResolveType, cls, cls->GetDexPc());
860   }
861 }
862 
CreateLoadMethodHandleRuntimeCallLocationSummary(HLoadMethodHandle * method_handle,Location runtime_proto_index_location,Location runtime_return_location)863 void CodeGenerator::CreateLoadMethodHandleRuntimeCallLocationSummary(
864     HLoadMethodHandle* method_handle,
865     Location runtime_proto_index_location,
866     Location runtime_return_location) {
867   DCHECK_EQ(method_handle->InputCount(), 1u);
868   LocationSummary* locations =
869       new (method_handle->GetBlock()->GetGraph()->GetAllocator()) LocationSummary(
870           method_handle, LocationSummary::kCallOnMainOnly);
871   locations->SetInAt(0, Location::NoLocation());
872   locations->AddTemp(runtime_proto_index_location);
873   locations->SetOut(runtime_return_location);
874 }
875 
GenerateLoadMethodHandleRuntimeCall(HLoadMethodHandle * method_handle)876 void CodeGenerator::GenerateLoadMethodHandleRuntimeCall(HLoadMethodHandle* method_handle) {
877   LocationSummary* locations = method_handle->GetLocations();
878   MoveConstant(locations->GetTemp(0), method_handle->GetMethodHandleIndex());
879   CheckEntrypointTypes<kQuickResolveMethodHandle, void*, uint32_t>();
880   InvokeRuntime(kQuickResolveMethodHandle, method_handle, method_handle->GetDexPc());
881 }
882 
CreateLoadMethodTypeRuntimeCallLocationSummary(HLoadMethodType * method_type,Location runtime_proto_index_location,Location runtime_return_location)883 void CodeGenerator::CreateLoadMethodTypeRuntimeCallLocationSummary(
884     HLoadMethodType* method_type,
885     Location runtime_proto_index_location,
886     Location runtime_return_location) {
887   DCHECK_EQ(method_type->InputCount(), 1u);
888   LocationSummary* locations =
889       new (method_type->GetBlock()->GetGraph()->GetAllocator()) LocationSummary(
890           method_type, LocationSummary::kCallOnMainOnly);
891   locations->SetInAt(0, Location::NoLocation());
892   locations->AddTemp(runtime_proto_index_location);
893   locations->SetOut(runtime_return_location);
894 }
895 
GenerateLoadMethodTypeRuntimeCall(HLoadMethodType * method_type)896 void CodeGenerator::GenerateLoadMethodTypeRuntimeCall(HLoadMethodType* method_type) {
897   LocationSummary* locations = method_type->GetLocations();
898   MoveConstant(locations->GetTemp(0), method_type->GetProtoIndex().index_);
899   CheckEntrypointTypes<kQuickResolveMethodType, void*, uint32_t>();
900   InvokeRuntime(kQuickResolveMethodType, method_type, method_type->GetDexPc());
901 }
902 
GetBootImageOffsetImpl(const void * object,ImageHeader::ImageSections section)903 static uint32_t GetBootImageOffsetImpl(const void* object, ImageHeader::ImageSections section) {
904   Runtime* runtime = Runtime::Current();
905   const std::vector<gc::space::ImageSpace*>& boot_image_spaces =
906       runtime->GetHeap()->GetBootImageSpaces();
907   // Check that the `object` is in the expected section of one of the boot image files.
908   DCHECK(std::any_of(boot_image_spaces.begin(),
909                      boot_image_spaces.end(),
910                      [object, section](gc::space::ImageSpace* space) {
911                        uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
912                        uintptr_t offset = reinterpret_cast<uintptr_t>(object) - begin;
913                        return space->GetImageHeader().GetImageSection(section).Contains(offset);
914                      }));
915   uintptr_t begin = reinterpret_cast<uintptr_t>(boot_image_spaces.front()->Begin());
916   uintptr_t offset = reinterpret_cast<uintptr_t>(object) - begin;
917   return dchecked_integral_cast<uint32_t>(offset);
918 }
919 
GetBootImageOffset(ObjPtr<mirror::Object> object)920 uint32_t CodeGenerator::GetBootImageOffset(ObjPtr<mirror::Object> object) {
921   return GetBootImageOffsetImpl(object.Ptr(), ImageHeader::kSectionObjects);
922 }
923 
924 // NO_THREAD_SAFETY_ANALYSIS: Avoid taking the mutator lock, boot image classes are non-moveable.
GetBootImageOffset(HLoadClass * load_class)925 uint32_t CodeGenerator::GetBootImageOffset(HLoadClass* load_class) NO_THREAD_SAFETY_ANALYSIS {
926   DCHECK_EQ(load_class->GetLoadKind(), HLoadClass::LoadKind::kBootImageRelRo);
927   ObjPtr<mirror::Class> klass = load_class->GetClass().Get();
928   DCHECK(klass != nullptr);
929   return GetBootImageOffsetImpl(klass.Ptr(), ImageHeader::kSectionObjects);
930 }
931 
932 // NO_THREAD_SAFETY_ANALYSIS: Avoid taking the mutator lock, boot image strings are non-moveable.
GetBootImageOffset(HLoadString * load_string)933 uint32_t CodeGenerator::GetBootImageOffset(HLoadString* load_string) NO_THREAD_SAFETY_ANALYSIS {
934   DCHECK_EQ(load_string->GetLoadKind(), HLoadString::LoadKind::kBootImageRelRo);
935   ObjPtr<mirror::String> string = load_string->GetString().Get();
936   DCHECK(string != nullptr);
937   return GetBootImageOffsetImpl(string.Ptr(), ImageHeader::kSectionObjects);
938 }
939 
GetBootImageOffset(HInvoke * invoke)940 uint32_t CodeGenerator::GetBootImageOffset(HInvoke* invoke) {
941   ArtMethod* method = invoke->GetResolvedMethod();
942   DCHECK(method != nullptr);
943   return GetBootImageOffsetImpl(method, ImageHeader::kSectionArtMethods);
944 }
945 
946 // NO_THREAD_SAFETY_ANALYSIS: Avoid taking the mutator lock, boot image objects are non-moveable.
GetBootImageOffset(ClassRoot class_root)947 uint32_t CodeGenerator::GetBootImageOffset(ClassRoot class_root) NO_THREAD_SAFETY_ANALYSIS {
948   ObjPtr<mirror::Class> klass = GetClassRoot<kWithoutReadBarrier>(class_root);
949   return GetBootImageOffsetImpl(klass.Ptr(), ImageHeader::kSectionObjects);
950 }
951 
952 // NO_THREAD_SAFETY_ANALYSIS: Avoid taking the mutator lock, boot image classes are non-moveable.
GetBootImageOffsetOfIntrinsicDeclaringClass(HInvoke * invoke)953 uint32_t CodeGenerator::GetBootImageOffsetOfIntrinsicDeclaringClass(HInvoke* invoke)
954     NO_THREAD_SAFETY_ANALYSIS {
955   DCHECK_NE(invoke->GetIntrinsic(), Intrinsics::kNone);
956   ArtMethod* method = invoke->GetResolvedMethod();
957   DCHECK(method != nullptr);
958   ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass<kWithoutReadBarrier>();
959   return GetBootImageOffsetImpl(declaring_class.Ptr(), ImageHeader::kSectionObjects);
960 }
961 
BlockIfInRegister(Location location,bool is_out) const962 void CodeGenerator::BlockIfInRegister(Location location, bool is_out) const {
963   // The DCHECKS below check that a register is not specified twice in
964   // the summary. The out location can overlap with an input, so we need
965   // to special case it.
966   if (location.IsRegister()) {
967     DCHECK(is_out || !blocked_core_registers_[location.reg()]);
968     blocked_core_registers_[location.reg()] = true;
969   } else if (location.IsFpuRegister()) {
970     DCHECK(is_out || !blocked_fpu_registers_[location.reg()]);
971     blocked_fpu_registers_[location.reg()] = true;
972   } else if (location.IsFpuRegisterPair()) {
973     DCHECK(is_out || !blocked_fpu_registers_[location.AsFpuRegisterPairLow<int>()]);
974     blocked_fpu_registers_[location.AsFpuRegisterPairLow<int>()] = true;
975     DCHECK(is_out || !blocked_fpu_registers_[location.AsFpuRegisterPairHigh<int>()]);
976     blocked_fpu_registers_[location.AsFpuRegisterPairHigh<int>()] = true;
977   } else if (location.IsRegisterPair()) {
978     DCHECK(is_out || !blocked_core_registers_[location.AsRegisterPairLow<int>()]);
979     blocked_core_registers_[location.AsRegisterPairLow<int>()] = true;
980     DCHECK(is_out || !blocked_core_registers_[location.AsRegisterPairHigh<int>()]);
981     blocked_core_registers_[location.AsRegisterPairHigh<int>()] = true;
982   }
983 }
984 
AllocateLocations(HInstruction * instruction)985 void CodeGenerator::AllocateLocations(HInstruction* instruction) {
986   for (HEnvironment* env = instruction->GetEnvironment(); env != nullptr; env = env->GetParent()) {
987     env->AllocateLocations();
988   }
989   instruction->Accept(GetLocationBuilder());
990   DCHECK(CheckTypeConsistency(instruction));
991   LocationSummary* locations = instruction->GetLocations();
992   if (!instruction->IsSuspendCheckEntry()) {
993     if (locations != nullptr) {
994       if (locations->CanCall()) {
995         MarkNotLeaf();
996         if (locations->NeedsSuspendCheckEntry()) {
997           MarkNeedsSuspendCheckEntry();
998         }
999       } else if (locations->Intrinsified() &&
1000                  instruction->IsInvokeStaticOrDirect() &&
1001                  !instruction->AsInvokeStaticOrDirect()->HasCurrentMethodInput()) {
1002         // A static method call that has been fully intrinsified, and cannot call on the slow
1003         // path or refer to the current method directly, no longer needs current method.
1004         return;
1005       }
1006     }
1007     if (instruction->NeedsCurrentMethod()) {
1008       SetRequiresCurrentMethod();
1009     }
1010   }
1011 }
1012 
Create(HGraph * graph,const CompilerOptions & compiler_options,OptimizingCompilerStats * stats)1013 std::unique_ptr<CodeGenerator> CodeGenerator::Create(HGraph* graph,
1014                                                      const CompilerOptions& compiler_options,
1015                                                      OptimizingCompilerStats* stats) {
1016   ArenaAllocator* allocator = graph->GetAllocator();
1017   switch (compiler_options.GetInstructionSet()) {
1018 #ifdef ART_ENABLE_CODEGEN_arm
1019     case InstructionSet::kArm:
1020     case InstructionSet::kThumb2: {
1021       return std::unique_ptr<CodeGenerator>(
1022           new (allocator) arm::CodeGeneratorARMVIXL(graph, compiler_options, stats));
1023     }
1024 #endif
1025 #ifdef ART_ENABLE_CODEGEN_arm64
1026     case InstructionSet::kArm64: {
1027       return std::unique_ptr<CodeGenerator>(
1028           new (allocator) arm64::CodeGeneratorARM64(graph, compiler_options, stats));
1029     }
1030 #endif
1031 #ifdef ART_ENABLE_CODEGEN_x86
1032     case InstructionSet::kX86: {
1033       return std::unique_ptr<CodeGenerator>(
1034           new (allocator) x86::CodeGeneratorX86(graph, compiler_options, stats));
1035     }
1036 #endif
1037 #ifdef ART_ENABLE_CODEGEN_x86_64
1038     case InstructionSet::kX86_64: {
1039       return std::unique_ptr<CodeGenerator>(
1040           new (allocator) x86_64::CodeGeneratorX86_64(graph, compiler_options, stats));
1041     }
1042 #endif
1043     default:
1044       UNUSED(allocator);
1045       UNUSED(graph);
1046       UNUSED(stats);
1047       return nullptr;
1048   }
1049 }
1050 
CodeGenerator(HGraph * graph,size_t number_of_core_registers,size_t number_of_fpu_registers,size_t number_of_register_pairs,uint32_t core_callee_save_mask,uint32_t fpu_callee_save_mask,const CompilerOptions & compiler_options,OptimizingCompilerStats * stats,const art::ArrayRef<const bool> & unimplemented_intrinsics)1051 CodeGenerator::CodeGenerator(HGraph* graph,
1052                              size_t number_of_core_registers,
1053                              size_t number_of_fpu_registers,
1054                              size_t number_of_register_pairs,
1055                              uint32_t core_callee_save_mask,
1056                              uint32_t fpu_callee_save_mask,
1057                              const CompilerOptions& compiler_options,
1058                              OptimizingCompilerStats* stats,
1059                              const art::ArrayRef<const bool>& unimplemented_intrinsics)
1060     : frame_size_(0),
1061       core_spill_mask_(0),
1062       fpu_spill_mask_(0),
1063       first_register_slot_in_slow_path_(0),
1064       allocated_registers_(RegisterSet::Empty()),
1065       blocked_core_registers_(graph->GetAllocator()->AllocArray<bool>(number_of_core_registers,
1066                                                                       kArenaAllocCodeGenerator)),
1067       blocked_fpu_registers_(graph->GetAllocator()->AllocArray<bool>(number_of_fpu_registers,
1068                                                                      kArenaAllocCodeGenerator)),
1069       number_of_core_registers_(number_of_core_registers),
1070       number_of_fpu_registers_(number_of_fpu_registers),
1071       number_of_register_pairs_(number_of_register_pairs),
1072       core_callee_save_mask_(core_callee_save_mask),
1073       fpu_callee_save_mask_(fpu_callee_save_mask),
1074       block_order_(nullptr),
1075       disasm_info_(nullptr),
1076       stats_(stats),
1077       graph_(graph),
1078       compiler_options_(compiler_options),
1079       current_slow_path_(nullptr),
1080       current_block_index_(0),
1081       is_leaf_(true),
1082       needs_suspend_check_entry_(false),
1083       requires_current_method_(false),
1084       code_generation_data_(),
1085       unimplemented_intrinsics_(unimplemented_intrinsics) {
1086   if (GetGraph()->IsCompilingOsr()) {
1087     // Make OSR methods have all registers spilled, this simplifies the logic of
1088     // jumping to the compiled code directly.
1089     for (size_t i = 0; i < number_of_core_registers_; ++i) {
1090       if (IsCoreCalleeSaveRegister(i)) {
1091         AddAllocatedRegister(Location::RegisterLocation(i));
1092       }
1093     }
1094     for (size_t i = 0; i < number_of_fpu_registers_; ++i) {
1095       if (IsFloatingPointCalleeSaveRegister(i)) {
1096         AddAllocatedRegister(Location::FpuRegisterLocation(i));
1097       }
1098     }
1099   }
1100   if (GetGraph()->IsCompilingBaseline()) {
1101     // We need the current method in case we reach the hotness threshold. As a
1102     // side effect this makes the frame non-empty.
1103     SetRequiresCurrentMethod();
1104   }
1105 }
1106 
~CodeGenerator()1107 CodeGenerator::~CodeGenerator() {}
1108 
GetNumberOfJitRoots() const1109 size_t CodeGenerator::GetNumberOfJitRoots() const {
1110   DCHECK(code_generation_data_ != nullptr);
1111   return code_generation_data_->GetNumberOfJitRoots();
1112 }
1113 
CheckCovers(uint32_t dex_pc,const HGraph & graph,const CodeInfo & code_info,const ArenaVector<HSuspendCheck * > & loop_headers,ArenaVector<size_t> * covered)1114 static void CheckCovers(uint32_t dex_pc,
1115                         const HGraph& graph,
1116                         const CodeInfo& code_info,
1117                         const ArenaVector<HSuspendCheck*>& loop_headers,
1118                         ArenaVector<size_t>* covered) {
1119   for (size_t i = 0; i < loop_headers.size(); ++i) {
1120     if (loop_headers[i]->GetDexPc() == dex_pc) {
1121       if (graph.IsCompilingOsr()) {
1122         DCHECK(code_info.GetOsrStackMapForDexPc(dex_pc).IsValid());
1123       }
1124       ++(*covered)[i];
1125     }
1126   }
1127 }
1128 
1129 // Debug helper to ensure loop entries in compiled code are matched by
1130 // dex branch instructions.
CheckLoopEntriesCanBeUsedForOsr(const HGraph & graph,const CodeInfo & code_info,const dex::CodeItem & code_item)1131 static void CheckLoopEntriesCanBeUsedForOsr(const HGraph& graph,
1132                                             const CodeInfo& code_info,
1133                                             const dex::CodeItem& code_item) {
1134   if (graph.HasTryCatch()) {
1135     // One can write loops through try/catch, which we do not support for OSR anyway.
1136     return;
1137   }
1138   ArenaVector<HSuspendCheck*> loop_headers(graph.GetAllocator()->Adapter(kArenaAllocMisc));
1139   for (HBasicBlock* block : graph.GetReversePostOrder()) {
1140     if (block->IsLoopHeader()) {
1141       HSuspendCheck* suspend_check = block->GetLoopInformation()->GetSuspendCheck();
1142       if (suspend_check != nullptr && !suspend_check->GetEnvironment()->IsFromInlinedInvoke()) {
1143         loop_headers.push_back(suspend_check);
1144       }
1145     }
1146   }
1147   ArenaVector<size_t> covered(
1148       loop_headers.size(), 0, graph.GetAllocator()->Adapter(kArenaAllocMisc));
1149   for (const DexInstructionPcPair& pair : CodeItemInstructionAccessor(graph.GetDexFile(),
1150                                                                       &code_item)) {
1151     const uint32_t dex_pc = pair.DexPc();
1152     const Instruction& instruction = pair.Inst();
1153     if (instruction.IsBranch()) {
1154       uint32_t target = dex_pc + instruction.GetTargetOffset();
1155       CheckCovers(target, graph, code_info, loop_headers, &covered);
1156     } else if (instruction.IsSwitch()) {
1157       DexSwitchTable table(instruction, dex_pc);
1158       uint16_t num_entries = table.GetNumEntries();
1159       size_t offset = table.GetFirstValueIndex();
1160 
1161       // Use a larger loop counter type to avoid overflow issues.
1162       for (size_t i = 0; i < num_entries; ++i) {
1163         // The target of the case.
1164         uint32_t target = dex_pc + table.GetEntryAt(i + offset);
1165         CheckCovers(target, graph, code_info, loop_headers, &covered);
1166       }
1167     }
1168   }
1169 
1170   for (size_t i = 0; i < covered.size(); ++i) {
1171     DCHECK_NE(covered[i], 0u) << "Loop in compiled code has no dex branch equivalent";
1172   }
1173 }
1174 
BuildStackMaps(const dex::CodeItem * code_item)1175 ScopedArenaVector<uint8_t> CodeGenerator::BuildStackMaps(const dex::CodeItem* code_item) {
1176   ScopedArenaVector<uint8_t> stack_map = GetStackMapStream()->Encode();
1177   if (kIsDebugBuild && code_item != nullptr) {
1178     CheckLoopEntriesCanBeUsedForOsr(*graph_, CodeInfo(stack_map.data()), *code_item);
1179   }
1180   return stack_map;
1181 }
1182 
1183 // Returns whether stackmap dex register info is needed for the instruction.
1184 //
1185 // The following cases mandate having a dex register map:
1186 //  * Deoptimization
1187 //    when we need to obtain the values to restore actual vregisters for interpreter.
1188 //  * Debuggability
1189 //    when we want to observe the values / asynchronously deoptimize.
1190 //  * Monitor operations
1191 //    to allow dumping in a stack trace locked dex registers for non-debuggable code.
1192 //  * On-stack-replacement (OSR)
1193 //    when entering compiled for OSR code from the interpreter we need to initialize the compiled
1194 //    code values with the values from the vregisters.
1195 //  * Method local catch blocks
1196 //    a catch block must see the environment of the instruction from the same method that can
1197 //    throw to this block.
NeedsVregInfo(HInstruction * instruction,bool osr)1198 static bool NeedsVregInfo(HInstruction* instruction, bool osr) {
1199   HGraph* graph = instruction->GetBlock()->GetGraph();
1200   return instruction->IsDeoptimize() ||
1201          graph->IsDebuggable() ||
1202          graph->HasMonitorOperations() ||
1203          osr ||
1204          instruction->CanThrowIntoCatchBlock();
1205 }
1206 
RecordPcInfo(HInstruction * instruction,uint32_t dex_pc,SlowPathCode * slow_path,bool native_debug_info)1207 void CodeGenerator::RecordPcInfo(HInstruction* instruction,
1208                                  uint32_t dex_pc,
1209                                  SlowPathCode* slow_path,
1210                                  bool native_debug_info) {
1211   RecordPcInfo(instruction, dex_pc, GetAssembler()->CodePosition(), slow_path, native_debug_info);
1212 }
1213 
RecordPcInfo(HInstruction * instruction,uint32_t dex_pc,uint32_t native_pc,SlowPathCode * slow_path,bool native_debug_info)1214 void CodeGenerator::RecordPcInfo(HInstruction* instruction,
1215                                  uint32_t dex_pc,
1216                                  uint32_t native_pc,
1217                                  SlowPathCode* slow_path,
1218                                  bool native_debug_info) {
1219   if (instruction != nullptr) {
1220     // The code generated for some type conversions
1221     // may call the runtime, thus normally requiring a subsequent
1222     // call to this method. However, the method verifier does not
1223     // produce PC information for certain instructions, which are
1224     // considered "atomic" (they cannot join a GC).
1225     // Therefore we do not currently record PC information for such
1226     // instructions.  As this may change later, we added this special
1227     // case so that code generators may nevertheless call
1228     // CodeGenerator::RecordPcInfo without triggering an error in
1229     // CodeGenerator::BuildNativeGCMap ("Missing ref for dex pc 0x")
1230     // thereafter.
1231     if (instruction->IsTypeConversion()) {
1232       return;
1233     }
1234     if (instruction->IsRem()) {
1235       DataType::Type type = instruction->AsRem()->GetResultType();
1236       if ((type == DataType::Type::kFloat32) || (type == DataType::Type::kFloat64)) {
1237         return;
1238       }
1239     }
1240   }
1241 
1242   StackMapStream* stack_map_stream = GetStackMapStream();
1243   if (instruction == nullptr) {
1244     // For stack overflow checks and native-debug-info entries without dex register
1245     // mapping (i.e. start of basic block or start of slow path).
1246     stack_map_stream->BeginStackMapEntry(dex_pc, native_pc);
1247     stack_map_stream->EndStackMapEntry();
1248     return;
1249   }
1250 
1251   LocationSummary* locations = instruction->GetLocations();
1252   uint32_t register_mask = locations->GetRegisterMask();
1253   DCHECK_EQ(register_mask & ~locations->GetLiveRegisters()->GetCoreRegisters(), 0u);
1254   if (locations->OnlyCallsOnSlowPath()) {
1255     // In case of slow path, we currently set the location of caller-save registers
1256     // to register (instead of their stack location when pushed before the slow-path
1257     // call). Therefore register_mask contains both callee-save and caller-save
1258     // registers that hold objects. We must remove the spilled caller-save from the
1259     // mask, since they will be overwritten by the callee.
1260     uint32_t spills = GetSlowPathSpills(locations, /* core_registers= */ true);
1261     register_mask &= ~spills;
1262   } else {
1263     // The register mask must be a subset of callee-save registers.
1264     DCHECK_EQ(register_mask & core_callee_save_mask_, register_mask);
1265   }
1266 
1267   uint32_t outer_dex_pc = dex_pc;
1268   uint32_t inlining_depth = 0;
1269   HEnvironment* const environment = instruction->GetEnvironment();
1270   if (environment != nullptr) {
1271     HEnvironment* outer_environment = environment;
1272     while (outer_environment->GetParent() != nullptr) {
1273       outer_environment = outer_environment->GetParent();
1274       ++inlining_depth;
1275     }
1276     outer_dex_pc = outer_environment->GetDexPc();
1277   }
1278 
1279   HLoopInformation* info = instruction->GetBlock()->GetLoopInformation();
1280   bool osr =
1281       instruction->IsSuspendCheck() &&
1282       (info != nullptr) &&
1283       graph_->IsCompilingOsr() &&
1284       (inlining_depth == 0);
1285   StackMap::Kind kind = native_debug_info
1286       ? StackMap::Kind::Debug
1287       : (osr ? StackMap::Kind::OSR : StackMap::Kind::Default);
1288   bool needs_vreg_info = NeedsVregInfo(instruction, osr);
1289   stack_map_stream->BeginStackMapEntry(outer_dex_pc,
1290                                        native_pc,
1291                                        register_mask,
1292                                        locations->GetStackMask(),
1293                                        kind,
1294                                        needs_vreg_info);
1295 
1296   EmitEnvironment(environment, slow_path, needs_vreg_info);
1297   stack_map_stream->EndStackMapEntry();
1298 
1299   if (osr) {
1300     DCHECK_EQ(info->GetSuspendCheck(), instruction);
1301     DCHECK(info->IsIrreducible());
1302     DCHECK(environment != nullptr);
1303     if (kIsDebugBuild) {
1304       for (size_t i = 0, environment_size = environment->Size(); i < environment_size; ++i) {
1305         HInstruction* in_environment = environment->GetInstructionAt(i);
1306         if (in_environment != nullptr) {
1307           DCHECK(in_environment->IsPhi() || in_environment->IsConstant());
1308           Location location = environment->GetLocationAt(i);
1309           DCHECK(location.IsStackSlot() ||
1310                  location.IsDoubleStackSlot() ||
1311                  location.IsConstant() ||
1312                  location.IsInvalid());
1313           if (location.IsStackSlot() || location.IsDoubleStackSlot()) {
1314             DCHECK_LT(location.GetStackIndex(), static_cast<int32_t>(GetFrameSize()));
1315           }
1316         }
1317       }
1318     }
1319   }
1320 }
1321 
HasStackMapAtCurrentPc()1322 bool CodeGenerator::HasStackMapAtCurrentPc() {
1323   uint32_t pc = GetAssembler()->CodeSize();
1324   StackMapStream* stack_map_stream = GetStackMapStream();
1325   size_t count = stack_map_stream->GetNumberOfStackMaps();
1326   if (count == 0) {
1327     return false;
1328   }
1329   return stack_map_stream->GetStackMapNativePcOffset(count - 1) == pc;
1330 }
1331 
MaybeRecordNativeDebugInfo(HInstruction * instruction,uint32_t dex_pc,SlowPathCode * slow_path)1332 void CodeGenerator::MaybeRecordNativeDebugInfo(HInstruction* instruction,
1333                                                uint32_t dex_pc,
1334                                                SlowPathCode* slow_path) {
1335   if (GetCompilerOptions().GetNativeDebuggable() && dex_pc != kNoDexPc) {
1336     if (HasStackMapAtCurrentPc()) {
1337       // Ensure that we do not collide with the stack map of the previous instruction.
1338       GenerateNop();
1339     }
1340     RecordPcInfo(instruction, dex_pc, slow_path, /* native_debug_info= */ true);
1341   }
1342 }
1343 
RecordCatchBlockInfo()1344 void CodeGenerator::RecordCatchBlockInfo() {
1345   StackMapStream* stack_map_stream = GetStackMapStream();
1346 
1347   for (HBasicBlock* block : *block_order_) {
1348     if (!block->IsCatchBlock()) {
1349       continue;
1350     }
1351 
1352     // Get the outer dex_pc. We save the full environment list for DCHECK purposes in kIsDebugBuild.
1353     std::vector<uint32_t> dex_pc_list_for_verification;
1354     if (kIsDebugBuild) {
1355       dex_pc_list_for_verification.push_back(block->GetDexPc());
1356     }
1357     DCHECK(block->GetFirstInstruction()->IsNop());
1358     DCHECK(block->GetFirstInstruction()->AsNop()->NeedsEnvironment());
1359     HEnvironment* const environment = block->GetFirstInstruction()->GetEnvironment();
1360     DCHECK(environment != nullptr);
1361     HEnvironment* outer_environment = environment;
1362     while (outer_environment->GetParent() != nullptr) {
1363       outer_environment = outer_environment->GetParent();
1364       if (kIsDebugBuild) {
1365         dex_pc_list_for_verification.push_back(outer_environment->GetDexPc());
1366       }
1367     }
1368 
1369     if (kIsDebugBuild) {
1370       // dex_pc_list_for_verification is set from innnermost to outermost. Let's reverse it
1371       // since we are expected to pass from outermost to innermost.
1372       std::reverse(dex_pc_list_for_verification.begin(), dex_pc_list_for_verification.end());
1373       DCHECK_EQ(dex_pc_list_for_verification.front(), outer_environment->GetDexPc());
1374     }
1375 
1376     uint32_t native_pc = GetAddressOf(block);
1377     stack_map_stream->BeginStackMapEntry(outer_environment->GetDexPc(),
1378                                          native_pc,
1379                                          /* register_mask= */ 0,
1380                                          /* sp_mask= */ nullptr,
1381                                          StackMap::Kind::Catch,
1382                                          /* needs_vreg_info= */ true,
1383                                          dex_pc_list_for_verification);
1384 
1385     EmitEnvironment(environment,
1386                     /* slow_path= */ nullptr,
1387                     /* needs_vreg_info= */ true,
1388                     /* is_for_catch_handler= */ true);
1389 
1390     stack_map_stream->EndStackMapEntry();
1391   }
1392 }
1393 
AddSlowPath(SlowPathCode * slow_path)1394 void CodeGenerator::AddSlowPath(SlowPathCode* slow_path) {
1395   DCHECK(code_generation_data_ != nullptr);
1396   code_generation_data_->AddSlowPath(slow_path);
1397 }
1398 
EmitVRegInfo(HEnvironment * environment,SlowPathCode * slow_path,bool is_for_catch_handler)1399 void CodeGenerator::EmitVRegInfo(HEnvironment* environment,
1400                                  SlowPathCode* slow_path,
1401                                  bool is_for_catch_handler) {
1402   StackMapStream* stack_map_stream = GetStackMapStream();
1403   // Walk over the environment, and record the location of dex registers.
1404   for (size_t i = 0, environment_size = environment->Size(); i < environment_size; ++i) {
1405     HInstruction* current = environment->GetInstructionAt(i);
1406     if (current == nullptr) {
1407       stack_map_stream->AddDexRegisterEntry(DexRegisterLocation::Kind::kNone, 0);
1408       continue;
1409     }
1410 
1411     using Kind = DexRegisterLocation::Kind;
1412     Location location = environment->GetLocationAt(i);
1413     switch (location.GetKind()) {
1414       case Location::kConstant: {
1415         DCHECK_EQ(current, location.GetConstant());
1416         if (current->IsLongConstant()) {
1417           int64_t value = current->AsLongConstant()->GetValue();
1418           stack_map_stream->AddDexRegisterEntry(Kind::kConstant, Low32Bits(value));
1419           stack_map_stream->AddDexRegisterEntry(Kind::kConstant, High32Bits(value));
1420           ++i;
1421           DCHECK_LT(i, environment_size);
1422         } else if (current->IsDoubleConstant()) {
1423           int64_t value = bit_cast<int64_t, double>(current->AsDoubleConstant()->GetValue());
1424           stack_map_stream->AddDexRegisterEntry(Kind::kConstant, Low32Bits(value));
1425           stack_map_stream->AddDexRegisterEntry(Kind::kConstant, High32Bits(value));
1426           ++i;
1427           DCHECK_LT(i, environment_size);
1428         } else if (current->IsIntConstant()) {
1429           int32_t value = current->AsIntConstant()->GetValue();
1430           stack_map_stream->AddDexRegisterEntry(Kind::kConstant, value);
1431         } else if (current->IsNullConstant()) {
1432           stack_map_stream->AddDexRegisterEntry(Kind::kConstant, 0);
1433         } else {
1434           DCHECK(current->IsFloatConstant()) << current->DebugName();
1435           int32_t value = bit_cast<int32_t, float>(current->AsFloatConstant()->GetValue());
1436           stack_map_stream->AddDexRegisterEntry(Kind::kConstant, value);
1437         }
1438         break;
1439       }
1440 
1441       case Location::kStackSlot: {
1442         stack_map_stream->AddDexRegisterEntry(Kind::kInStack, location.GetStackIndex());
1443         break;
1444       }
1445 
1446       case Location::kDoubleStackSlot: {
1447         stack_map_stream->AddDexRegisterEntry(Kind::kInStack, location.GetStackIndex());
1448         stack_map_stream->AddDexRegisterEntry(
1449             Kind::kInStack, location.GetHighStackIndex(kVRegSize));
1450         ++i;
1451         DCHECK_LT(i, environment_size);
1452         break;
1453       }
1454 
1455       case Location::kRegister : {
1456         DCHECK(!is_for_catch_handler);
1457         int id = location.reg();
1458         if (slow_path != nullptr && slow_path->IsCoreRegisterSaved(id)) {
1459           uint32_t offset = slow_path->GetStackOffsetOfCoreRegister(id);
1460           stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset);
1461           if (current->GetType() == DataType::Type::kInt64) {
1462             stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset + kVRegSize);
1463             ++i;
1464             DCHECK_LT(i, environment_size);
1465           }
1466         } else {
1467           stack_map_stream->AddDexRegisterEntry(Kind::kInRegister, id);
1468           if (current->GetType() == DataType::Type::kInt64) {
1469             stack_map_stream->AddDexRegisterEntry(Kind::kInRegisterHigh, id);
1470             ++i;
1471             DCHECK_LT(i, environment_size);
1472           }
1473         }
1474         break;
1475       }
1476 
1477       case Location::kFpuRegister : {
1478         DCHECK(!is_for_catch_handler);
1479         int id = location.reg();
1480         if (slow_path != nullptr && slow_path->IsFpuRegisterSaved(id)) {
1481           uint32_t offset = slow_path->GetStackOffsetOfFpuRegister(id);
1482           stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset);
1483           if (current->GetType() == DataType::Type::kFloat64) {
1484             stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset + kVRegSize);
1485             ++i;
1486             DCHECK_LT(i, environment_size);
1487           }
1488         } else {
1489           stack_map_stream->AddDexRegisterEntry(Kind::kInFpuRegister, id);
1490           if (current->GetType() == DataType::Type::kFloat64) {
1491             stack_map_stream->AddDexRegisterEntry(Kind::kInFpuRegisterHigh, id);
1492             ++i;
1493             DCHECK_LT(i, environment_size);
1494           }
1495         }
1496         break;
1497       }
1498 
1499       case Location::kFpuRegisterPair : {
1500         DCHECK(!is_for_catch_handler);
1501         int low = location.low();
1502         int high = location.high();
1503         if (slow_path != nullptr && slow_path->IsFpuRegisterSaved(low)) {
1504           uint32_t offset = slow_path->GetStackOffsetOfFpuRegister(low);
1505           stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset);
1506         } else {
1507           stack_map_stream->AddDexRegisterEntry(Kind::kInFpuRegister, low);
1508         }
1509         if (slow_path != nullptr && slow_path->IsFpuRegisterSaved(high)) {
1510           uint32_t offset = slow_path->GetStackOffsetOfFpuRegister(high);
1511           stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset);
1512           ++i;
1513         } else {
1514           stack_map_stream->AddDexRegisterEntry(Kind::kInFpuRegister, high);
1515           ++i;
1516         }
1517         DCHECK_LT(i, environment_size);
1518         break;
1519       }
1520 
1521       case Location::kRegisterPair : {
1522         DCHECK(!is_for_catch_handler);
1523         int low = location.low();
1524         int high = location.high();
1525         if (slow_path != nullptr && slow_path->IsCoreRegisterSaved(low)) {
1526           uint32_t offset = slow_path->GetStackOffsetOfCoreRegister(low);
1527           stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset);
1528         } else {
1529           stack_map_stream->AddDexRegisterEntry(Kind::kInRegister, low);
1530         }
1531         if (slow_path != nullptr && slow_path->IsCoreRegisterSaved(high)) {
1532           uint32_t offset = slow_path->GetStackOffsetOfCoreRegister(high);
1533           stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset);
1534         } else {
1535           stack_map_stream->AddDexRegisterEntry(Kind::kInRegister, high);
1536         }
1537         ++i;
1538         DCHECK_LT(i, environment_size);
1539         break;
1540       }
1541 
1542       case Location::kInvalid: {
1543         stack_map_stream->AddDexRegisterEntry(Kind::kNone, 0);
1544         break;
1545       }
1546 
1547       default:
1548         LOG(FATAL) << "Unexpected kind " << location.GetKind();
1549     }
1550   }
1551 }
1552 
EmitVRegInfoOnlyCatchPhis(HEnvironment * environment)1553 void CodeGenerator::EmitVRegInfoOnlyCatchPhis(HEnvironment* environment) {
1554   StackMapStream* stack_map_stream = GetStackMapStream();
1555   DCHECK(environment->GetHolder()->GetBlock()->IsCatchBlock());
1556   DCHECK_EQ(environment->GetHolder()->GetBlock()->GetFirstInstruction(), environment->GetHolder());
1557   HInstruction* current_phi = environment->GetHolder()->GetBlock()->GetFirstPhi();
1558   for (size_t vreg = 0; vreg < environment->Size(); ++vreg) {
1559     while (current_phi != nullptr && current_phi->AsPhi()->GetRegNumber() < vreg) {
1560       HInstruction* next_phi = current_phi->GetNext();
1561       DCHECK(next_phi == nullptr ||
1562              current_phi->AsPhi()->GetRegNumber() <= next_phi->AsPhi()->GetRegNumber())
1563           << "Phis need to be sorted by vreg number to keep this a linear-time loop.";
1564       current_phi = next_phi;
1565     }
1566 
1567     if (current_phi == nullptr || current_phi->AsPhi()->GetRegNumber() != vreg) {
1568       stack_map_stream->AddDexRegisterEntry(DexRegisterLocation::Kind::kNone, 0);
1569     } else {
1570       Location location = current_phi->GetLocations()->Out();
1571       switch (location.GetKind()) {
1572         case Location::kStackSlot: {
1573           stack_map_stream->AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack,
1574                                                 location.GetStackIndex());
1575           break;
1576         }
1577         case Location::kDoubleStackSlot: {
1578           stack_map_stream->AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack,
1579                                                 location.GetStackIndex());
1580           stack_map_stream->AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack,
1581                                                 location.GetHighStackIndex(kVRegSize));
1582           ++vreg;
1583           DCHECK_LT(vreg, environment->Size());
1584           break;
1585         }
1586         default: {
1587           LOG(FATAL) << "All catch phis must be allocated to a stack slot. Unexpected kind "
1588                      << location.GetKind();
1589           UNREACHABLE();
1590         }
1591       }
1592     }
1593   }
1594 }
1595 
EmitEnvironment(HEnvironment * environment,SlowPathCode * slow_path,bool needs_vreg_info,bool is_for_catch_handler,bool innermost_environment)1596 void CodeGenerator::EmitEnvironment(HEnvironment* environment,
1597                                     SlowPathCode* slow_path,
1598                                     bool needs_vreg_info,
1599                                     bool is_for_catch_handler,
1600                                     bool innermost_environment) {
1601   if (environment == nullptr) return;
1602 
1603   StackMapStream* stack_map_stream = GetStackMapStream();
1604   bool emit_inline_info = environment->GetParent() != nullptr;
1605 
1606   if (emit_inline_info) {
1607     // We emit the parent environment first.
1608     EmitEnvironment(environment->GetParent(),
1609                     slow_path,
1610                     needs_vreg_info,
1611                     is_for_catch_handler,
1612                     /* innermost_environment= */ false);
1613     stack_map_stream->BeginInlineInfoEntry(environment->GetMethod(),
1614                                            environment->GetDexPc(),
1615                                            needs_vreg_info ? environment->Size() : 0,
1616                                            &graph_->GetDexFile(),
1617                                            this);
1618   }
1619 
1620   // If a dex register map is not required we just won't emit it.
1621   if (needs_vreg_info) {
1622     if (innermost_environment && is_for_catch_handler) {
1623       EmitVRegInfoOnlyCatchPhis(environment);
1624     } else {
1625       EmitVRegInfo(environment, slow_path, is_for_catch_handler);
1626     }
1627   }
1628 
1629   if (emit_inline_info) {
1630     stack_map_stream->EndInlineInfoEntry();
1631   }
1632 }
1633 
CanMoveNullCheckToUser(HNullCheck * null_check)1634 bool CodeGenerator::CanMoveNullCheckToUser(HNullCheck* null_check) {
1635   return null_check->IsEmittedAtUseSite();
1636 }
1637 
MaybeRecordImplicitNullCheck(HInstruction * instr)1638 void CodeGenerator::MaybeRecordImplicitNullCheck(HInstruction* instr) {
1639   HNullCheck* null_check = instr->GetImplicitNullCheck();
1640   if (null_check != nullptr) {
1641     RecordPcInfo(null_check, null_check->GetDexPc(), GetAssembler()->CodePosition());
1642   }
1643 }
1644 
CreateThrowingSlowPathLocations(HInstruction * instruction,RegisterSet caller_saves)1645 LocationSummary* CodeGenerator::CreateThrowingSlowPathLocations(HInstruction* instruction,
1646                                                                 RegisterSet caller_saves) {
1647   // Note: Using kNoCall allows the method to be treated as leaf (and eliminate the
1648   // HSuspendCheck from entry block). However, it will still get a valid stack frame
1649   // because the HNullCheck needs an environment.
1650   LocationSummary::CallKind call_kind = LocationSummary::kNoCall;
1651   // When throwing from a try block, we may need to retrieve dalvik registers from
1652   // physical registers and we also need to set up stack mask for GC. This is
1653   // implicitly achieved by passing kCallOnSlowPath to the LocationSummary.
1654   bool can_throw_into_catch_block = instruction->CanThrowIntoCatchBlock();
1655   if (can_throw_into_catch_block) {
1656     call_kind = LocationSummary::kCallOnSlowPath;
1657   }
1658   LocationSummary* locations =
1659       new (GetGraph()->GetAllocator()) LocationSummary(instruction, call_kind);
1660   if (can_throw_into_catch_block && compiler_options_.GetImplicitNullChecks()) {
1661     locations->SetCustomSlowPathCallerSaves(caller_saves);  // Default: no caller-save registers.
1662   }
1663   DCHECK(!instruction->HasUses());
1664   return locations;
1665 }
1666 
GenerateNullCheck(HNullCheck * instruction)1667 void CodeGenerator::GenerateNullCheck(HNullCheck* instruction) {
1668   if (compiler_options_.GetImplicitNullChecks()) {
1669     MaybeRecordStat(stats_, MethodCompilationStat::kImplicitNullCheckGenerated);
1670     GenerateImplicitNullCheck(instruction);
1671   } else {
1672     MaybeRecordStat(stats_, MethodCompilationStat::kExplicitNullCheckGenerated);
1673     GenerateExplicitNullCheck(instruction);
1674   }
1675 }
1676 
ClearSpillSlotsFromLoopPhisInStackMap(HSuspendCheck * suspend_check,HParallelMove * spills) const1677 void CodeGenerator::ClearSpillSlotsFromLoopPhisInStackMap(HSuspendCheck* suspend_check,
1678                                                           HParallelMove* spills) const {
1679   LocationSummary* locations = suspend_check->GetLocations();
1680   HBasicBlock* block = suspend_check->GetBlock();
1681   DCHECK(block->GetLoopInformation()->GetSuspendCheck() == suspend_check);
1682   DCHECK(block->IsLoopHeader());
1683   DCHECK(block->GetFirstInstruction() == spills);
1684 
1685   for (size_t i = 0, num_moves = spills->NumMoves(); i != num_moves; ++i) {
1686     Location dest = spills->MoveOperandsAt(i)->GetDestination();
1687     // All parallel moves in loop headers are spills.
1688     DCHECK(dest.IsStackSlot() || dest.IsDoubleStackSlot() || dest.IsSIMDStackSlot()) << dest;
1689     // Clear the stack bit marking a reference. Do not bother to check if the spill is
1690     // actually a reference spill, clearing bits that are already zero is harmless.
1691     locations->ClearStackBit(dest.GetStackIndex() / kVRegSize);
1692   }
1693 }
1694 
EmitParallelMoves(Location from1,Location to1,DataType::Type type1,Location from2,Location to2,DataType::Type type2)1695 void CodeGenerator::EmitParallelMoves(Location from1,
1696                                       Location to1,
1697                                       DataType::Type type1,
1698                                       Location from2,
1699                                       Location to2,
1700                                       DataType::Type type2) {
1701   HParallelMove parallel_move(GetGraph()->GetAllocator());
1702   parallel_move.AddMove(from1, to1, type1, nullptr);
1703   parallel_move.AddMove(from2, to2, type2, nullptr);
1704   GetMoveResolver()->EmitNativeCode(&parallel_move);
1705 }
1706 
ValidateInvokeRuntime(QuickEntrypointEnum entrypoint,HInstruction * instruction,SlowPathCode * slow_path)1707 void CodeGenerator::ValidateInvokeRuntime(QuickEntrypointEnum entrypoint,
1708                                           HInstruction* instruction,
1709                                           SlowPathCode* slow_path) {
1710   // Ensure that the call kind indication given to the register allocator is
1711   // coherent with the runtime call generated.
1712   if (slow_path == nullptr) {
1713     DCHECK(instruction->GetLocations()->WillCall())
1714         << "instruction->DebugName()=" << instruction->DebugName();
1715   } else {
1716     DCHECK(instruction->GetLocations()->CallsOnSlowPath() || slow_path->IsFatal())
1717         << "instruction->DebugName()=" << instruction->DebugName()
1718         << " slow_path->GetDescription()=" << slow_path->GetDescription();
1719   }
1720 
1721   // Check that the GC side effect is set when required.
1722   // TODO: Reverse EntrypointCanTriggerGC
1723   if (EntrypointCanTriggerGC(entrypoint)) {
1724     if (slow_path == nullptr) {
1725       DCHECK(instruction->GetSideEffects().Includes(SideEffects::CanTriggerGC()))
1726           << "instruction->DebugName()=" << instruction->DebugName()
1727           << " instruction->GetSideEffects().ToString()="
1728           << instruction->GetSideEffects().ToString();
1729     } else {
1730       // 'CanTriggerGC' side effect is used to restrict optimization of instructions which depend
1731       // on GC (e.g. IntermediateAddress) - to ensure they are not alive across GC points. However
1732       // if execution never returns to the compiled code from a GC point this restriction is
1733       // unnecessary - in particular for fatal slow paths which might trigger GC.
1734       DCHECK((slow_path->IsFatal() && !instruction->GetLocations()->WillCall()) ||
1735              instruction->GetSideEffects().Includes(SideEffects::CanTriggerGC()) ||
1736              // When (non-Baker) read barriers are enabled, some instructions
1737              // use a slow path to emit a read barrier, which does not trigger
1738              // GC.
1739              (gUseReadBarrier &&
1740               !kUseBakerReadBarrier &&
1741               (instruction->IsInstanceFieldGet() ||
1742                instruction->IsPredicatedInstanceFieldGet() ||
1743                instruction->IsStaticFieldGet() ||
1744                instruction->IsArrayGet() ||
1745                instruction->IsLoadClass() ||
1746                instruction->IsLoadString() ||
1747                instruction->IsInstanceOf() ||
1748                instruction->IsCheckCast() ||
1749                (instruction->IsInvokeVirtual() && instruction->GetLocations()->Intrinsified()))))
1750           << "instruction->DebugName()=" << instruction->DebugName()
1751           << " instruction->GetSideEffects().ToString()="
1752           << instruction->GetSideEffects().ToString()
1753           << " slow_path->GetDescription()=" << slow_path->GetDescription() << std::endl
1754           << "Instruction and args: " << instruction->DumpWithArgs();
1755     }
1756   } else {
1757     // The GC side effect is not required for the instruction. But the instruction might still have
1758     // it, for example if it calls other entrypoints requiring it.
1759   }
1760 
1761   // Check the coherency of leaf information.
1762   DCHECK(instruction->IsSuspendCheck()
1763          || ((slow_path != nullptr) && slow_path->IsFatal())
1764          || instruction->GetLocations()->CanCall()
1765          || !IsLeafMethod())
1766       << instruction->DebugName() << ((slow_path != nullptr) ? slow_path->GetDescription() : "");
1767 }
1768 
ValidateInvokeRuntimeWithoutRecordingPcInfo(HInstruction * instruction,SlowPathCode * slow_path)1769 void CodeGenerator::ValidateInvokeRuntimeWithoutRecordingPcInfo(HInstruction* instruction,
1770                                                                 SlowPathCode* slow_path) {
1771   DCHECK(instruction->GetLocations()->OnlyCallsOnSlowPath())
1772       << "instruction->DebugName()=" << instruction->DebugName()
1773       << " slow_path->GetDescription()=" << slow_path->GetDescription();
1774   // Only the Baker read barrier marking slow path used by certains
1775   // instructions is expected to invoke the runtime without recording
1776   // PC-related information.
1777   DCHECK(kUseBakerReadBarrier);
1778   DCHECK(instruction->IsInstanceFieldGet() ||
1779          instruction->IsPredicatedInstanceFieldGet() ||
1780          instruction->IsStaticFieldGet() ||
1781          instruction->IsArrayGet() ||
1782          instruction->IsArraySet() ||
1783          instruction->IsLoadClass() ||
1784          instruction->IsLoadString() ||
1785          instruction->IsInstanceOf() ||
1786          instruction->IsCheckCast() ||
1787          (instruction->IsInvoke() && instruction->GetLocations()->Intrinsified()))
1788       << "instruction->DebugName()=" << instruction->DebugName()
1789       << " slow_path->GetDescription()=" << slow_path->GetDescription();
1790 }
1791 
SaveLiveRegisters(CodeGenerator * codegen,LocationSummary * locations)1792 void SlowPathCode::SaveLiveRegisters(CodeGenerator* codegen, LocationSummary* locations) {
1793   size_t stack_offset = codegen->GetFirstRegisterSlotInSlowPath();
1794 
1795   const uint32_t core_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ true);
1796   for (uint32_t i : LowToHighBits(core_spills)) {
1797     // If the register holds an object, update the stack mask.
1798     if (locations->RegisterContainsObject(i)) {
1799       locations->SetStackBit(stack_offset / kVRegSize);
1800     }
1801     DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
1802     DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
1803     saved_core_stack_offsets_[i] = stack_offset;
1804     stack_offset += codegen->SaveCoreRegister(stack_offset, i);
1805   }
1806 
1807   const uint32_t fp_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ false);
1808   for (uint32_t i : LowToHighBits(fp_spills)) {
1809     DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
1810     DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
1811     saved_fpu_stack_offsets_[i] = stack_offset;
1812     stack_offset += codegen->SaveFloatingPointRegister(stack_offset, i);
1813   }
1814 }
1815 
RestoreLiveRegisters(CodeGenerator * codegen,LocationSummary * locations)1816 void SlowPathCode::RestoreLiveRegisters(CodeGenerator* codegen, LocationSummary* locations) {
1817   size_t stack_offset = codegen->GetFirstRegisterSlotInSlowPath();
1818 
1819   const uint32_t core_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ true);
1820   for (uint32_t i : LowToHighBits(core_spills)) {
1821     DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
1822     DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
1823     stack_offset += codegen->RestoreCoreRegister(stack_offset, i);
1824   }
1825 
1826   const uint32_t fp_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ false);
1827   for (uint32_t i : LowToHighBits(fp_spills)) {
1828     DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
1829     DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
1830     stack_offset += codegen->RestoreFloatingPointRegister(stack_offset, i);
1831   }
1832 }
1833 
CreateSystemArrayCopyLocationSummary(HInvoke * invoke)1834 void CodeGenerator::CreateSystemArrayCopyLocationSummary(HInvoke* invoke) {
1835   // Check to see if we have known failures that will cause us to have to bail out
1836   // to the runtime, and just generate the runtime call directly.
1837   HIntConstant* src_pos = invoke->InputAt(1)->AsIntConstant();
1838   HIntConstant* dest_pos = invoke->InputAt(3)->AsIntConstant();
1839 
1840   // The positions must be non-negative.
1841   if ((src_pos != nullptr && src_pos->GetValue() < 0) ||
1842       (dest_pos != nullptr && dest_pos->GetValue() < 0)) {
1843     // We will have to fail anyways.
1844     return;
1845   }
1846 
1847   // The length must be >= 0.
1848   HIntConstant* length = invoke->InputAt(4)->AsIntConstant();
1849   if (length != nullptr) {
1850     int32_t len = length->GetValue();
1851     if (len < 0) {
1852       // Just call as normal.
1853       return;
1854     }
1855   }
1856 
1857   SystemArrayCopyOptimizations optimizations(invoke);
1858 
1859   if (optimizations.GetDestinationIsSource()) {
1860     if (src_pos != nullptr && dest_pos != nullptr && src_pos->GetValue() < dest_pos->GetValue()) {
1861       // We only support backward copying if source and destination are the same.
1862       return;
1863     }
1864   }
1865 
1866   if (optimizations.GetDestinationIsPrimitiveArray() || optimizations.GetSourceIsPrimitiveArray()) {
1867     // We currently don't intrinsify primitive copying.
1868     return;
1869   }
1870 
1871   ArenaAllocator* allocator = invoke->GetBlock()->GetGraph()->GetAllocator();
1872   LocationSummary* locations = new (allocator) LocationSummary(invoke,
1873                                                                LocationSummary::kCallOnSlowPath,
1874                                                                kIntrinsified);
1875   // arraycopy(Object src, int src_pos, Object dest, int dest_pos, int length).
1876   locations->SetInAt(0, Location::RequiresRegister());
1877   locations->SetInAt(1, Location::RegisterOrConstant(invoke->InputAt(1)));
1878   locations->SetInAt(2, Location::RequiresRegister());
1879   locations->SetInAt(3, Location::RegisterOrConstant(invoke->InputAt(3)));
1880   locations->SetInAt(4, Location::RegisterOrConstant(invoke->InputAt(4)));
1881 
1882   locations->AddTemp(Location::RequiresRegister());
1883   locations->AddTemp(Location::RequiresRegister());
1884   locations->AddTemp(Location::RequiresRegister());
1885 }
1886 
EmitJitRoots(uint8_t * code,const uint8_t * roots_data,std::vector<Handle<mirror::Object>> * roots)1887 void CodeGenerator::EmitJitRoots(uint8_t* code,
1888                                  const uint8_t* roots_data,
1889                                  /*out*/std::vector<Handle<mirror::Object>>* roots) {
1890   code_generation_data_->EmitJitRoots(roots);
1891   EmitJitRootPatches(code, roots_data);
1892 }
1893 
GetArrayAllocationEntrypoint(HNewArray * new_array)1894 QuickEntrypointEnum CodeGenerator::GetArrayAllocationEntrypoint(HNewArray* new_array) {
1895   switch (new_array->GetComponentSizeShift()) {
1896     case 0: return kQuickAllocArrayResolved8;
1897     case 1: return kQuickAllocArrayResolved16;
1898     case 2: return kQuickAllocArrayResolved32;
1899     case 3: return kQuickAllocArrayResolved64;
1900   }
1901   LOG(FATAL) << "Unreachable";
1902   UNREACHABLE();
1903 }
1904 
ScaleFactorForType(DataType::Type type)1905 ScaleFactor CodeGenerator::ScaleFactorForType(DataType::Type type) {
1906   switch (type) {
1907     case DataType::Type::kBool:
1908     case DataType::Type::kUint8:
1909     case DataType::Type::kInt8:
1910       return TIMES_1;
1911     case DataType::Type::kUint16:
1912     case DataType::Type::kInt16:
1913       return TIMES_2;
1914     case DataType::Type::kInt32:
1915     case DataType::Type::kUint32:
1916     case DataType::Type::kFloat32:
1917     case DataType::Type::kReference:
1918       return TIMES_4;
1919     case DataType::Type::kInt64:
1920     case DataType::Type::kUint64:
1921     case DataType::Type::kFloat64:
1922       return TIMES_8;
1923     case DataType::Type::kVoid:
1924       LOG(FATAL) << "Unreachable type " << type;
1925       UNREACHABLE();
1926   }
1927 }
1928 
1929 }  // namespace art
1930