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