1 /*
2 * Copyright (C) 2016 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_arm_vixl.h"
18
19 #include "arch/arm/asm_support_arm.h"
20 #include "arch/arm/instruction_set_features_arm.h"
21 #include "art_method-inl.h"
22 #include "base/bit_utils.h"
23 #include "base/bit_utils_iterator.h"
24 #include "class_table.h"
25 #include "code_generator_utils.h"
26 #include "common_arm.h"
27 #include "compiled_method.h"
28 #include "entrypoints/quick/quick_entrypoints.h"
29 #include "gc/accounting/card_table.h"
30 #include "gc/space/image_space.h"
31 #include "heap_poisoning.h"
32 #include "intrinsics.h"
33 #include "intrinsics_arm_vixl.h"
34 #include "linker/linker_patch.h"
35 #include "mirror/array-inl.h"
36 #include "mirror/class-inl.h"
37 #include "scoped_thread_state_change-inl.h"
38 #include "thread.h"
39 #include "utils/arm/assembler_arm_vixl.h"
40 #include "utils/arm/managed_register_arm.h"
41 #include "utils/assembler.h"
42 #include "utils/stack_checks.h"
43
44 namespace art {
45 namespace arm {
46
47 namespace vixl32 = vixl::aarch32;
48 using namespace vixl32; // NOLINT(build/namespaces)
49
50 using helpers::DRegisterFrom;
51 using helpers::HighRegisterFrom;
52 using helpers::InputDRegisterAt;
53 using helpers::InputOperandAt;
54 using helpers::InputRegister;
55 using helpers::InputRegisterAt;
56 using helpers::InputSRegisterAt;
57 using helpers::InputVRegister;
58 using helpers::InputVRegisterAt;
59 using helpers::Int32ConstantFrom;
60 using helpers::Int64ConstantFrom;
61 using helpers::LocationFrom;
62 using helpers::LowRegisterFrom;
63 using helpers::LowSRegisterFrom;
64 using helpers::OperandFrom;
65 using helpers::OutputRegister;
66 using helpers::OutputSRegister;
67 using helpers::OutputVRegister;
68 using helpers::RegisterFrom;
69 using helpers::SRegisterFrom;
70 using helpers::Uint64ConstantFrom;
71
72 using vixl::EmissionCheckScope;
73 using vixl::ExactAssemblyScope;
74 using vixl::CodeBufferCheckScope;
75
76 using RegisterList = vixl32::RegisterList;
77
ExpectedPairLayout(Location location)78 static bool ExpectedPairLayout(Location location) {
79 // We expected this for both core and fpu register pairs.
80 return ((location.low() & 1) == 0) && (location.low() + 1 == location.high());
81 }
82 // Use a local definition to prevent copying mistakes.
83 static constexpr size_t kArmWordSize = static_cast<size_t>(kArmPointerSize);
84 static constexpr size_t kArmBitsPerWord = kArmWordSize * kBitsPerByte;
85 static constexpr uint32_t kPackedSwitchCompareJumpThreshold = 7;
86
87 // Reference load (except object array loads) is using LDR Rt, [Rn, #offset] which can handle
88 // offset < 4KiB. For offsets >= 4KiB, the load shall be emitted as two or more instructions.
89 // For the Baker read barrier implementation using link-time generated thunks we need to split
90 // the offset explicitly.
91 constexpr uint32_t kReferenceLoadMinFarOffset = 4 * KB;
92
93 // Using a base helps identify when we hit Marking Register check breakpoints.
94 constexpr int kMarkingRegisterCheckBreakCodeBaseCode = 0x10;
95
96 #ifdef __
97 #error "ARM Codegen VIXL macro-assembler macro already defined."
98 #endif
99
100 // NOLINT on __ macro to suppress wrong warning/fix (misc-macro-parentheses) from clang-tidy.
101 #define __ down_cast<CodeGeneratorARMVIXL*>(codegen)->GetVIXLAssembler()-> // NOLINT
102 #define QUICK_ENTRY_POINT(x) QUICK_ENTRYPOINT_OFFSET(kArmPointerSize, x).Int32Value()
103
104 // Marker that code is yet to be, and must, be implemented.
105 #define TODO_VIXL32(level) LOG(level) << __PRETTY_FUNCTION__ << " unimplemented "
106
CanEmitNarrowLdr(vixl32::Register rt,vixl32::Register rn,uint32_t offset)107 static inline bool CanEmitNarrowLdr(vixl32::Register rt, vixl32::Register rn, uint32_t offset) {
108 return rt.IsLow() && rn.IsLow() && offset < 32u;
109 }
110
111 class EmitAdrCode {
112 public:
EmitAdrCode(ArmVIXLMacroAssembler * assembler,vixl32::Register rd,vixl32::Label * label)113 EmitAdrCode(ArmVIXLMacroAssembler* assembler, vixl32::Register rd, vixl32::Label* label)
114 : assembler_(assembler), rd_(rd), label_(label) {
115 DCHECK(!assembler->AllowMacroInstructions()); // In ExactAssemblyScope.
116 adr_location_ = assembler->GetCursorOffset();
117 assembler->adr(EncodingSize(Wide), rd, label);
118 }
119
~EmitAdrCode()120 ~EmitAdrCode() {
121 DCHECK(label_->IsBound());
122 // The ADR emitted by the assembler does not set the Thumb mode bit we need.
123 // TODO: Maybe extend VIXL to allow ADR for return address?
124 uint8_t* raw_adr = assembler_->GetBuffer()->GetOffsetAddress<uint8_t*>(adr_location_);
125 // Expecting ADR encoding T3 with `(offset & 1) == 0`.
126 DCHECK_EQ(raw_adr[1] & 0xfbu, 0xf2u); // Check bits 24-31, except 26.
127 DCHECK_EQ(raw_adr[0] & 0xffu, 0x0fu); // Check bits 16-23.
128 DCHECK_EQ(raw_adr[3] & 0x8fu, rd_.GetCode()); // Check bits 8-11 and 15.
129 DCHECK_EQ(raw_adr[2] & 0x01u, 0x00u); // Check bit 0, i.e. the `offset & 1`.
130 // Add the Thumb mode bit.
131 raw_adr[2] |= 0x01u;
132 }
133
134 private:
135 ArmVIXLMacroAssembler* const assembler_;
136 vixl32::Register rd_;
137 vixl32::Label* const label_;
138 int32_t adr_location_;
139 };
140
OneRegInReferenceOutSaveEverythingCallerSaves()141 static RegisterSet OneRegInReferenceOutSaveEverythingCallerSaves() {
142 InvokeRuntimeCallingConventionARMVIXL calling_convention;
143 RegisterSet caller_saves = RegisterSet::Empty();
144 caller_saves.Add(LocationFrom(calling_convention.GetRegisterAt(0)));
145 // TODO: Add GetReturnLocation() to the calling convention so that we can DCHECK()
146 // that the the kPrimNot result register is the same as the first argument register.
147 return caller_saves;
148 }
149
150 // SaveLiveRegisters and RestoreLiveRegisters from SlowPathCodeARM operate on sets of S registers,
151 // for each live D registers they treat two corresponding S registers as live ones.
152 //
153 // Two following functions (SaveContiguousSRegisterList, RestoreContiguousSRegisterList) build
154 // from a list of contiguous S registers a list of contiguous D registers (processing first/last
155 // S registers corner cases) and save/restore this new list treating them as D registers.
156 // - decreasing code size
157 // - avoiding hazards on Cortex-A57, when a pair of S registers for an actual live D register is
158 // restored and then used in regular non SlowPath code as D register.
159 //
160 // For the following example (v means the S register is live):
161 // D names: | D0 | D1 | D2 | D4 | ...
162 // S names: | S0 | S1 | S2 | S3 | S4 | S5 | S6 | S7 | ...
163 // Live? | | v | v | v | v | v | v | | ...
164 //
165 // S1 and S6 will be saved/restored independently; D registers list (D1, D2) will be processed
166 // as D registers.
167 //
168 // TODO(VIXL): All this code should be unnecessary once the VIXL AArch32 backend provides helpers
169 // for lists of floating-point registers.
SaveContiguousSRegisterList(size_t first,size_t last,CodeGenerator * codegen,size_t stack_offset)170 static size_t SaveContiguousSRegisterList(size_t first,
171 size_t last,
172 CodeGenerator* codegen,
173 size_t stack_offset) {
174 static_assert(kSRegSizeInBytes == kArmWordSize, "Broken assumption on reg/word sizes.");
175 static_assert(kDRegSizeInBytes == 2 * kArmWordSize, "Broken assumption on reg/word sizes.");
176 DCHECK_LE(first, last);
177 if ((first == last) && (first == 0)) {
178 __ Vstr(vixl32::SRegister(first), MemOperand(sp, stack_offset));
179 return stack_offset + kSRegSizeInBytes;
180 }
181 if (first % 2 == 1) {
182 __ Vstr(vixl32::SRegister(first++), MemOperand(sp, stack_offset));
183 stack_offset += kSRegSizeInBytes;
184 }
185
186 bool save_last = false;
187 if (last % 2 == 0) {
188 save_last = true;
189 --last;
190 }
191
192 if (first < last) {
193 vixl32::DRegister d_reg = vixl32::DRegister(first / 2);
194 DCHECK_EQ((last - first + 1) % 2, 0u);
195 size_t number_of_d_regs = (last - first + 1) / 2;
196
197 if (number_of_d_regs == 1) {
198 __ Vstr(d_reg, MemOperand(sp, stack_offset));
199 } else if (number_of_d_regs > 1) {
200 UseScratchRegisterScope temps(down_cast<CodeGeneratorARMVIXL*>(codegen)->GetVIXLAssembler());
201 vixl32::Register base = sp;
202 if (stack_offset != 0) {
203 base = temps.Acquire();
204 __ Add(base, sp, Operand::From(stack_offset));
205 }
206 __ Vstm(F64, base, NO_WRITE_BACK, DRegisterList(d_reg, number_of_d_regs));
207 }
208 stack_offset += number_of_d_regs * kDRegSizeInBytes;
209 }
210
211 if (save_last) {
212 __ Vstr(vixl32::SRegister(last + 1), MemOperand(sp, stack_offset));
213 stack_offset += kSRegSizeInBytes;
214 }
215
216 return stack_offset;
217 }
218
RestoreContiguousSRegisterList(size_t first,size_t last,CodeGenerator * codegen,size_t stack_offset)219 static size_t RestoreContiguousSRegisterList(size_t first,
220 size_t last,
221 CodeGenerator* codegen,
222 size_t stack_offset) {
223 static_assert(kSRegSizeInBytes == kArmWordSize, "Broken assumption on reg/word sizes.");
224 static_assert(kDRegSizeInBytes == 2 * kArmWordSize, "Broken assumption on reg/word sizes.");
225 DCHECK_LE(first, last);
226 if ((first == last) && (first == 0)) {
227 __ Vldr(vixl32::SRegister(first), MemOperand(sp, stack_offset));
228 return stack_offset + kSRegSizeInBytes;
229 }
230 if (first % 2 == 1) {
231 __ Vldr(vixl32::SRegister(first++), MemOperand(sp, stack_offset));
232 stack_offset += kSRegSizeInBytes;
233 }
234
235 bool restore_last = false;
236 if (last % 2 == 0) {
237 restore_last = true;
238 --last;
239 }
240
241 if (first < last) {
242 vixl32::DRegister d_reg = vixl32::DRegister(first / 2);
243 DCHECK_EQ((last - first + 1) % 2, 0u);
244 size_t number_of_d_regs = (last - first + 1) / 2;
245 if (number_of_d_regs == 1) {
246 __ Vldr(d_reg, MemOperand(sp, stack_offset));
247 } else if (number_of_d_regs > 1) {
248 UseScratchRegisterScope temps(down_cast<CodeGeneratorARMVIXL*>(codegen)->GetVIXLAssembler());
249 vixl32::Register base = sp;
250 if (stack_offset != 0) {
251 base = temps.Acquire();
252 __ Add(base, sp, Operand::From(stack_offset));
253 }
254 __ Vldm(F64, base, NO_WRITE_BACK, DRegisterList(d_reg, number_of_d_regs));
255 }
256 stack_offset += number_of_d_regs * kDRegSizeInBytes;
257 }
258
259 if (restore_last) {
260 __ Vldr(vixl32::SRegister(last + 1), MemOperand(sp, stack_offset));
261 stack_offset += kSRegSizeInBytes;
262 }
263
264 return stack_offset;
265 }
266
GetLoadOperandType(DataType::Type type)267 static LoadOperandType GetLoadOperandType(DataType::Type type) {
268 switch (type) {
269 case DataType::Type::kReference:
270 return kLoadWord;
271 case DataType::Type::kBool:
272 case DataType::Type::kUint8:
273 return kLoadUnsignedByte;
274 case DataType::Type::kInt8:
275 return kLoadSignedByte;
276 case DataType::Type::kUint16:
277 return kLoadUnsignedHalfword;
278 case DataType::Type::kInt16:
279 return kLoadSignedHalfword;
280 case DataType::Type::kInt32:
281 return kLoadWord;
282 case DataType::Type::kInt64:
283 return kLoadWordPair;
284 case DataType::Type::kFloat32:
285 return kLoadSWord;
286 case DataType::Type::kFloat64:
287 return kLoadDWord;
288 default:
289 LOG(FATAL) << "Unreachable type " << type;
290 UNREACHABLE();
291 }
292 }
293
GetStoreOperandType(DataType::Type type)294 static StoreOperandType GetStoreOperandType(DataType::Type type) {
295 switch (type) {
296 case DataType::Type::kReference:
297 return kStoreWord;
298 case DataType::Type::kBool:
299 case DataType::Type::kUint8:
300 case DataType::Type::kInt8:
301 return kStoreByte;
302 case DataType::Type::kUint16:
303 case DataType::Type::kInt16:
304 return kStoreHalfword;
305 case DataType::Type::kInt32:
306 return kStoreWord;
307 case DataType::Type::kInt64:
308 return kStoreWordPair;
309 case DataType::Type::kFloat32:
310 return kStoreSWord;
311 case DataType::Type::kFloat64:
312 return kStoreDWord;
313 default:
314 LOG(FATAL) << "Unreachable type " << type;
315 UNREACHABLE();
316 }
317 }
318
SaveLiveRegisters(CodeGenerator * codegen,LocationSummary * locations)319 void SlowPathCodeARMVIXL::SaveLiveRegisters(CodeGenerator* codegen, LocationSummary* locations) {
320 size_t stack_offset = codegen->GetFirstRegisterSlotInSlowPath();
321 size_t orig_offset = stack_offset;
322
323 const uint32_t core_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ true);
324 for (uint32_t i : LowToHighBits(core_spills)) {
325 // If the register holds an object, update the stack mask.
326 if (locations->RegisterContainsObject(i)) {
327 locations->SetStackBit(stack_offset / kVRegSize);
328 }
329 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
330 DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
331 saved_core_stack_offsets_[i] = stack_offset;
332 stack_offset += kArmWordSize;
333 }
334
335 CodeGeneratorARMVIXL* arm_codegen = down_cast<CodeGeneratorARMVIXL*>(codegen);
336 arm_codegen->GetAssembler()->StoreRegisterList(core_spills, orig_offset);
337
338 uint32_t fp_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ false);
339 orig_offset = stack_offset;
340 for (uint32_t i : LowToHighBits(fp_spills)) {
341 DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
342 saved_fpu_stack_offsets_[i] = stack_offset;
343 stack_offset += kArmWordSize;
344 }
345
346 stack_offset = orig_offset;
347 while (fp_spills != 0u) {
348 uint32_t begin = CTZ(fp_spills);
349 uint32_t tmp = fp_spills + (1u << begin);
350 fp_spills &= tmp; // Clear the contiguous range of 1s.
351 uint32_t end = (tmp == 0u) ? 32u : CTZ(tmp); // CTZ(0) is undefined.
352 stack_offset = SaveContiguousSRegisterList(begin, end - 1, codegen, stack_offset);
353 }
354 DCHECK_LE(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
355 }
356
RestoreLiveRegisters(CodeGenerator * codegen,LocationSummary * locations)357 void SlowPathCodeARMVIXL::RestoreLiveRegisters(CodeGenerator* codegen, LocationSummary* locations) {
358 size_t stack_offset = codegen->GetFirstRegisterSlotInSlowPath();
359 size_t orig_offset = stack_offset;
360
361 const uint32_t core_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ true);
362 for (uint32_t i : LowToHighBits(core_spills)) {
363 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
364 DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
365 stack_offset += kArmWordSize;
366 }
367
368 // TODO(VIXL): Check the coherency of stack_offset after this with a test.
369 CodeGeneratorARMVIXL* arm_codegen = down_cast<CodeGeneratorARMVIXL*>(codegen);
370 arm_codegen->GetAssembler()->LoadRegisterList(core_spills, orig_offset);
371
372 uint32_t fp_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ false);
373 while (fp_spills != 0u) {
374 uint32_t begin = CTZ(fp_spills);
375 uint32_t tmp = fp_spills + (1u << begin);
376 fp_spills &= tmp; // Clear the contiguous range of 1s.
377 uint32_t end = (tmp == 0u) ? 32u : CTZ(tmp); // CTZ(0) is undefined.
378 stack_offset = RestoreContiguousSRegisterList(begin, end - 1, codegen, stack_offset);
379 }
380 DCHECK_LE(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
381 }
382
383 class NullCheckSlowPathARMVIXL : public SlowPathCodeARMVIXL {
384 public:
NullCheckSlowPathARMVIXL(HNullCheck * instruction)385 explicit NullCheckSlowPathARMVIXL(HNullCheck* instruction) : SlowPathCodeARMVIXL(instruction) {}
386
EmitNativeCode(CodeGenerator * codegen)387 void EmitNativeCode(CodeGenerator* codegen) override {
388 CodeGeneratorARMVIXL* arm_codegen = down_cast<CodeGeneratorARMVIXL*>(codegen);
389 __ Bind(GetEntryLabel());
390 if (instruction_->CanThrowIntoCatchBlock()) {
391 // Live registers will be restored in the catch block if caught.
392 SaveLiveRegisters(codegen, instruction_->GetLocations());
393 }
394 arm_codegen->InvokeRuntime(kQuickThrowNullPointer,
395 instruction_,
396 instruction_->GetDexPc(),
397 this);
398 CheckEntrypointTypes<kQuickThrowNullPointer, void, void>();
399 }
400
IsFatal() const401 bool IsFatal() const override { return true; }
402
GetDescription() const403 const char* GetDescription() const override { return "NullCheckSlowPathARMVIXL"; }
404
405 private:
406 DISALLOW_COPY_AND_ASSIGN(NullCheckSlowPathARMVIXL);
407 };
408
409 class DivZeroCheckSlowPathARMVIXL : public SlowPathCodeARMVIXL {
410 public:
DivZeroCheckSlowPathARMVIXL(HDivZeroCheck * instruction)411 explicit DivZeroCheckSlowPathARMVIXL(HDivZeroCheck* instruction)
412 : SlowPathCodeARMVIXL(instruction) {}
413
EmitNativeCode(CodeGenerator * codegen)414 void EmitNativeCode(CodeGenerator* codegen) override {
415 CodeGeneratorARMVIXL* arm_codegen = down_cast<CodeGeneratorARMVIXL*>(codegen);
416 __ Bind(GetEntryLabel());
417 arm_codegen->InvokeRuntime(kQuickThrowDivZero, instruction_, instruction_->GetDexPc(), this);
418 CheckEntrypointTypes<kQuickThrowDivZero, void, void>();
419 }
420
IsFatal() const421 bool IsFatal() const override { return true; }
422
GetDescription() const423 const char* GetDescription() const override { return "DivZeroCheckSlowPathARMVIXL"; }
424
425 private:
426 DISALLOW_COPY_AND_ASSIGN(DivZeroCheckSlowPathARMVIXL);
427 };
428
429 class SuspendCheckSlowPathARMVIXL : public SlowPathCodeARMVIXL {
430 public:
SuspendCheckSlowPathARMVIXL(HSuspendCheck * instruction,HBasicBlock * successor)431 SuspendCheckSlowPathARMVIXL(HSuspendCheck* instruction, HBasicBlock* successor)
432 : SlowPathCodeARMVIXL(instruction), successor_(successor) {}
433
EmitNativeCode(CodeGenerator * codegen)434 void EmitNativeCode(CodeGenerator* codegen) override {
435 CodeGeneratorARMVIXL* arm_codegen = down_cast<CodeGeneratorARMVIXL*>(codegen);
436 __ Bind(GetEntryLabel());
437 arm_codegen->InvokeRuntime(kQuickTestSuspend, instruction_, instruction_->GetDexPc(), this);
438 CheckEntrypointTypes<kQuickTestSuspend, void, void>();
439 if (successor_ == nullptr) {
440 __ B(GetReturnLabel());
441 } else {
442 __ B(arm_codegen->GetLabelOf(successor_));
443 }
444 }
445
GetReturnLabel()446 vixl32::Label* GetReturnLabel() {
447 DCHECK(successor_ == nullptr);
448 return &return_label_;
449 }
450
GetSuccessor() const451 HBasicBlock* GetSuccessor() const {
452 return successor_;
453 }
454
GetDescription() const455 const char* GetDescription() const override { return "SuspendCheckSlowPathARMVIXL"; }
456
457 private:
458 // If not null, the block to branch to after the suspend check.
459 HBasicBlock* const successor_;
460
461 // If `successor_` is null, the label to branch to after the suspend check.
462 vixl32::Label return_label_;
463
464 DISALLOW_COPY_AND_ASSIGN(SuspendCheckSlowPathARMVIXL);
465 };
466
467 class BoundsCheckSlowPathARMVIXL : public SlowPathCodeARMVIXL {
468 public:
BoundsCheckSlowPathARMVIXL(HBoundsCheck * instruction)469 explicit BoundsCheckSlowPathARMVIXL(HBoundsCheck* instruction)
470 : SlowPathCodeARMVIXL(instruction) {}
471
EmitNativeCode(CodeGenerator * codegen)472 void EmitNativeCode(CodeGenerator* codegen) override {
473 CodeGeneratorARMVIXL* arm_codegen = down_cast<CodeGeneratorARMVIXL*>(codegen);
474 LocationSummary* locations = instruction_->GetLocations();
475
476 __ Bind(GetEntryLabel());
477 if (instruction_->CanThrowIntoCatchBlock()) {
478 // Live registers will be restored in the catch block if caught.
479 SaveLiveRegisters(codegen, instruction_->GetLocations());
480 }
481 // We're moving two locations to locations that could overlap, so we need a parallel
482 // move resolver.
483 InvokeRuntimeCallingConventionARMVIXL calling_convention;
484 codegen->EmitParallelMoves(
485 locations->InAt(0),
486 LocationFrom(calling_convention.GetRegisterAt(0)),
487 DataType::Type::kInt32,
488 locations->InAt(1),
489 LocationFrom(calling_convention.GetRegisterAt(1)),
490 DataType::Type::kInt32);
491 QuickEntrypointEnum entrypoint = instruction_->AsBoundsCheck()->IsStringCharAt()
492 ? kQuickThrowStringBounds
493 : kQuickThrowArrayBounds;
494 arm_codegen->InvokeRuntime(entrypoint, instruction_, instruction_->GetDexPc(), this);
495 CheckEntrypointTypes<kQuickThrowStringBounds, void, int32_t, int32_t>();
496 CheckEntrypointTypes<kQuickThrowArrayBounds, void, int32_t, int32_t>();
497 }
498
IsFatal() const499 bool IsFatal() const override { return true; }
500
GetDescription() const501 const char* GetDescription() const override { return "BoundsCheckSlowPathARMVIXL"; }
502
503 private:
504 DISALLOW_COPY_AND_ASSIGN(BoundsCheckSlowPathARMVIXL);
505 };
506
507 class LoadClassSlowPathARMVIXL : public SlowPathCodeARMVIXL {
508 public:
LoadClassSlowPathARMVIXL(HLoadClass * cls,HInstruction * at)509 LoadClassSlowPathARMVIXL(HLoadClass* cls, HInstruction* at)
510 : SlowPathCodeARMVIXL(at), cls_(cls) {
511 DCHECK(at->IsLoadClass() || at->IsClinitCheck());
512 DCHECK_EQ(instruction_->IsLoadClass(), cls_ == instruction_);
513 }
514
EmitNativeCode(CodeGenerator * codegen)515 void EmitNativeCode(CodeGenerator* codegen) override {
516 LocationSummary* locations = instruction_->GetLocations();
517 Location out = locations->Out();
518 const uint32_t dex_pc = instruction_->GetDexPc();
519 bool must_resolve_type = instruction_->IsLoadClass() && cls_->MustResolveTypeOnSlowPath();
520 bool must_do_clinit = instruction_->IsClinitCheck() || cls_->MustGenerateClinitCheck();
521
522 CodeGeneratorARMVIXL* arm_codegen = down_cast<CodeGeneratorARMVIXL*>(codegen);
523 __ Bind(GetEntryLabel());
524 SaveLiveRegisters(codegen, locations);
525
526 InvokeRuntimeCallingConventionARMVIXL calling_convention;
527 if (must_resolve_type) {
528 DCHECK(IsSameDexFile(cls_->GetDexFile(), arm_codegen->GetGraph()->GetDexFile()));
529 dex::TypeIndex type_index = cls_->GetTypeIndex();
530 __ Mov(calling_convention.GetRegisterAt(0), type_index.index_);
531 arm_codegen->InvokeRuntime(kQuickResolveType, instruction_, dex_pc, this);
532 CheckEntrypointTypes<kQuickResolveType, void*, uint32_t>();
533 // If we also must_do_clinit, the resolved type is now in the correct register.
534 } else {
535 DCHECK(must_do_clinit);
536 Location source = instruction_->IsLoadClass() ? out : locations->InAt(0);
537 arm_codegen->Move32(LocationFrom(calling_convention.GetRegisterAt(0)), source);
538 }
539 if (must_do_clinit) {
540 arm_codegen->InvokeRuntime(kQuickInitializeStaticStorage, instruction_, dex_pc, this);
541 CheckEntrypointTypes<kQuickInitializeStaticStorage, void*, mirror::Class*>();
542 }
543
544 // Move the class to the desired location.
545 if (out.IsValid()) {
546 DCHECK(out.IsRegister() && !locations->GetLiveRegisters()->ContainsCoreRegister(out.reg()));
547 arm_codegen->Move32(locations->Out(), LocationFrom(r0));
548 }
549 RestoreLiveRegisters(codegen, locations);
550 __ B(GetExitLabel());
551 }
552
GetDescription() const553 const char* GetDescription() const override { return "LoadClassSlowPathARMVIXL"; }
554
555 private:
556 // The class this slow path will load.
557 HLoadClass* const cls_;
558
559 DISALLOW_COPY_AND_ASSIGN(LoadClassSlowPathARMVIXL);
560 };
561
562 class LoadStringSlowPathARMVIXL : public SlowPathCodeARMVIXL {
563 public:
LoadStringSlowPathARMVIXL(HLoadString * instruction)564 explicit LoadStringSlowPathARMVIXL(HLoadString* instruction)
565 : SlowPathCodeARMVIXL(instruction) {}
566
EmitNativeCode(CodeGenerator * codegen)567 void EmitNativeCode(CodeGenerator* codegen) override {
568 DCHECK(instruction_->IsLoadString());
569 DCHECK_EQ(instruction_->AsLoadString()->GetLoadKind(), HLoadString::LoadKind::kBssEntry);
570 LocationSummary* locations = instruction_->GetLocations();
571 DCHECK(!locations->GetLiveRegisters()->ContainsCoreRegister(locations->Out().reg()));
572 const dex::StringIndex string_index = instruction_->AsLoadString()->GetStringIndex();
573
574 CodeGeneratorARMVIXL* arm_codegen = down_cast<CodeGeneratorARMVIXL*>(codegen);
575 __ Bind(GetEntryLabel());
576 SaveLiveRegisters(codegen, locations);
577
578 InvokeRuntimeCallingConventionARMVIXL calling_convention;
579 __ Mov(calling_convention.GetRegisterAt(0), string_index.index_);
580 arm_codegen->InvokeRuntime(kQuickResolveString, instruction_, instruction_->GetDexPc(), this);
581 CheckEntrypointTypes<kQuickResolveString, void*, uint32_t>();
582
583 arm_codegen->Move32(locations->Out(), LocationFrom(r0));
584 RestoreLiveRegisters(codegen, locations);
585
586 __ B(GetExitLabel());
587 }
588
GetDescription() const589 const char* GetDescription() const override { return "LoadStringSlowPathARMVIXL"; }
590
591 private:
592 DISALLOW_COPY_AND_ASSIGN(LoadStringSlowPathARMVIXL);
593 };
594
595 class TypeCheckSlowPathARMVIXL : public SlowPathCodeARMVIXL {
596 public:
TypeCheckSlowPathARMVIXL(HInstruction * instruction,bool is_fatal)597 TypeCheckSlowPathARMVIXL(HInstruction* instruction, bool is_fatal)
598 : SlowPathCodeARMVIXL(instruction), is_fatal_(is_fatal) {}
599
EmitNativeCode(CodeGenerator * codegen)600 void EmitNativeCode(CodeGenerator* codegen) override {
601 LocationSummary* locations = instruction_->GetLocations();
602 DCHECK(instruction_->IsCheckCast()
603 || !locations->GetLiveRegisters()->ContainsCoreRegister(locations->Out().reg()));
604
605 CodeGeneratorARMVIXL* arm_codegen = down_cast<CodeGeneratorARMVIXL*>(codegen);
606 __ Bind(GetEntryLabel());
607
608 if (!is_fatal_ || instruction_->CanThrowIntoCatchBlock()) {
609 SaveLiveRegisters(codegen, locations);
610 }
611
612 // We're moving two locations to locations that could overlap, so we need a parallel
613 // move resolver.
614 InvokeRuntimeCallingConventionARMVIXL calling_convention;
615
616 codegen->EmitParallelMoves(locations->InAt(0),
617 LocationFrom(calling_convention.GetRegisterAt(0)),
618 DataType::Type::kReference,
619 locations->InAt(1),
620 LocationFrom(calling_convention.GetRegisterAt(1)),
621 DataType::Type::kReference);
622 if (instruction_->IsInstanceOf()) {
623 arm_codegen->InvokeRuntime(kQuickInstanceofNonTrivial,
624 instruction_,
625 instruction_->GetDexPc(),
626 this);
627 CheckEntrypointTypes<kQuickInstanceofNonTrivial, size_t, mirror::Object*, mirror::Class*>();
628 arm_codegen->Move32(locations->Out(), LocationFrom(r0));
629 } else {
630 DCHECK(instruction_->IsCheckCast());
631 arm_codegen->InvokeRuntime(kQuickCheckInstanceOf,
632 instruction_,
633 instruction_->GetDexPc(),
634 this);
635 CheckEntrypointTypes<kQuickCheckInstanceOf, void, mirror::Object*, mirror::Class*>();
636 }
637
638 if (!is_fatal_) {
639 RestoreLiveRegisters(codegen, locations);
640 __ B(GetExitLabel());
641 }
642 }
643
GetDescription() const644 const char* GetDescription() const override { return "TypeCheckSlowPathARMVIXL"; }
645
IsFatal() const646 bool IsFatal() const override { return is_fatal_; }
647
648 private:
649 const bool is_fatal_;
650
651 DISALLOW_COPY_AND_ASSIGN(TypeCheckSlowPathARMVIXL);
652 };
653
654 class DeoptimizationSlowPathARMVIXL : public SlowPathCodeARMVIXL {
655 public:
DeoptimizationSlowPathARMVIXL(HDeoptimize * instruction)656 explicit DeoptimizationSlowPathARMVIXL(HDeoptimize* instruction)
657 : SlowPathCodeARMVIXL(instruction) {}
658
EmitNativeCode(CodeGenerator * codegen)659 void EmitNativeCode(CodeGenerator* codegen) override {
660 CodeGeneratorARMVIXL* arm_codegen = down_cast<CodeGeneratorARMVIXL*>(codegen);
661 __ Bind(GetEntryLabel());
662 LocationSummary* locations = instruction_->GetLocations();
663 SaveLiveRegisters(codegen, locations);
664 InvokeRuntimeCallingConventionARMVIXL calling_convention;
665 __ Mov(calling_convention.GetRegisterAt(0),
666 static_cast<uint32_t>(instruction_->AsDeoptimize()->GetDeoptimizationKind()));
667
668 arm_codegen->InvokeRuntime(kQuickDeoptimize, instruction_, instruction_->GetDexPc(), this);
669 CheckEntrypointTypes<kQuickDeoptimize, void, DeoptimizationKind>();
670 }
671
GetDescription() const672 const char* GetDescription() const override { return "DeoptimizationSlowPathARMVIXL"; }
673
674 private:
675 DISALLOW_COPY_AND_ASSIGN(DeoptimizationSlowPathARMVIXL);
676 };
677
678 class ArraySetSlowPathARMVIXL : public SlowPathCodeARMVIXL {
679 public:
ArraySetSlowPathARMVIXL(HInstruction * instruction)680 explicit ArraySetSlowPathARMVIXL(HInstruction* instruction) : SlowPathCodeARMVIXL(instruction) {}
681
EmitNativeCode(CodeGenerator * codegen)682 void EmitNativeCode(CodeGenerator* codegen) override {
683 LocationSummary* locations = instruction_->GetLocations();
684 __ Bind(GetEntryLabel());
685 SaveLiveRegisters(codegen, locations);
686
687 InvokeRuntimeCallingConventionARMVIXL calling_convention;
688 HParallelMove parallel_move(codegen->GetGraph()->GetAllocator());
689 parallel_move.AddMove(
690 locations->InAt(0),
691 LocationFrom(calling_convention.GetRegisterAt(0)),
692 DataType::Type::kReference,
693 nullptr);
694 parallel_move.AddMove(
695 locations->InAt(1),
696 LocationFrom(calling_convention.GetRegisterAt(1)),
697 DataType::Type::kInt32,
698 nullptr);
699 parallel_move.AddMove(
700 locations->InAt(2),
701 LocationFrom(calling_convention.GetRegisterAt(2)),
702 DataType::Type::kReference,
703 nullptr);
704 codegen->GetMoveResolver()->EmitNativeCode(¶llel_move);
705
706 CodeGeneratorARMVIXL* arm_codegen = down_cast<CodeGeneratorARMVIXL*>(codegen);
707 arm_codegen->InvokeRuntime(kQuickAputObject, instruction_, instruction_->GetDexPc(), this);
708 CheckEntrypointTypes<kQuickAputObject, void, mirror::Array*, int32_t, mirror::Object*>();
709 RestoreLiveRegisters(codegen, locations);
710 __ B(GetExitLabel());
711 }
712
GetDescription() const713 const char* GetDescription() const override { return "ArraySetSlowPathARMVIXL"; }
714
715 private:
716 DISALLOW_COPY_AND_ASSIGN(ArraySetSlowPathARMVIXL);
717 };
718
719 // Slow path generating a read barrier for a heap reference.
720 class ReadBarrierForHeapReferenceSlowPathARMVIXL : public SlowPathCodeARMVIXL {
721 public:
ReadBarrierForHeapReferenceSlowPathARMVIXL(HInstruction * instruction,Location out,Location ref,Location obj,uint32_t offset,Location index)722 ReadBarrierForHeapReferenceSlowPathARMVIXL(HInstruction* instruction,
723 Location out,
724 Location ref,
725 Location obj,
726 uint32_t offset,
727 Location index)
728 : SlowPathCodeARMVIXL(instruction),
729 out_(out),
730 ref_(ref),
731 obj_(obj),
732 offset_(offset),
733 index_(index) {
734 DCHECK(kEmitCompilerReadBarrier);
735 // If `obj` is equal to `out` or `ref`, it means the initial object
736 // has been overwritten by (or after) the heap object reference load
737 // to be instrumented, e.g.:
738 //
739 // __ LoadFromOffset(kLoadWord, out, out, offset);
740 // codegen_->GenerateReadBarrierSlow(instruction, out_loc, out_loc, out_loc, offset);
741 //
742 // In that case, we have lost the information about the original
743 // object, and the emitted read barrier cannot work properly.
744 DCHECK(!obj.Equals(out)) << "obj=" << obj << " out=" << out;
745 DCHECK(!obj.Equals(ref)) << "obj=" << obj << " ref=" << ref;
746 }
747
EmitNativeCode(CodeGenerator * codegen)748 void EmitNativeCode(CodeGenerator* codegen) override {
749 CodeGeneratorARMVIXL* arm_codegen = down_cast<CodeGeneratorARMVIXL*>(codegen);
750 LocationSummary* locations = instruction_->GetLocations();
751 vixl32::Register reg_out = RegisterFrom(out_);
752 DCHECK(locations->CanCall());
753 DCHECK(!locations->GetLiveRegisters()->ContainsCoreRegister(reg_out.GetCode()));
754 DCHECK(instruction_->IsInstanceFieldGet() ||
755 instruction_->IsStaticFieldGet() ||
756 instruction_->IsArrayGet() ||
757 instruction_->IsInstanceOf() ||
758 instruction_->IsCheckCast() ||
759 (instruction_->IsInvokeVirtual() && instruction_->GetLocations()->Intrinsified()))
760 << "Unexpected instruction in read barrier for heap reference slow path: "
761 << instruction_->DebugName();
762 // The read barrier instrumentation of object ArrayGet
763 // instructions does not support the HIntermediateAddress
764 // instruction.
765 DCHECK(!(instruction_->IsArrayGet() &&
766 instruction_->AsArrayGet()->GetArray()->IsIntermediateAddress()));
767
768 __ Bind(GetEntryLabel());
769 SaveLiveRegisters(codegen, locations);
770
771 // We may have to change the index's value, but as `index_` is a
772 // constant member (like other "inputs" of this slow path),
773 // introduce a copy of it, `index`.
774 Location index = index_;
775 if (index_.IsValid()) {
776 // Handle `index_` for HArrayGet and UnsafeGetObject/UnsafeGetObjectVolatile intrinsics.
777 if (instruction_->IsArrayGet()) {
778 // Compute the actual memory offset and store it in `index`.
779 vixl32::Register index_reg = RegisterFrom(index_);
780 DCHECK(locations->GetLiveRegisters()->ContainsCoreRegister(index_reg.GetCode()));
781 if (codegen->IsCoreCalleeSaveRegister(index_reg.GetCode())) {
782 // We are about to change the value of `index_reg` (see the
783 // calls to art::arm::ArmVIXLMacroAssembler::Lsl and
784 // art::arm::ArmVIXLMacroAssembler::Add below), but it has
785 // not been saved by the previous call to
786 // art::SlowPathCode::SaveLiveRegisters, as it is a
787 // callee-save register --
788 // art::SlowPathCode::SaveLiveRegisters does not consider
789 // callee-save registers, as it has been designed with the
790 // assumption that callee-save registers are supposed to be
791 // handled by the called function. So, as a callee-save
792 // register, `index_reg` _would_ eventually be saved onto
793 // the stack, but it would be too late: we would have
794 // changed its value earlier. Therefore, we manually save
795 // it here into another freely available register,
796 // `free_reg`, chosen of course among the caller-save
797 // registers (as a callee-save `free_reg` register would
798 // exhibit the same problem).
799 //
800 // Note we could have requested a temporary register from
801 // the register allocator instead; but we prefer not to, as
802 // this is a slow path, and we know we can find a
803 // caller-save register that is available.
804 vixl32::Register free_reg = FindAvailableCallerSaveRegister(codegen);
805 __ Mov(free_reg, index_reg);
806 index_reg = free_reg;
807 index = LocationFrom(index_reg);
808 } else {
809 // The initial register stored in `index_` has already been
810 // saved in the call to art::SlowPathCode::SaveLiveRegisters
811 // (as it is not a callee-save register), so we can freely
812 // use it.
813 }
814 // Shifting the index value contained in `index_reg` by the scale
815 // factor (2) cannot overflow in practice, as the runtime is
816 // unable to allocate object arrays with a size larger than
817 // 2^26 - 1 (that is, 2^28 - 4 bytes).
818 __ Lsl(index_reg, index_reg, TIMES_4);
819 static_assert(
820 sizeof(mirror::HeapReference<mirror::Object>) == sizeof(int32_t),
821 "art::mirror::HeapReference<art::mirror::Object> and int32_t have different sizes.");
822 __ Add(index_reg, index_reg, offset_);
823 } else {
824 // In the case of the UnsafeGetObject/UnsafeGetObjectVolatile
825 // intrinsics, `index_` is not shifted by a scale factor of 2
826 // (as in the case of ArrayGet), as it is actually an offset
827 // to an object field within an object.
828 DCHECK(instruction_->IsInvoke()) << instruction_->DebugName();
829 DCHECK(instruction_->GetLocations()->Intrinsified());
830 DCHECK((instruction_->AsInvoke()->GetIntrinsic() == Intrinsics::kUnsafeGetObject) ||
831 (instruction_->AsInvoke()->GetIntrinsic() == Intrinsics::kUnsafeGetObjectVolatile))
832 << instruction_->AsInvoke()->GetIntrinsic();
833 DCHECK_EQ(offset_, 0U);
834 DCHECK(index_.IsRegisterPair());
835 // UnsafeGet's offset location is a register pair, the low
836 // part contains the correct offset.
837 index = index_.ToLow();
838 }
839 }
840
841 // We're moving two or three locations to locations that could
842 // overlap, so we need a parallel move resolver.
843 InvokeRuntimeCallingConventionARMVIXL calling_convention;
844 HParallelMove parallel_move(codegen->GetGraph()->GetAllocator());
845 parallel_move.AddMove(ref_,
846 LocationFrom(calling_convention.GetRegisterAt(0)),
847 DataType::Type::kReference,
848 nullptr);
849 parallel_move.AddMove(obj_,
850 LocationFrom(calling_convention.GetRegisterAt(1)),
851 DataType::Type::kReference,
852 nullptr);
853 if (index.IsValid()) {
854 parallel_move.AddMove(index,
855 LocationFrom(calling_convention.GetRegisterAt(2)),
856 DataType::Type::kInt32,
857 nullptr);
858 codegen->GetMoveResolver()->EmitNativeCode(¶llel_move);
859 } else {
860 codegen->GetMoveResolver()->EmitNativeCode(¶llel_move);
861 __ Mov(calling_convention.GetRegisterAt(2), offset_);
862 }
863 arm_codegen->InvokeRuntime(kQuickReadBarrierSlow, instruction_, instruction_->GetDexPc(), this);
864 CheckEntrypointTypes<
865 kQuickReadBarrierSlow, mirror::Object*, mirror::Object*, mirror::Object*, uint32_t>();
866 arm_codegen->Move32(out_, LocationFrom(r0));
867
868 RestoreLiveRegisters(codegen, locations);
869 __ B(GetExitLabel());
870 }
871
GetDescription() const872 const char* GetDescription() const override {
873 return "ReadBarrierForHeapReferenceSlowPathARMVIXL";
874 }
875
876 private:
FindAvailableCallerSaveRegister(CodeGenerator * codegen)877 vixl32::Register FindAvailableCallerSaveRegister(CodeGenerator* codegen) {
878 uint32_t ref = RegisterFrom(ref_).GetCode();
879 uint32_t obj = RegisterFrom(obj_).GetCode();
880 for (uint32_t i = 0, e = codegen->GetNumberOfCoreRegisters(); i < e; ++i) {
881 if (i != ref && i != obj && !codegen->IsCoreCalleeSaveRegister(i)) {
882 return vixl32::Register(i);
883 }
884 }
885 // We shall never fail to find a free caller-save register, as
886 // there are more than two core caller-save registers on ARM
887 // (meaning it is possible to find one which is different from
888 // `ref` and `obj`).
889 DCHECK_GT(codegen->GetNumberOfCoreCallerSaveRegisters(), 2u);
890 LOG(FATAL) << "Could not find a free caller-save register";
891 UNREACHABLE();
892 }
893
894 const Location out_;
895 const Location ref_;
896 const Location obj_;
897 const uint32_t offset_;
898 // An additional location containing an index to an array.
899 // Only used for HArrayGet and the UnsafeGetObject &
900 // UnsafeGetObjectVolatile intrinsics.
901 const Location index_;
902
903 DISALLOW_COPY_AND_ASSIGN(ReadBarrierForHeapReferenceSlowPathARMVIXL);
904 };
905
906 // Slow path generating a read barrier for a GC root.
907 class ReadBarrierForRootSlowPathARMVIXL : public SlowPathCodeARMVIXL {
908 public:
ReadBarrierForRootSlowPathARMVIXL(HInstruction * instruction,Location out,Location root)909 ReadBarrierForRootSlowPathARMVIXL(HInstruction* instruction, Location out, Location root)
910 : SlowPathCodeARMVIXL(instruction), out_(out), root_(root) {
911 DCHECK(kEmitCompilerReadBarrier);
912 }
913
EmitNativeCode(CodeGenerator * codegen)914 void EmitNativeCode(CodeGenerator* codegen) override {
915 LocationSummary* locations = instruction_->GetLocations();
916 vixl32::Register reg_out = RegisterFrom(out_);
917 DCHECK(locations->CanCall());
918 DCHECK(!locations->GetLiveRegisters()->ContainsCoreRegister(reg_out.GetCode()));
919 DCHECK(instruction_->IsLoadClass() || instruction_->IsLoadString())
920 << "Unexpected instruction in read barrier for GC root slow path: "
921 << instruction_->DebugName();
922
923 __ Bind(GetEntryLabel());
924 SaveLiveRegisters(codegen, locations);
925
926 InvokeRuntimeCallingConventionARMVIXL calling_convention;
927 CodeGeneratorARMVIXL* arm_codegen = down_cast<CodeGeneratorARMVIXL*>(codegen);
928 arm_codegen->Move32(LocationFrom(calling_convention.GetRegisterAt(0)), root_);
929 arm_codegen->InvokeRuntime(kQuickReadBarrierForRootSlow,
930 instruction_,
931 instruction_->GetDexPc(),
932 this);
933 CheckEntrypointTypes<kQuickReadBarrierForRootSlow, mirror::Object*, GcRoot<mirror::Object>*>();
934 arm_codegen->Move32(out_, LocationFrom(r0));
935
936 RestoreLiveRegisters(codegen, locations);
937 __ B(GetExitLabel());
938 }
939
GetDescription() const940 const char* GetDescription() const override { return "ReadBarrierForRootSlowPathARMVIXL"; }
941
942 private:
943 const Location out_;
944 const Location root_;
945
946 DISALLOW_COPY_AND_ASSIGN(ReadBarrierForRootSlowPathARMVIXL);
947 };
948
ARMCondition(IfCondition cond)949 inline vixl32::Condition ARMCondition(IfCondition cond) {
950 switch (cond) {
951 case kCondEQ: return eq;
952 case kCondNE: return ne;
953 case kCondLT: return lt;
954 case kCondLE: return le;
955 case kCondGT: return gt;
956 case kCondGE: return ge;
957 case kCondB: return lo;
958 case kCondBE: return ls;
959 case kCondA: return hi;
960 case kCondAE: return hs;
961 }
962 LOG(FATAL) << "Unreachable";
963 UNREACHABLE();
964 }
965
966 // Maps signed condition to unsigned condition.
ARMUnsignedCondition(IfCondition cond)967 inline vixl32::Condition ARMUnsignedCondition(IfCondition cond) {
968 switch (cond) {
969 case kCondEQ: return eq;
970 case kCondNE: return ne;
971 // Signed to unsigned.
972 case kCondLT: return lo;
973 case kCondLE: return ls;
974 case kCondGT: return hi;
975 case kCondGE: return hs;
976 // Unsigned remain unchanged.
977 case kCondB: return lo;
978 case kCondBE: return ls;
979 case kCondA: return hi;
980 case kCondAE: return hs;
981 }
982 LOG(FATAL) << "Unreachable";
983 UNREACHABLE();
984 }
985
ARMFPCondition(IfCondition cond,bool gt_bias)986 inline vixl32::Condition ARMFPCondition(IfCondition cond, bool gt_bias) {
987 // The ARM condition codes can express all the necessary branches, see the
988 // "Meaning (floating-point)" column in the table A8-1 of the ARMv7 reference manual.
989 // There is no dex instruction or HIR that would need the missing conditions
990 // "equal or unordered" or "not equal".
991 switch (cond) {
992 case kCondEQ: return eq;
993 case kCondNE: return ne /* unordered */;
994 case kCondLT: return gt_bias ? cc : lt /* unordered */;
995 case kCondLE: return gt_bias ? ls : le /* unordered */;
996 case kCondGT: return gt_bias ? hi /* unordered */ : gt;
997 case kCondGE: return gt_bias ? cs /* unordered */ : ge;
998 default:
999 LOG(FATAL) << "UNREACHABLE";
1000 UNREACHABLE();
1001 }
1002 }
1003
ShiftFromOpKind(HDataProcWithShifterOp::OpKind op_kind)1004 inline ShiftType ShiftFromOpKind(HDataProcWithShifterOp::OpKind op_kind) {
1005 switch (op_kind) {
1006 case HDataProcWithShifterOp::kASR: return ShiftType::ASR;
1007 case HDataProcWithShifterOp::kLSL: return ShiftType::LSL;
1008 case HDataProcWithShifterOp::kLSR: return ShiftType::LSR;
1009 default:
1010 LOG(FATAL) << "Unexpected op kind " << op_kind;
1011 UNREACHABLE();
1012 }
1013 }
1014
DumpCoreRegister(std::ostream & stream,int reg) const1015 void CodeGeneratorARMVIXL::DumpCoreRegister(std::ostream& stream, int reg) const {
1016 stream << vixl32::Register(reg);
1017 }
1018
DumpFloatingPointRegister(std::ostream & stream,int reg) const1019 void CodeGeneratorARMVIXL::DumpFloatingPointRegister(std::ostream& stream, int reg) const {
1020 stream << vixl32::SRegister(reg);
1021 }
1022
GetInstructionSetFeatures() const1023 const ArmInstructionSetFeatures& CodeGeneratorARMVIXL::GetInstructionSetFeatures() const {
1024 return *GetCompilerOptions().GetInstructionSetFeatures()->AsArmInstructionSetFeatures();
1025 }
1026
ComputeSRegisterListMask(const SRegisterList & regs)1027 static uint32_t ComputeSRegisterListMask(const SRegisterList& regs) {
1028 uint32_t mask = 0;
1029 for (uint32_t i = regs.GetFirstSRegister().GetCode();
1030 i <= regs.GetLastSRegister().GetCode();
1031 ++i) {
1032 mask |= (1 << i);
1033 }
1034 return mask;
1035 }
1036
1037 // Saves the register in the stack. Returns the size taken on stack.
SaveCoreRegister(size_t stack_index ATTRIBUTE_UNUSED,uint32_t reg_id ATTRIBUTE_UNUSED)1038 size_t CodeGeneratorARMVIXL::SaveCoreRegister(size_t stack_index ATTRIBUTE_UNUSED,
1039 uint32_t reg_id ATTRIBUTE_UNUSED) {
1040 TODO_VIXL32(FATAL);
1041 UNREACHABLE();
1042 }
1043
1044 // Restores the register from the stack. Returns the size taken on stack.
RestoreCoreRegister(size_t stack_index ATTRIBUTE_UNUSED,uint32_t reg_id ATTRIBUTE_UNUSED)1045 size_t CodeGeneratorARMVIXL::RestoreCoreRegister(size_t stack_index ATTRIBUTE_UNUSED,
1046 uint32_t reg_id ATTRIBUTE_UNUSED) {
1047 TODO_VIXL32(FATAL);
1048 UNREACHABLE();
1049 }
1050
SaveFloatingPointRegister(size_t stack_index ATTRIBUTE_UNUSED,uint32_t reg_id ATTRIBUTE_UNUSED)1051 size_t CodeGeneratorARMVIXL::SaveFloatingPointRegister(size_t stack_index ATTRIBUTE_UNUSED,
1052 uint32_t reg_id ATTRIBUTE_UNUSED) {
1053 TODO_VIXL32(FATAL);
1054 UNREACHABLE();
1055 }
1056
RestoreFloatingPointRegister(size_t stack_index ATTRIBUTE_UNUSED,uint32_t reg_id ATTRIBUTE_UNUSED)1057 size_t CodeGeneratorARMVIXL::RestoreFloatingPointRegister(size_t stack_index ATTRIBUTE_UNUSED,
1058 uint32_t reg_id ATTRIBUTE_UNUSED) {
1059 TODO_VIXL32(FATAL);
1060 UNREACHABLE();
1061 }
1062
GenerateDataProcInstruction(HInstruction::InstructionKind kind,vixl32::Register out,vixl32::Register first,const Operand & second,CodeGeneratorARMVIXL * codegen)1063 static void GenerateDataProcInstruction(HInstruction::InstructionKind kind,
1064 vixl32::Register out,
1065 vixl32::Register first,
1066 const Operand& second,
1067 CodeGeneratorARMVIXL* codegen) {
1068 if (second.IsImmediate() && second.GetImmediate() == 0) {
1069 const Operand in = kind == HInstruction::kAnd
1070 ? Operand(0)
1071 : Operand(first);
1072
1073 __ Mov(out, in);
1074 } else {
1075 switch (kind) {
1076 case HInstruction::kAdd:
1077 __ Add(out, first, second);
1078 break;
1079 case HInstruction::kAnd:
1080 __ And(out, first, second);
1081 break;
1082 case HInstruction::kOr:
1083 __ Orr(out, first, second);
1084 break;
1085 case HInstruction::kSub:
1086 __ Sub(out, first, second);
1087 break;
1088 case HInstruction::kXor:
1089 __ Eor(out, first, second);
1090 break;
1091 default:
1092 LOG(FATAL) << "Unexpected instruction kind: " << kind;
1093 UNREACHABLE();
1094 }
1095 }
1096 }
1097
GenerateDataProc(HInstruction::InstructionKind kind,const Location & out,const Location & first,const Operand & second_lo,const Operand & second_hi,CodeGeneratorARMVIXL * codegen)1098 static void GenerateDataProc(HInstruction::InstructionKind kind,
1099 const Location& out,
1100 const Location& first,
1101 const Operand& second_lo,
1102 const Operand& second_hi,
1103 CodeGeneratorARMVIXL* codegen) {
1104 const vixl32::Register first_hi = HighRegisterFrom(first);
1105 const vixl32::Register first_lo = LowRegisterFrom(first);
1106 const vixl32::Register out_hi = HighRegisterFrom(out);
1107 const vixl32::Register out_lo = LowRegisterFrom(out);
1108
1109 if (kind == HInstruction::kAdd) {
1110 __ Adds(out_lo, first_lo, second_lo);
1111 __ Adc(out_hi, first_hi, second_hi);
1112 } else if (kind == HInstruction::kSub) {
1113 __ Subs(out_lo, first_lo, second_lo);
1114 __ Sbc(out_hi, first_hi, second_hi);
1115 } else {
1116 GenerateDataProcInstruction(kind, out_lo, first_lo, second_lo, codegen);
1117 GenerateDataProcInstruction(kind, out_hi, first_hi, second_hi, codegen);
1118 }
1119 }
1120
GetShifterOperand(vixl32::Register rm,ShiftType shift,uint32_t shift_imm)1121 static Operand GetShifterOperand(vixl32::Register rm, ShiftType shift, uint32_t shift_imm) {
1122 return shift_imm == 0 ? Operand(rm) : Operand(rm, shift, shift_imm);
1123 }
1124
GenerateLongDataProc(HDataProcWithShifterOp * instruction,CodeGeneratorARMVIXL * codegen)1125 static void GenerateLongDataProc(HDataProcWithShifterOp* instruction,
1126 CodeGeneratorARMVIXL* codegen) {
1127 DCHECK_EQ(instruction->GetType(), DataType::Type::kInt64);
1128 DCHECK(HDataProcWithShifterOp::IsShiftOp(instruction->GetOpKind()));
1129
1130 const LocationSummary* const locations = instruction->GetLocations();
1131 const uint32_t shift_value = instruction->GetShiftAmount();
1132 const HInstruction::InstructionKind kind = instruction->GetInstrKind();
1133 const Location first = locations->InAt(0);
1134 const Location second = locations->InAt(1);
1135 const Location out = locations->Out();
1136 const vixl32::Register first_hi = HighRegisterFrom(first);
1137 const vixl32::Register first_lo = LowRegisterFrom(first);
1138 const vixl32::Register out_hi = HighRegisterFrom(out);
1139 const vixl32::Register out_lo = LowRegisterFrom(out);
1140 const vixl32::Register second_hi = HighRegisterFrom(second);
1141 const vixl32::Register second_lo = LowRegisterFrom(second);
1142 const ShiftType shift = ShiftFromOpKind(instruction->GetOpKind());
1143
1144 if (shift_value >= 32) {
1145 if (shift == ShiftType::LSL) {
1146 GenerateDataProcInstruction(kind,
1147 out_hi,
1148 first_hi,
1149 Operand(second_lo, ShiftType::LSL, shift_value - 32),
1150 codegen);
1151 GenerateDataProcInstruction(kind, out_lo, first_lo, 0, codegen);
1152 } else if (shift == ShiftType::ASR) {
1153 GenerateDataProc(kind,
1154 out,
1155 first,
1156 GetShifterOperand(second_hi, ShiftType::ASR, shift_value - 32),
1157 Operand(second_hi, ShiftType::ASR, 31),
1158 codegen);
1159 } else {
1160 DCHECK_EQ(shift, ShiftType::LSR);
1161 GenerateDataProc(kind,
1162 out,
1163 first,
1164 GetShifterOperand(second_hi, ShiftType::LSR, shift_value - 32),
1165 0,
1166 codegen);
1167 }
1168 } else {
1169 DCHECK_GT(shift_value, 1U);
1170 DCHECK_LT(shift_value, 32U);
1171
1172 UseScratchRegisterScope temps(codegen->GetVIXLAssembler());
1173
1174 if (shift == ShiftType::LSL) {
1175 // We are not doing this for HInstruction::kAdd because the output will require
1176 // Location::kOutputOverlap; not applicable to other cases.
1177 if (kind == HInstruction::kOr || kind == HInstruction::kXor) {
1178 GenerateDataProcInstruction(kind,
1179 out_hi,
1180 first_hi,
1181 Operand(second_hi, ShiftType::LSL, shift_value),
1182 codegen);
1183 GenerateDataProcInstruction(kind,
1184 out_hi,
1185 out_hi,
1186 Operand(second_lo, ShiftType::LSR, 32 - shift_value),
1187 codegen);
1188 GenerateDataProcInstruction(kind,
1189 out_lo,
1190 first_lo,
1191 Operand(second_lo, ShiftType::LSL, shift_value),
1192 codegen);
1193 } else {
1194 const vixl32::Register temp = temps.Acquire();
1195
1196 __ Lsl(temp, second_hi, shift_value);
1197 __ Orr(temp, temp, Operand(second_lo, ShiftType::LSR, 32 - shift_value));
1198 GenerateDataProc(kind,
1199 out,
1200 first,
1201 Operand(second_lo, ShiftType::LSL, shift_value),
1202 temp,
1203 codegen);
1204 }
1205 } else {
1206 DCHECK(shift == ShiftType::ASR || shift == ShiftType::LSR);
1207
1208 // We are not doing this for HInstruction::kAdd because the output will require
1209 // Location::kOutputOverlap; not applicable to other cases.
1210 if (kind == HInstruction::kOr || kind == HInstruction::kXor) {
1211 GenerateDataProcInstruction(kind,
1212 out_lo,
1213 first_lo,
1214 Operand(second_lo, ShiftType::LSR, shift_value),
1215 codegen);
1216 GenerateDataProcInstruction(kind,
1217 out_lo,
1218 out_lo,
1219 Operand(second_hi, ShiftType::LSL, 32 - shift_value),
1220 codegen);
1221 GenerateDataProcInstruction(kind,
1222 out_hi,
1223 first_hi,
1224 Operand(second_hi, shift, shift_value),
1225 codegen);
1226 } else {
1227 const vixl32::Register temp = temps.Acquire();
1228
1229 __ Lsr(temp, second_lo, shift_value);
1230 __ Orr(temp, temp, Operand(second_hi, ShiftType::LSL, 32 - shift_value));
1231 GenerateDataProc(kind,
1232 out,
1233 first,
1234 temp,
1235 Operand(second_hi, shift, shift_value),
1236 codegen);
1237 }
1238 }
1239 }
1240 }
1241
GenerateVcmp(HInstruction * instruction,CodeGeneratorARMVIXL * codegen)1242 static void GenerateVcmp(HInstruction* instruction, CodeGeneratorARMVIXL* codegen) {
1243 const Location rhs_loc = instruction->GetLocations()->InAt(1);
1244 if (rhs_loc.IsConstant()) {
1245 // 0.0 is the only immediate that can be encoded directly in
1246 // a VCMP instruction.
1247 //
1248 // Both the JLS (section 15.20.1) and the JVMS (section 6.5)
1249 // specify that in a floating-point comparison, positive zero
1250 // and negative zero are considered equal, so we can use the
1251 // literal 0.0 for both cases here.
1252 //
1253 // Note however that some methods (Float.equal, Float.compare,
1254 // Float.compareTo, Double.equal, Double.compare,
1255 // Double.compareTo, Math.max, Math.min, StrictMath.max,
1256 // StrictMath.min) consider 0.0 to be (strictly) greater than
1257 // -0.0. So if we ever translate calls to these methods into a
1258 // HCompare instruction, we must handle the -0.0 case with
1259 // care here.
1260 DCHECK(rhs_loc.GetConstant()->IsArithmeticZero());
1261
1262 const DataType::Type type = instruction->InputAt(0)->GetType();
1263
1264 if (type == DataType::Type::kFloat32) {
1265 __ Vcmp(F32, InputSRegisterAt(instruction, 0), 0.0);
1266 } else {
1267 DCHECK_EQ(type, DataType::Type::kFloat64);
1268 __ Vcmp(F64, InputDRegisterAt(instruction, 0), 0.0);
1269 }
1270 } else {
1271 __ Vcmp(InputVRegisterAt(instruction, 0), InputVRegisterAt(instruction, 1));
1272 }
1273 }
1274
AdjustConstantForCondition(int64_t value,IfCondition * condition,IfCondition * opposite)1275 static int64_t AdjustConstantForCondition(int64_t value,
1276 IfCondition* condition,
1277 IfCondition* opposite) {
1278 if (value == 1) {
1279 if (*condition == kCondB) {
1280 value = 0;
1281 *condition = kCondEQ;
1282 *opposite = kCondNE;
1283 } else if (*condition == kCondAE) {
1284 value = 0;
1285 *condition = kCondNE;
1286 *opposite = kCondEQ;
1287 }
1288 } else if (value == -1) {
1289 if (*condition == kCondGT) {
1290 value = 0;
1291 *condition = kCondGE;
1292 *opposite = kCondLT;
1293 } else if (*condition == kCondLE) {
1294 value = 0;
1295 *condition = kCondLT;
1296 *opposite = kCondGE;
1297 }
1298 }
1299
1300 return value;
1301 }
1302
GenerateLongTestConstant(HCondition * condition,bool invert,CodeGeneratorARMVIXL * codegen)1303 static std::pair<vixl32::Condition, vixl32::Condition> GenerateLongTestConstant(
1304 HCondition* condition,
1305 bool invert,
1306 CodeGeneratorARMVIXL* codegen) {
1307 DCHECK_EQ(condition->GetLeft()->GetType(), DataType::Type::kInt64);
1308
1309 const LocationSummary* const locations = condition->GetLocations();
1310 IfCondition cond = condition->GetCondition();
1311 IfCondition opposite = condition->GetOppositeCondition();
1312
1313 if (invert) {
1314 std::swap(cond, opposite);
1315 }
1316
1317 std::pair<vixl32::Condition, vixl32::Condition> ret(eq, ne);
1318 const Location left = locations->InAt(0);
1319 const Location right = locations->InAt(1);
1320
1321 DCHECK(right.IsConstant());
1322
1323 const vixl32::Register left_high = HighRegisterFrom(left);
1324 const vixl32::Register left_low = LowRegisterFrom(left);
1325 int64_t value = AdjustConstantForCondition(Int64ConstantFrom(right), &cond, &opposite);
1326 UseScratchRegisterScope temps(codegen->GetVIXLAssembler());
1327
1328 // Comparisons against 0 are common enough to deserve special attention.
1329 if (value == 0) {
1330 switch (cond) {
1331 case kCondNE:
1332 // x > 0 iff x != 0 when the comparison is unsigned.
1333 case kCondA:
1334 ret = std::make_pair(ne, eq);
1335 FALLTHROUGH_INTENDED;
1336 case kCondEQ:
1337 // x <= 0 iff x == 0 when the comparison is unsigned.
1338 case kCondBE:
1339 __ Orrs(temps.Acquire(), left_low, left_high);
1340 return ret;
1341 case kCondLT:
1342 case kCondGE:
1343 __ Cmp(left_high, 0);
1344 return std::make_pair(ARMCondition(cond), ARMCondition(opposite));
1345 // Trivially true or false.
1346 case kCondB:
1347 ret = std::make_pair(ne, eq);
1348 FALLTHROUGH_INTENDED;
1349 case kCondAE:
1350 __ Cmp(left_low, left_low);
1351 return ret;
1352 default:
1353 break;
1354 }
1355 }
1356
1357 switch (cond) {
1358 case kCondEQ:
1359 case kCondNE:
1360 case kCondB:
1361 case kCondBE:
1362 case kCondA:
1363 case kCondAE: {
1364 const uint32_t value_low = Low32Bits(value);
1365 Operand operand_low(value_low);
1366
1367 __ Cmp(left_high, High32Bits(value));
1368
1369 // Since IT blocks longer than a 16-bit instruction are deprecated by ARMv8,
1370 // we must ensure that the operands corresponding to the least significant
1371 // halves of the inputs fit into a 16-bit CMP encoding.
1372 if (!left_low.IsLow() || !IsUint<8>(value_low)) {
1373 operand_low = Operand(temps.Acquire());
1374 __ Mov(LeaveFlags, operand_low.GetBaseRegister(), value_low);
1375 }
1376
1377 // We use the scope because of the IT block that follows.
1378 ExactAssemblyScope guard(codegen->GetVIXLAssembler(),
1379 2 * vixl32::k16BitT32InstructionSizeInBytes,
1380 CodeBufferCheckScope::kExactSize);
1381
1382 __ it(eq);
1383 __ cmp(eq, left_low, operand_low);
1384 ret = std::make_pair(ARMUnsignedCondition(cond), ARMUnsignedCondition(opposite));
1385 break;
1386 }
1387 case kCondLE:
1388 case kCondGT:
1389 // Trivially true or false.
1390 if (value == std::numeric_limits<int64_t>::max()) {
1391 __ Cmp(left_low, left_low);
1392 ret = cond == kCondLE ? std::make_pair(eq, ne) : std::make_pair(ne, eq);
1393 break;
1394 }
1395
1396 if (cond == kCondLE) {
1397 DCHECK_EQ(opposite, kCondGT);
1398 cond = kCondLT;
1399 opposite = kCondGE;
1400 } else {
1401 DCHECK_EQ(cond, kCondGT);
1402 DCHECK_EQ(opposite, kCondLE);
1403 cond = kCondGE;
1404 opposite = kCondLT;
1405 }
1406
1407 value++;
1408 FALLTHROUGH_INTENDED;
1409 case kCondGE:
1410 case kCondLT: {
1411 __ Cmp(left_low, Low32Bits(value));
1412 __ Sbcs(temps.Acquire(), left_high, High32Bits(value));
1413 ret = std::make_pair(ARMCondition(cond), ARMCondition(opposite));
1414 break;
1415 }
1416 default:
1417 LOG(FATAL) << "Unreachable";
1418 UNREACHABLE();
1419 }
1420
1421 return ret;
1422 }
1423
GenerateLongTest(HCondition * condition,bool invert,CodeGeneratorARMVIXL * codegen)1424 static std::pair<vixl32::Condition, vixl32::Condition> GenerateLongTest(
1425 HCondition* condition,
1426 bool invert,
1427 CodeGeneratorARMVIXL* codegen) {
1428 DCHECK_EQ(condition->GetLeft()->GetType(), DataType::Type::kInt64);
1429
1430 const LocationSummary* const locations = condition->GetLocations();
1431 IfCondition cond = condition->GetCondition();
1432 IfCondition opposite = condition->GetOppositeCondition();
1433
1434 if (invert) {
1435 std::swap(cond, opposite);
1436 }
1437
1438 std::pair<vixl32::Condition, vixl32::Condition> ret(eq, ne);
1439 Location left = locations->InAt(0);
1440 Location right = locations->InAt(1);
1441
1442 DCHECK(right.IsRegisterPair());
1443
1444 switch (cond) {
1445 case kCondEQ:
1446 case kCondNE:
1447 case kCondB:
1448 case kCondBE:
1449 case kCondA:
1450 case kCondAE: {
1451 __ Cmp(HighRegisterFrom(left), HighRegisterFrom(right));
1452
1453 // We use the scope because of the IT block that follows.
1454 ExactAssemblyScope guard(codegen->GetVIXLAssembler(),
1455 2 * vixl32::k16BitT32InstructionSizeInBytes,
1456 CodeBufferCheckScope::kExactSize);
1457
1458 __ it(eq);
1459 __ cmp(eq, LowRegisterFrom(left), LowRegisterFrom(right));
1460 ret = std::make_pair(ARMUnsignedCondition(cond), ARMUnsignedCondition(opposite));
1461 break;
1462 }
1463 case kCondLE:
1464 case kCondGT:
1465 if (cond == kCondLE) {
1466 DCHECK_EQ(opposite, kCondGT);
1467 cond = kCondGE;
1468 opposite = kCondLT;
1469 } else {
1470 DCHECK_EQ(cond, kCondGT);
1471 DCHECK_EQ(opposite, kCondLE);
1472 cond = kCondLT;
1473 opposite = kCondGE;
1474 }
1475
1476 std::swap(left, right);
1477 FALLTHROUGH_INTENDED;
1478 case kCondGE:
1479 case kCondLT: {
1480 UseScratchRegisterScope temps(codegen->GetVIXLAssembler());
1481
1482 __ Cmp(LowRegisterFrom(left), LowRegisterFrom(right));
1483 __ Sbcs(temps.Acquire(), HighRegisterFrom(left), HighRegisterFrom(right));
1484 ret = std::make_pair(ARMCondition(cond), ARMCondition(opposite));
1485 break;
1486 }
1487 default:
1488 LOG(FATAL) << "Unreachable";
1489 UNREACHABLE();
1490 }
1491
1492 return ret;
1493 }
1494
GenerateTest(HCondition * condition,bool invert,CodeGeneratorARMVIXL * codegen)1495 static std::pair<vixl32::Condition, vixl32::Condition> GenerateTest(HCondition* condition,
1496 bool invert,
1497 CodeGeneratorARMVIXL* codegen) {
1498 const DataType::Type type = condition->GetLeft()->GetType();
1499 IfCondition cond = condition->GetCondition();
1500 IfCondition opposite = condition->GetOppositeCondition();
1501 std::pair<vixl32::Condition, vixl32::Condition> ret(eq, ne);
1502
1503 if (invert) {
1504 std::swap(cond, opposite);
1505 }
1506
1507 if (type == DataType::Type::kInt64) {
1508 ret = condition->GetLocations()->InAt(1).IsConstant()
1509 ? GenerateLongTestConstant(condition, invert, codegen)
1510 : GenerateLongTest(condition, invert, codegen);
1511 } else if (DataType::IsFloatingPointType(type)) {
1512 GenerateVcmp(condition, codegen);
1513 __ Vmrs(RegisterOrAPSR_nzcv(kPcCode), FPSCR);
1514 ret = std::make_pair(ARMFPCondition(cond, condition->IsGtBias()),
1515 ARMFPCondition(opposite, condition->IsGtBias()));
1516 } else {
1517 DCHECK(DataType::IsIntegralType(type) || type == DataType::Type::kReference) << type;
1518 __ Cmp(InputRegisterAt(condition, 0), InputOperandAt(condition, 1));
1519 ret = std::make_pair(ARMCondition(cond), ARMCondition(opposite));
1520 }
1521
1522 return ret;
1523 }
1524
GenerateConditionGeneric(HCondition * cond,CodeGeneratorARMVIXL * codegen)1525 static void GenerateConditionGeneric(HCondition* cond, CodeGeneratorARMVIXL* codegen) {
1526 const vixl32::Register out = OutputRegister(cond);
1527 const auto condition = GenerateTest(cond, false, codegen);
1528
1529 __ Mov(LeaveFlags, out, 0);
1530
1531 if (out.IsLow()) {
1532 // We use the scope because of the IT block that follows.
1533 ExactAssemblyScope guard(codegen->GetVIXLAssembler(),
1534 2 * vixl32::k16BitT32InstructionSizeInBytes,
1535 CodeBufferCheckScope::kExactSize);
1536
1537 __ it(condition.first);
1538 __ mov(condition.first, out, 1);
1539 } else {
1540 vixl32::Label done_label;
1541 vixl32::Label* const final_label = codegen->GetFinalLabel(cond, &done_label);
1542
1543 __ B(condition.second, final_label, /* is_far_target= */ false);
1544 __ Mov(out, 1);
1545
1546 if (done_label.IsReferenced()) {
1547 __ Bind(&done_label);
1548 }
1549 }
1550 }
1551
GenerateEqualLong(HCondition * cond,CodeGeneratorARMVIXL * codegen)1552 static void GenerateEqualLong(HCondition* cond, CodeGeneratorARMVIXL* codegen) {
1553 DCHECK_EQ(cond->GetLeft()->GetType(), DataType::Type::kInt64);
1554
1555 const LocationSummary* const locations = cond->GetLocations();
1556 IfCondition condition = cond->GetCondition();
1557 const vixl32::Register out = OutputRegister(cond);
1558 const Location left = locations->InAt(0);
1559 const Location right = locations->InAt(1);
1560 vixl32::Register left_high = HighRegisterFrom(left);
1561 vixl32::Register left_low = LowRegisterFrom(left);
1562 vixl32::Register temp;
1563 UseScratchRegisterScope temps(codegen->GetVIXLAssembler());
1564
1565 if (right.IsConstant()) {
1566 IfCondition opposite = cond->GetOppositeCondition();
1567 const int64_t value = AdjustConstantForCondition(Int64ConstantFrom(right),
1568 &condition,
1569 &opposite);
1570 Operand right_high = High32Bits(value);
1571 Operand right_low = Low32Bits(value);
1572
1573 // The output uses Location::kNoOutputOverlap.
1574 if (out.Is(left_high)) {
1575 std::swap(left_low, left_high);
1576 std::swap(right_low, right_high);
1577 }
1578
1579 __ Sub(out, left_low, right_low);
1580 temp = temps.Acquire();
1581 __ Sub(temp, left_high, right_high);
1582 } else {
1583 DCHECK(right.IsRegisterPair());
1584 temp = temps.Acquire();
1585 __ Sub(temp, left_high, HighRegisterFrom(right));
1586 __ Sub(out, left_low, LowRegisterFrom(right));
1587 }
1588
1589 // Need to check after calling AdjustConstantForCondition().
1590 DCHECK(condition == kCondEQ || condition == kCondNE) << condition;
1591
1592 if (condition == kCondNE && out.IsLow()) {
1593 __ Orrs(out, out, temp);
1594
1595 // We use the scope because of the IT block that follows.
1596 ExactAssemblyScope guard(codegen->GetVIXLAssembler(),
1597 2 * vixl32::k16BitT32InstructionSizeInBytes,
1598 CodeBufferCheckScope::kExactSize);
1599
1600 __ it(ne);
1601 __ mov(ne, out, 1);
1602 } else {
1603 __ Orr(out, out, temp);
1604 codegen->GenerateConditionWithZero(condition, out, out, temp);
1605 }
1606 }
1607
GenerateConditionLong(HCondition * cond,CodeGeneratorARMVIXL * codegen)1608 static void GenerateConditionLong(HCondition* cond, CodeGeneratorARMVIXL* codegen) {
1609 DCHECK_EQ(cond->GetLeft()->GetType(), DataType::Type::kInt64);
1610
1611 const LocationSummary* const locations = cond->GetLocations();
1612 IfCondition condition = cond->GetCondition();
1613 const vixl32::Register out = OutputRegister(cond);
1614 const Location left = locations->InAt(0);
1615 const Location right = locations->InAt(1);
1616
1617 if (right.IsConstant()) {
1618 IfCondition opposite = cond->GetOppositeCondition();
1619
1620 // Comparisons against 0 are common enough to deserve special attention.
1621 if (AdjustConstantForCondition(Int64ConstantFrom(right), &condition, &opposite) == 0) {
1622 switch (condition) {
1623 case kCondNE:
1624 case kCondA:
1625 if (out.IsLow()) {
1626 // We only care if both input registers are 0 or not.
1627 __ Orrs(out, LowRegisterFrom(left), HighRegisterFrom(left));
1628
1629 // We use the scope because of the IT block that follows.
1630 ExactAssemblyScope guard(codegen->GetVIXLAssembler(),
1631 2 * vixl32::k16BitT32InstructionSizeInBytes,
1632 CodeBufferCheckScope::kExactSize);
1633
1634 __ it(ne);
1635 __ mov(ne, out, 1);
1636 return;
1637 }
1638
1639 FALLTHROUGH_INTENDED;
1640 case kCondEQ:
1641 case kCondBE:
1642 // We only care if both input registers are 0 or not.
1643 __ Orr(out, LowRegisterFrom(left), HighRegisterFrom(left));
1644 codegen->GenerateConditionWithZero(condition, out, out);
1645 return;
1646 case kCondLT:
1647 case kCondGE:
1648 // We only care about the sign bit.
1649 FALLTHROUGH_INTENDED;
1650 case kCondAE:
1651 case kCondB:
1652 codegen->GenerateConditionWithZero(condition, out, HighRegisterFrom(left));
1653 return;
1654 case kCondLE:
1655 case kCondGT:
1656 default:
1657 break;
1658 }
1659 }
1660 }
1661
1662 // If `out` is a low register, then the GenerateConditionGeneric()
1663 // function generates a shorter code sequence that is still branchless.
1664 if ((condition == kCondEQ || condition == kCondNE) && !out.IsLow()) {
1665 GenerateEqualLong(cond, codegen);
1666 return;
1667 }
1668
1669 GenerateConditionGeneric(cond, codegen);
1670 }
1671
GenerateConditionIntegralOrNonPrimitive(HCondition * cond,CodeGeneratorARMVIXL * codegen)1672 static void GenerateConditionIntegralOrNonPrimitive(HCondition* cond,
1673 CodeGeneratorARMVIXL* codegen) {
1674 const DataType::Type type = cond->GetLeft()->GetType();
1675
1676 DCHECK(DataType::IsIntegralType(type) || type == DataType::Type::kReference) << type;
1677
1678 if (type == DataType::Type::kInt64) {
1679 GenerateConditionLong(cond, codegen);
1680 return;
1681 }
1682
1683 IfCondition condition = cond->GetCondition();
1684 vixl32::Register in = InputRegisterAt(cond, 0);
1685 const vixl32::Register out = OutputRegister(cond);
1686 const Location right = cond->GetLocations()->InAt(1);
1687 int64_t value;
1688
1689 if (right.IsConstant()) {
1690 IfCondition opposite = cond->GetOppositeCondition();
1691
1692 value = AdjustConstantForCondition(Int64ConstantFrom(right), &condition, &opposite);
1693
1694 // Comparisons against 0 are common enough to deserve special attention.
1695 if (value == 0) {
1696 switch (condition) {
1697 case kCondNE:
1698 case kCondA:
1699 if (out.IsLow() && out.Is(in)) {
1700 __ Cmp(out, 0);
1701
1702 // We use the scope because of the IT block that follows.
1703 ExactAssemblyScope guard(codegen->GetVIXLAssembler(),
1704 2 * vixl32::k16BitT32InstructionSizeInBytes,
1705 CodeBufferCheckScope::kExactSize);
1706
1707 __ it(ne);
1708 __ mov(ne, out, 1);
1709 return;
1710 }
1711
1712 FALLTHROUGH_INTENDED;
1713 case kCondEQ:
1714 case kCondBE:
1715 case kCondLT:
1716 case kCondGE:
1717 case kCondAE:
1718 case kCondB:
1719 codegen->GenerateConditionWithZero(condition, out, in);
1720 return;
1721 case kCondLE:
1722 case kCondGT:
1723 default:
1724 break;
1725 }
1726 }
1727 }
1728
1729 if (condition == kCondEQ || condition == kCondNE) {
1730 Operand operand(0);
1731
1732 if (right.IsConstant()) {
1733 operand = Operand::From(value);
1734 } else if (out.Is(RegisterFrom(right))) {
1735 // Avoid 32-bit instructions if possible.
1736 operand = InputOperandAt(cond, 0);
1737 in = RegisterFrom(right);
1738 } else {
1739 operand = InputOperandAt(cond, 1);
1740 }
1741
1742 if (condition == kCondNE && out.IsLow()) {
1743 __ Subs(out, in, operand);
1744
1745 // We use the scope because of the IT block that follows.
1746 ExactAssemblyScope guard(codegen->GetVIXLAssembler(),
1747 2 * vixl32::k16BitT32InstructionSizeInBytes,
1748 CodeBufferCheckScope::kExactSize);
1749
1750 __ it(ne);
1751 __ mov(ne, out, 1);
1752 } else {
1753 __ Sub(out, in, operand);
1754 codegen->GenerateConditionWithZero(condition, out, out);
1755 }
1756
1757 return;
1758 }
1759
1760 GenerateConditionGeneric(cond, codegen);
1761 }
1762
CanEncodeConstantAs8BitImmediate(HConstant * constant)1763 static bool CanEncodeConstantAs8BitImmediate(HConstant* constant) {
1764 const DataType::Type type = constant->GetType();
1765 bool ret = false;
1766
1767 DCHECK(DataType::IsIntegralType(type) || type == DataType::Type::kReference) << type;
1768
1769 if (type == DataType::Type::kInt64) {
1770 const uint64_t value = Uint64ConstantFrom(constant);
1771
1772 ret = IsUint<8>(Low32Bits(value)) && IsUint<8>(High32Bits(value));
1773 } else {
1774 ret = IsUint<8>(Int32ConstantFrom(constant));
1775 }
1776
1777 return ret;
1778 }
1779
Arm8BitEncodableConstantOrRegister(HInstruction * constant)1780 static Location Arm8BitEncodableConstantOrRegister(HInstruction* constant) {
1781 DCHECK(!DataType::IsFloatingPointType(constant->GetType()));
1782
1783 if (constant->IsConstant() && CanEncodeConstantAs8BitImmediate(constant->AsConstant())) {
1784 return Location::ConstantLocation(constant->AsConstant());
1785 }
1786
1787 return Location::RequiresRegister();
1788 }
1789
CanGenerateConditionalMove(const Location & out,const Location & src)1790 static bool CanGenerateConditionalMove(const Location& out, const Location& src) {
1791 // Since IT blocks longer than a 16-bit instruction are deprecated by ARMv8,
1792 // we check that we are not dealing with floating-point output (there is no
1793 // 16-bit VMOV encoding).
1794 if (!out.IsRegister() && !out.IsRegisterPair()) {
1795 return false;
1796 }
1797
1798 // For constants, we also check that the output is in one or two low registers,
1799 // and that the constants fit in an 8-bit unsigned integer, so that a 16-bit
1800 // MOV encoding can be used.
1801 if (src.IsConstant()) {
1802 if (!CanEncodeConstantAs8BitImmediate(src.GetConstant())) {
1803 return false;
1804 }
1805
1806 if (out.IsRegister()) {
1807 if (!RegisterFrom(out).IsLow()) {
1808 return false;
1809 }
1810 } else {
1811 DCHECK(out.IsRegisterPair());
1812
1813 if (!HighRegisterFrom(out).IsLow()) {
1814 return false;
1815 }
1816 }
1817 }
1818
1819 return true;
1820 }
1821
1822 #undef __
1823
GetFinalLabel(HInstruction * instruction,vixl32::Label * final_label)1824 vixl32::Label* CodeGeneratorARMVIXL::GetFinalLabel(HInstruction* instruction,
1825 vixl32::Label* final_label) {
1826 DCHECK(!instruction->IsControlFlow() && !instruction->IsSuspendCheck());
1827 DCHECK(!instruction->IsInvoke() || !instruction->GetLocations()->CanCall());
1828
1829 const HBasicBlock* const block = instruction->GetBlock();
1830 const HLoopInformation* const info = block->GetLoopInformation();
1831 HInstruction* const next = instruction->GetNext();
1832
1833 // Avoid a branch to a branch.
1834 if (next->IsGoto() && (info == nullptr ||
1835 !info->IsBackEdge(*block) ||
1836 !info->HasSuspendCheck())) {
1837 final_label = GetLabelOf(next->AsGoto()->GetSuccessor());
1838 }
1839
1840 return final_label;
1841 }
1842
CodeGeneratorARMVIXL(HGraph * graph,const CompilerOptions & compiler_options,OptimizingCompilerStats * stats)1843 CodeGeneratorARMVIXL::CodeGeneratorARMVIXL(HGraph* graph,
1844 const CompilerOptions& compiler_options,
1845 OptimizingCompilerStats* stats)
1846 : CodeGenerator(graph,
1847 kNumberOfCoreRegisters,
1848 kNumberOfSRegisters,
1849 kNumberOfRegisterPairs,
1850 kCoreCalleeSaves.GetList(),
1851 ComputeSRegisterListMask(kFpuCalleeSaves),
1852 compiler_options,
1853 stats),
1854 block_labels_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1855 jump_tables_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1856 location_builder_(graph, this),
1857 instruction_visitor_(graph, this),
1858 move_resolver_(graph->GetAllocator(), this),
1859 assembler_(graph->GetAllocator()),
1860 boot_image_method_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1861 method_bss_entry_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1862 boot_image_type_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1863 type_bss_entry_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1864 boot_image_string_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1865 string_bss_entry_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1866 boot_image_other_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1867 call_entrypoint_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1868 baker_read_barrier_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1869 uint32_literals_(std::less<uint32_t>(),
1870 graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1871 jit_string_patches_(StringReferenceValueComparator(),
1872 graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1873 jit_class_patches_(TypeReferenceValueComparator(),
1874 graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
1875 jit_baker_read_barrier_slow_paths_(std::less<uint32_t>(),
1876 graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)) {
1877 // Always save the LR register to mimic Quick.
1878 AddAllocatedRegister(Location::RegisterLocation(LR));
1879 // Give D30 and D31 as scratch register to VIXL. The register allocator only works on
1880 // S0-S31, which alias to D0-D15.
1881 GetVIXLAssembler()->GetScratchVRegisterList()->Combine(d31);
1882 GetVIXLAssembler()->GetScratchVRegisterList()->Combine(d30);
1883 }
1884
EmitTable(CodeGeneratorARMVIXL * codegen)1885 void JumpTableARMVIXL::EmitTable(CodeGeneratorARMVIXL* codegen) {
1886 uint32_t num_entries = switch_instr_->GetNumEntries();
1887 DCHECK_GE(num_entries, kPackedSwitchCompareJumpThreshold);
1888
1889 // We are about to use the assembler to place literals directly. Make sure we have enough
1890 // underlying code buffer and we have generated a jump table of the right size, using
1891 // codegen->GetVIXLAssembler()->GetBuffer().Align();
1892 ExactAssemblyScope aas(codegen->GetVIXLAssembler(),
1893 num_entries * sizeof(int32_t),
1894 CodeBufferCheckScope::kMaximumSize);
1895 // TODO(VIXL): Check that using lower case bind is fine here.
1896 codegen->GetVIXLAssembler()->bind(&table_start_);
1897 for (uint32_t i = 0; i < num_entries; i++) {
1898 codegen->GetVIXLAssembler()->place(bb_addresses_[i].get());
1899 }
1900 }
1901
FixTable(CodeGeneratorARMVIXL * codegen)1902 void JumpTableARMVIXL::FixTable(CodeGeneratorARMVIXL* codegen) {
1903 uint32_t num_entries = switch_instr_->GetNumEntries();
1904 DCHECK_GE(num_entries, kPackedSwitchCompareJumpThreshold);
1905
1906 const ArenaVector<HBasicBlock*>& successors = switch_instr_->GetBlock()->GetSuccessors();
1907 for (uint32_t i = 0; i < num_entries; i++) {
1908 vixl32::Label* target_label = codegen->GetLabelOf(successors[i]);
1909 DCHECK(target_label->IsBound());
1910 int32_t jump_offset = target_label->GetLocation() - table_start_.GetLocation();
1911 // When doing BX to address we need to have lower bit set to 1 in T32.
1912 if (codegen->GetVIXLAssembler()->IsUsingT32()) {
1913 jump_offset++;
1914 }
1915 DCHECK_GT(jump_offset, std::numeric_limits<int32_t>::min());
1916 DCHECK_LE(jump_offset, std::numeric_limits<int32_t>::max());
1917
1918 bb_addresses_[i].get()->UpdateValue(jump_offset, codegen->GetVIXLAssembler()->GetBuffer());
1919 }
1920 }
1921
FixJumpTables()1922 void CodeGeneratorARMVIXL::FixJumpTables() {
1923 for (auto&& jump_table : jump_tables_) {
1924 jump_table->FixTable(this);
1925 }
1926 }
1927
1928 #define __ reinterpret_cast<ArmVIXLAssembler*>(GetAssembler())->GetVIXLAssembler()-> // NOLINT
1929
Finalize(CodeAllocator * allocator)1930 void CodeGeneratorARMVIXL::Finalize(CodeAllocator* allocator) {
1931 FixJumpTables();
1932
1933 // Emit JIT baker read barrier slow paths.
1934 DCHECK(Runtime::Current()->UseJitCompilation() || jit_baker_read_barrier_slow_paths_.empty());
1935 for (auto& entry : jit_baker_read_barrier_slow_paths_) {
1936 uint32_t encoded_data = entry.first;
1937 vixl::aarch32::Label* slow_path_entry = &entry.second.label;
1938 __ Bind(slow_path_entry);
1939 CompileBakerReadBarrierThunk(*GetAssembler(), encoded_data, /* debug_name= */ nullptr);
1940 }
1941
1942 GetAssembler()->FinalizeCode();
1943 CodeGenerator::Finalize(allocator);
1944
1945 // Verify Baker read barrier linker patches.
1946 if (kIsDebugBuild) {
1947 ArrayRef<const uint8_t> code = allocator->GetMemory();
1948 for (const BakerReadBarrierPatchInfo& info : baker_read_barrier_patches_) {
1949 DCHECK(info.label.IsBound());
1950 uint32_t literal_offset = info.label.GetLocation();
1951 DCHECK_ALIGNED(literal_offset, 2u);
1952
1953 auto GetInsn16 = [&code](uint32_t offset) {
1954 DCHECK_ALIGNED(offset, 2u);
1955 return (static_cast<uint32_t>(code[offset + 0]) << 0) +
1956 (static_cast<uint32_t>(code[offset + 1]) << 8);
1957 };
1958 auto GetInsn32 = [=](uint32_t offset) {
1959 return (GetInsn16(offset) << 16) + (GetInsn16(offset + 2u) << 0);
1960 };
1961
1962 uint32_t encoded_data = info.custom_data;
1963 BakerReadBarrierKind kind = BakerReadBarrierKindField::Decode(encoded_data);
1964 // Check that the next instruction matches the expected LDR.
1965 switch (kind) {
1966 case BakerReadBarrierKind::kField: {
1967 BakerReadBarrierWidth width = BakerReadBarrierWidthField::Decode(encoded_data);
1968 if (width == BakerReadBarrierWidth::kWide) {
1969 DCHECK_GE(code.size() - literal_offset, 8u);
1970 uint32_t next_insn = GetInsn32(literal_offset + 4u);
1971 // LDR (immediate), encoding T3, with correct base_reg.
1972 CheckValidReg((next_insn >> 12) & 0xfu); // Check destination register.
1973 const uint32_t base_reg = BakerReadBarrierFirstRegField::Decode(encoded_data);
1974 CHECK_EQ(next_insn & 0xffff0000u, 0xf8d00000u | (base_reg << 16));
1975 } else {
1976 DCHECK_GE(code.size() - literal_offset, 6u);
1977 uint32_t next_insn = GetInsn16(literal_offset + 4u);
1978 // LDR (immediate), encoding T1, with correct base_reg.
1979 CheckValidReg(next_insn & 0x7u); // Check destination register.
1980 const uint32_t base_reg = BakerReadBarrierFirstRegField::Decode(encoded_data);
1981 CHECK_EQ(next_insn & 0xf838u, 0x6800u | (base_reg << 3));
1982 }
1983 break;
1984 }
1985 case BakerReadBarrierKind::kArray: {
1986 DCHECK_GE(code.size() - literal_offset, 8u);
1987 uint32_t next_insn = GetInsn32(literal_offset + 4u);
1988 // LDR (register) with correct base_reg, S=1 and option=011 (LDR Wt, [Xn, Xm, LSL #2]).
1989 CheckValidReg((next_insn >> 12) & 0xfu); // Check destination register.
1990 const uint32_t base_reg = BakerReadBarrierFirstRegField::Decode(encoded_data);
1991 CHECK_EQ(next_insn & 0xffff0ff0u, 0xf8500020u | (base_reg << 16));
1992 CheckValidReg(next_insn & 0xf); // Check index register
1993 break;
1994 }
1995 case BakerReadBarrierKind::kGcRoot: {
1996 BakerReadBarrierWidth width = BakerReadBarrierWidthField::Decode(encoded_data);
1997 if (width == BakerReadBarrierWidth::kWide) {
1998 DCHECK_GE(literal_offset, 4u);
1999 uint32_t prev_insn = GetInsn32(literal_offset - 4u);
2000 // LDR (immediate), encoding T3, with correct root_reg.
2001 const uint32_t root_reg = BakerReadBarrierFirstRegField::Decode(encoded_data);
2002 CHECK_EQ(prev_insn & 0xfff0f000u, 0xf8d00000u | (root_reg << 12));
2003 } else {
2004 DCHECK_GE(literal_offset, 2u);
2005 uint32_t prev_insn = GetInsn16(literal_offset - 2u);
2006 // LDR (immediate), encoding T1, with correct root_reg.
2007 const uint32_t root_reg = BakerReadBarrierFirstRegField::Decode(encoded_data);
2008 CHECK_EQ(prev_insn & 0xf807u, 0x6800u | root_reg);
2009 }
2010 break;
2011 }
2012 case BakerReadBarrierKind::kUnsafeCas: {
2013 DCHECK_GE(literal_offset, 4u);
2014 uint32_t prev_insn = GetInsn32(literal_offset - 4u);
2015 // ADD (register), encoding T3, with correct root_reg.
2016 const uint32_t root_reg = BakerReadBarrierFirstRegField::Decode(encoded_data);
2017 CHECK_EQ(prev_insn & 0xfff0fff0u, 0xeb000000u | (root_reg << 8));
2018 break;
2019 }
2020 default:
2021 LOG(FATAL) << "Unexpected kind: " << static_cast<uint32_t>(kind);
2022 UNREACHABLE();
2023 }
2024 }
2025 }
2026 }
2027
SetupBlockedRegisters() const2028 void CodeGeneratorARMVIXL::SetupBlockedRegisters() const {
2029 // Stack register, LR and PC are always reserved.
2030 blocked_core_registers_[SP] = true;
2031 blocked_core_registers_[LR] = true;
2032 blocked_core_registers_[PC] = true;
2033
2034 if (kEmitCompilerReadBarrier && kUseBakerReadBarrier) {
2035 // Reserve marking register.
2036 blocked_core_registers_[MR] = true;
2037 }
2038
2039 // Reserve thread register.
2040 blocked_core_registers_[TR] = true;
2041
2042 // Reserve temp register.
2043 blocked_core_registers_[IP] = true;
2044
2045 if (GetGraph()->IsDebuggable()) {
2046 // Stubs do not save callee-save floating point registers. If the graph
2047 // is debuggable, we need to deal with these registers differently. For
2048 // now, just block them.
2049 for (uint32_t i = kFpuCalleeSaves.GetFirstSRegister().GetCode();
2050 i <= kFpuCalleeSaves.GetLastSRegister().GetCode();
2051 ++i) {
2052 blocked_fpu_registers_[i] = true;
2053 }
2054 }
2055 }
2056
InstructionCodeGeneratorARMVIXL(HGraph * graph,CodeGeneratorARMVIXL * codegen)2057 InstructionCodeGeneratorARMVIXL::InstructionCodeGeneratorARMVIXL(HGraph* graph,
2058 CodeGeneratorARMVIXL* codegen)
2059 : InstructionCodeGenerator(graph, codegen),
2060 assembler_(codegen->GetAssembler()),
2061 codegen_(codegen) {}
2062
ComputeSpillMask()2063 void CodeGeneratorARMVIXL::ComputeSpillMask() {
2064 core_spill_mask_ = allocated_registers_.GetCoreRegisters() & core_callee_save_mask_;
2065 DCHECK_NE(core_spill_mask_ & (1u << kLrCode), 0u)
2066 << "At least the return address register must be saved";
2067 // 16-bit PUSH/POP (T1) can save/restore just the LR/PC.
2068 DCHECK(GetVIXLAssembler()->IsUsingT32());
2069 fpu_spill_mask_ = allocated_registers_.GetFloatingPointRegisters() & fpu_callee_save_mask_;
2070 // We use vpush and vpop for saving and restoring floating point registers, which take
2071 // a SRegister and the number of registers to save/restore after that SRegister. We
2072 // therefore update the `fpu_spill_mask_` to also contain those registers not allocated,
2073 // but in the range.
2074 if (fpu_spill_mask_ != 0) {
2075 uint32_t least_significant_bit = LeastSignificantBit(fpu_spill_mask_);
2076 uint32_t most_significant_bit = MostSignificantBit(fpu_spill_mask_);
2077 for (uint32_t i = least_significant_bit + 1 ; i < most_significant_bit; ++i) {
2078 fpu_spill_mask_ |= (1 << i);
2079 }
2080 }
2081 }
2082
MaybeIncrementHotness(bool is_frame_entry)2083 void CodeGeneratorARMVIXL::MaybeIncrementHotness(bool is_frame_entry) {
2084 if (GetCompilerOptions().CountHotnessInCompiledCode()) {
2085 UseScratchRegisterScope temps(GetVIXLAssembler());
2086 vixl32::Register temp = temps.Acquire();
2087 static_assert(ArtMethod::MaxCounter() == 0xFFFF, "asm is probably wrong");
2088 if (!is_frame_entry) {
2089 __ Push(vixl32::Register(kMethodRegister));
2090 GetAssembler()->LoadFromOffset(kLoadWord, kMethodRegister, sp, kArmWordSize);
2091 }
2092 // Load with zero extend to clear the high bits for integer overflow check.
2093 __ Ldrh(temp, MemOperand(kMethodRegister, ArtMethod::HotnessCountOffset().Int32Value()));
2094 __ Add(temp, temp, 1);
2095 // Subtract one if the counter would overflow.
2096 __ Sub(temp, temp, Operand(temp, ShiftType::LSR, 16));
2097 __ Strh(temp, MemOperand(kMethodRegister, ArtMethod::HotnessCountOffset().Int32Value()));
2098 if (!is_frame_entry) {
2099 __ Pop(vixl32::Register(kMethodRegister));
2100 }
2101 }
2102
2103 if (GetGraph()->IsCompilingBaseline() && !Runtime::Current()->IsAotCompiler()) {
2104 ScopedObjectAccess soa(Thread::Current());
2105 ProfilingInfo* info = GetGraph()->GetArtMethod()->GetProfilingInfo(kRuntimePointerSize);
2106 if (info != nullptr) {
2107 uint32_t address = reinterpret_cast32<uint32_t>(info);
2108 vixl::aarch32::Label done;
2109 UseScratchRegisterScope temps(GetVIXLAssembler());
2110 temps.Exclude(ip);
2111 if (!is_frame_entry) {
2112 __ Push(r4); // Will be used as temporary. For frame entry, r4 is always available.
2113 }
2114 __ Mov(r4, address);
2115 __ Ldrh(ip, MemOperand(r4, ProfilingInfo::BaselineHotnessCountOffset().Int32Value()));
2116 __ Add(ip, ip, 1);
2117 __ Strh(ip, MemOperand(r4, ProfilingInfo::BaselineHotnessCountOffset().Int32Value()));
2118 if (!is_frame_entry) {
2119 __ Pop(r4);
2120 }
2121 __ Lsls(ip, ip, 16);
2122 __ B(ne, &done);
2123 uint32_t entry_point_offset =
2124 GetThreadOffset<kArmPointerSize>(kQuickCompileOptimized).Int32Value();
2125 if (HasEmptyFrame()) {
2126 CHECK(is_frame_entry);
2127 // For leaf methods, we need to spill lr and r0. Also spill r1 and r2 for
2128 // alignment.
2129 uint32_t core_spill_mask =
2130 (1 << lr.GetCode()) | (1 << r0.GetCode()) | (1 << r1.GetCode()) | (1 << r2.GetCode());
2131 __ Push(RegisterList(core_spill_mask));
2132 __ Ldr(lr, MemOperand(tr, entry_point_offset));
2133 __ Blx(lr);
2134 __ Pop(RegisterList(core_spill_mask));
2135 } else {
2136 if (!RequiresCurrentMethod()) {
2137 CHECK(is_frame_entry);
2138 GetAssembler()->StoreToOffset(kStoreWord, kMethodRegister, sp, 0);
2139 }
2140 __ Ldr(lr, MemOperand(tr, entry_point_offset));
2141 __ Blx(lr);
2142 }
2143 __ Bind(&done);
2144 }
2145 }
2146 }
2147
GenerateFrameEntry()2148 void CodeGeneratorARMVIXL::GenerateFrameEntry() {
2149 bool skip_overflow_check =
2150 IsLeafMethod() && !FrameNeedsStackCheck(GetFrameSize(), InstructionSet::kArm);
2151 DCHECK(GetCompilerOptions().GetImplicitStackOverflowChecks());
2152 __ Bind(&frame_entry_label_);
2153
2154 if (HasEmptyFrame()) {
2155 // Ensure that the CFI opcode list is not empty.
2156 GetAssembler()->cfi().Nop();
2157 MaybeIncrementHotness(/* is_frame_entry= */ true);
2158 return;
2159 }
2160
2161 if (!skip_overflow_check) {
2162 // Using r4 instead of IP saves 2 bytes.
2163 UseScratchRegisterScope temps(GetVIXLAssembler());
2164 vixl32::Register temp;
2165 // TODO: Remove this check when R4 is made a callee-save register
2166 // in ART compiled code (b/72801708). Currently we need to make
2167 // sure r4 is not blocked, e.g. in special purpose
2168 // TestCodeGeneratorARMVIXL; also asserting that r4 is available
2169 // here.
2170 if (!blocked_core_registers_[R4]) {
2171 for (vixl32::Register reg : kParameterCoreRegistersVIXL) {
2172 DCHECK(!reg.Is(r4));
2173 }
2174 DCHECK(!kCoreCalleeSaves.Includes(r4));
2175 temp = r4;
2176 } else {
2177 temp = temps.Acquire();
2178 }
2179 __ Sub(temp, sp, Operand::From(GetStackOverflowReservedBytes(InstructionSet::kArm)));
2180 // The load must immediately precede RecordPcInfo.
2181 ExactAssemblyScope aas(GetVIXLAssembler(),
2182 vixl32::kMaxInstructionSizeInBytes,
2183 CodeBufferCheckScope::kMaximumSize);
2184 __ ldr(temp, MemOperand(temp));
2185 RecordPcInfo(nullptr, 0);
2186 }
2187
2188 uint32_t frame_size = GetFrameSize();
2189 uint32_t core_spills_offset = frame_size - GetCoreSpillSize();
2190 uint32_t fp_spills_offset = frame_size - FrameEntrySpillSize();
2191 if ((fpu_spill_mask_ == 0u || IsPowerOfTwo(fpu_spill_mask_)) &&
2192 core_spills_offset <= 3u * kArmWordSize) {
2193 // Do a single PUSH for core registers including the method and up to two
2194 // filler registers. Then store the single FP spill if any.
2195 // (The worst case is when the method is not required and we actually
2196 // store 3 extra registers but they are stored in the same properly
2197 // aligned 16-byte chunk where we're already writing anyway.)
2198 DCHECK_EQ(kMethodRegister.GetCode(), 0u);
2199 uint32_t extra_regs = MaxInt<uint32_t>(core_spills_offset / kArmWordSize);
2200 DCHECK_LT(MostSignificantBit(extra_regs), LeastSignificantBit(core_spill_mask_));
2201 __ Push(RegisterList(core_spill_mask_ | extra_regs));
2202 GetAssembler()->cfi().AdjustCFAOffset(frame_size);
2203 GetAssembler()->cfi().RelOffsetForMany(DWARFReg(kMethodRegister),
2204 core_spills_offset,
2205 core_spill_mask_,
2206 kArmWordSize);
2207 if (fpu_spill_mask_ != 0u) {
2208 DCHECK(IsPowerOfTwo(fpu_spill_mask_));
2209 vixl::aarch32::SRegister sreg(LeastSignificantBit(fpu_spill_mask_));
2210 GetAssembler()->StoreSToOffset(sreg, sp, fp_spills_offset);
2211 GetAssembler()->cfi().RelOffset(DWARFReg(sreg), /*offset=*/ fp_spills_offset);
2212 }
2213 } else {
2214 __ Push(RegisterList(core_spill_mask_));
2215 GetAssembler()->cfi().AdjustCFAOffset(kArmWordSize * POPCOUNT(core_spill_mask_));
2216 GetAssembler()->cfi().RelOffsetForMany(DWARFReg(kMethodRegister),
2217 /*offset=*/ 0,
2218 core_spill_mask_,
2219 kArmWordSize);
2220 if (fpu_spill_mask_ != 0) {
2221 uint32_t first = LeastSignificantBit(fpu_spill_mask_);
2222
2223 // Check that list is contiguous.
2224 DCHECK_EQ(fpu_spill_mask_ >> CTZ(fpu_spill_mask_), ~0u >> (32 - POPCOUNT(fpu_spill_mask_)));
2225
2226 __ Vpush(SRegisterList(vixl32::SRegister(first), POPCOUNT(fpu_spill_mask_)));
2227 GetAssembler()->cfi().AdjustCFAOffset(kArmWordSize * POPCOUNT(fpu_spill_mask_));
2228 GetAssembler()->cfi().RelOffsetForMany(DWARFReg(s0),
2229 /*offset=*/ 0,
2230 fpu_spill_mask_,
2231 kArmWordSize);
2232 }
2233
2234 // Adjust SP and save the current method if we need it. Note that we do
2235 // not save the method in HCurrentMethod, as the instruction might have
2236 // been removed in the SSA graph.
2237 if (RequiresCurrentMethod() && fp_spills_offset <= 3 * kArmWordSize) {
2238 DCHECK_EQ(kMethodRegister.GetCode(), 0u);
2239 __ Push(RegisterList(MaxInt<uint32_t>(fp_spills_offset / kArmWordSize)));
2240 GetAssembler()->cfi().AdjustCFAOffset(fp_spills_offset);
2241 } else {
2242 __ Sub(sp, sp, dchecked_integral_cast<int32_t>(fp_spills_offset));
2243 GetAssembler()->cfi().AdjustCFAOffset(fp_spills_offset);
2244 if (RequiresCurrentMethod()) {
2245 GetAssembler()->StoreToOffset(kStoreWord, kMethodRegister, sp, 0);
2246 }
2247 }
2248 }
2249
2250 if (GetGraph()->HasShouldDeoptimizeFlag()) {
2251 UseScratchRegisterScope temps(GetVIXLAssembler());
2252 vixl32::Register temp = temps.Acquire();
2253 // Initialize should_deoptimize flag to 0.
2254 __ Mov(temp, 0);
2255 GetAssembler()->StoreToOffset(kStoreWord, temp, sp, GetStackOffsetOfShouldDeoptimizeFlag());
2256 }
2257
2258 MaybeIncrementHotness(/* is_frame_entry= */ true);
2259 MaybeGenerateMarkingRegisterCheck(/* code= */ 1);
2260 }
2261
GenerateFrameExit()2262 void CodeGeneratorARMVIXL::GenerateFrameExit() {
2263 if (HasEmptyFrame()) {
2264 __ Bx(lr);
2265 return;
2266 }
2267
2268 // Pop LR into PC to return.
2269 DCHECK_NE(core_spill_mask_ & (1 << kLrCode), 0U);
2270 uint32_t pop_mask = (core_spill_mask_ & (~(1 << kLrCode))) | 1 << kPcCode;
2271
2272 uint32_t frame_size = GetFrameSize();
2273 uint32_t core_spills_offset = frame_size - GetCoreSpillSize();
2274 uint32_t fp_spills_offset = frame_size - FrameEntrySpillSize();
2275 if ((fpu_spill_mask_ == 0u || IsPowerOfTwo(fpu_spill_mask_)) &&
2276 // r4 is blocked by TestCodeGeneratorARMVIXL used by some tests.
2277 core_spills_offset <= (blocked_core_registers_[r4.GetCode()] ? 2u : 3u) * kArmWordSize) {
2278 // Load the FP spill if any and then do a single POP including the method
2279 // and up to two filler registers. If we have no FP spills, this also has
2280 // the advantage that we do not need to emit CFI directives.
2281 if (fpu_spill_mask_ != 0u) {
2282 DCHECK(IsPowerOfTwo(fpu_spill_mask_));
2283 vixl::aarch32::SRegister sreg(LeastSignificantBit(fpu_spill_mask_));
2284 GetAssembler()->cfi().RememberState();
2285 GetAssembler()->LoadSFromOffset(sreg, sp, fp_spills_offset);
2286 GetAssembler()->cfi().Restore(DWARFReg(sreg));
2287 }
2288 // Clobber registers r2-r4 as they are caller-save in ART managed ABI and
2289 // never hold the return value.
2290 uint32_t extra_regs = MaxInt<uint32_t>(core_spills_offset / kArmWordSize) << r2.GetCode();
2291 DCHECK_EQ(extra_regs & kCoreCalleeSaves.GetList(), 0u);
2292 DCHECK_LT(MostSignificantBit(extra_regs), LeastSignificantBit(pop_mask));
2293 __ Pop(RegisterList(pop_mask | extra_regs));
2294 if (fpu_spill_mask_ != 0u) {
2295 GetAssembler()->cfi().RestoreState();
2296 }
2297 } else {
2298 GetAssembler()->cfi().RememberState();
2299 __ Add(sp, sp, fp_spills_offset);
2300 GetAssembler()->cfi().AdjustCFAOffset(-dchecked_integral_cast<int32_t>(fp_spills_offset));
2301 if (fpu_spill_mask_ != 0) {
2302 uint32_t first = LeastSignificantBit(fpu_spill_mask_);
2303
2304 // Check that list is contiguous.
2305 DCHECK_EQ(fpu_spill_mask_ >> CTZ(fpu_spill_mask_), ~0u >> (32 - POPCOUNT(fpu_spill_mask_)));
2306
2307 __ Vpop(SRegisterList(vixl32::SRegister(first), POPCOUNT(fpu_spill_mask_)));
2308 GetAssembler()->cfi().AdjustCFAOffset(
2309 -static_cast<int>(kArmWordSize) * POPCOUNT(fpu_spill_mask_));
2310 GetAssembler()->cfi().RestoreMany(DWARFReg(vixl32::SRegister(0)), fpu_spill_mask_);
2311 }
2312 __ Pop(RegisterList(pop_mask));
2313 GetAssembler()->cfi().RestoreState();
2314 GetAssembler()->cfi().DefCFAOffset(GetFrameSize());
2315 }
2316 }
2317
Bind(HBasicBlock * block)2318 void CodeGeneratorARMVIXL::Bind(HBasicBlock* block) {
2319 __ Bind(GetLabelOf(block));
2320 }
2321
GetNextLocation(DataType::Type type)2322 Location InvokeDexCallingConventionVisitorARMVIXL::GetNextLocation(DataType::Type type) {
2323 switch (type) {
2324 case DataType::Type::kReference:
2325 case DataType::Type::kBool:
2326 case DataType::Type::kUint8:
2327 case DataType::Type::kInt8:
2328 case DataType::Type::kUint16:
2329 case DataType::Type::kInt16:
2330 case DataType::Type::kInt32: {
2331 uint32_t index = gp_index_++;
2332 uint32_t stack_index = stack_index_++;
2333 if (index < calling_convention.GetNumberOfRegisters()) {
2334 return LocationFrom(calling_convention.GetRegisterAt(index));
2335 } else {
2336 return Location::StackSlot(calling_convention.GetStackOffsetOf(stack_index));
2337 }
2338 }
2339
2340 case DataType::Type::kInt64: {
2341 uint32_t index = gp_index_;
2342 uint32_t stack_index = stack_index_;
2343 gp_index_ += 2;
2344 stack_index_ += 2;
2345 if (index + 1 < calling_convention.GetNumberOfRegisters()) {
2346 if (calling_convention.GetRegisterAt(index).Is(r1)) {
2347 // Skip R1, and use R2_R3 instead.
2348 gp_index_++;
2349 index++;
2350 }
2351 }
2352 if (index + 1 < calling_convention.GetNumberOfRegisters()) {
2353 DCHECK_EQ(calling_convention.GetRegisterAt(index).GetCode() + 1,
2354 calling_convention.GetRegisterAt(index + 1).GetCode());
2355
2356 return LocationFrom(calling_convention.GetRegisterAt(index),
2357 calling_convention.GetRegisterAt(index + 1));
2358 } else {
2359 return Location::DoubleStackSlot(calling_convention.GetStackOffsetOf(stack_index));
2360 }
2361 }
2362
2363 case DataType::Type::kFloat32: {
2364 uint32_t stack_index = stack_index_++;
2365 if (float_index_ % 2 == 0) {
2366 float_index_ = std::max(double_index_, float_index_);
2367 }
2368 if (float_index_ < calling_convention.GetNumberOfFpuRegisters()) {
2369 return LocationFrom(calling_convention.GetFpuRegisterAt(float_index_++));
2370 } else {
2371 return Location::StackSlot(calling_convention.GetStackOffsetOf(stack_index));
2372 }
2373 }
2374
2375 case DataType::Type::kFloat64: {
2376 double_index_ = std::max(double_index_, RoundUp(float_index_, 2));
2377 uint32_t stack_index = stack_index_;
2378 stack_index_ += 2;
2379 if (double_index_ + 1 < calling_convention.GetNumberOfFpuRegisters()) {
2380 uint32_t index = double_index_;
2381 double_index_ += 2;
2382 Location result = LocationFrom(
2383 calling_convention.GetFpuRegisterAt(index),
2384 calling_convention.GetFpuRegisterAt(index + 1));
2385 DCHECK(ExpectedPairLayout(result));
2386 return result;
2387 } else {
2388 return Location::DoubleStackSlot(calling_convention.GetStackOffsetOf(stack_index));
2389 }
2390 }
2391
2392 case DataType::Type::kUint32:
2393 case DataType::Type::kUint64:
2394 case DataType::Type::kVoid:
2395 LOG(FATAL) << "Unexpected parameter type " << type;
2396 UNREACHABLE();
2397 }
2398 return Location::NoLocation();
2399 }
2400
GetReturnLocation(DataType::Type type) const2401 Location InvokeDexCallingConventionVisitorARMVIXL::GetReturnLocation(DataType::Type type) const {
2402 switch (type) {
2403 case DataType::Type::kReference:
2404 case DataType::Type::kBool:
2405 case DataType::Type::kUint8:
2406 case DataType::Type::kInt8:
2407 case DataType::Type::kUint16:
2408 case DataType::Type::kInt16:
2409 case DataType::Type::kUint32:
2410 case DataType::Type::kInt32: {
2411 return LocationFrom(r0);
2412 }
2413
2414 case DataType::Type::kFloat32: {
2415 return LocationFrom(s0);
2416 }
2417
2418 case DataType::Type::kUint64:
2419 case DataType::Type::kInt64: {
2420 return LocationFrom(r0, r1);
2421 }
2422
2423 case DataType::Type::kFloat64: {
2424 return LocationFrom(s0, s1);
2425 }
2426
2427 case DataType::Type::kVoid:
2428 return Location::NoLocation();
2429 }
2430
2431 UNREACHABLE();
2432 }
2433
GetMethodLocation() const2434 Location InvokeDexCallingConventionVisitorARMVIXL::GetMethodLocation() const {
2435 return LocationFrom(kMethodRegister);
2436 }
2437
Move32(Location destination,Location source)2438 void CodeGeneratorARMVIXL::Move32(Location destination, Location source) {
2439 if (source.Equals(destination)) {
2440 return;
2441 }
2442 if (destination.IsRegister()) {
2443 if (source.IsRegister()) {
2444 __ Mov(RegisterFrom(destination), RegisterFrom(source));
2445 } else if (source.IsFpuRegister()) {
2446 __ Vmov(RegisterFrom(destination), SRegisterFrom(source));
2447 } else {
2448 GetAssembler()->LoadFromOffset(kLoadWord,
2449 RegisterFrom(destination),
2450 sp,
2451 source.GetStackIndex());
2452 }
2453 } else if (destination.IsFpuRegister()) {
2454 if (source.IsRegister()) {
2455 __ Vmov(SRegisterFrom(destination), RegisterFrom(source));
2456 } else if (source.IsFpuRegister()) {
2457 __ Vmov(SRegisterFrom(destination), SRegisterFrom(source));
2458 } else {
2459 GetAssembler()->LoadSFromOffset(SRegisterFrom(destination), sp, source.GetStackIndex());
2460 }
2461 } else {
2462 DCHECK(destination.IsStackSlot()) << destination;
2463 if (source.IsRegister()) {
2464 GetAssembler()->StoreToOffset(kStoreWord,
2465 RegisterFrom(source),
2466 sp,
2467 destination.GetStackIndex());
2468 } else if (source.IsFpuRegister()) {
2469 GetAssembler()->StoreSToOffset(SRegisterFrom(source), sp, destination.GetStackIndex());
2470 } else {
2471 DCHECK(source.IsStackSlot()) << source;
2472 UseScratchRegisterScope temps(GetVIXLAssembler());
2473 vixl32::Register temp = temps.Acquire();
2474 GetAssembler()->LoadFromOffset(kLoadWord, temp, sp, source.GetStackIndex());
2475 GetAssembler()->StoreToOffset(kStoreWord, temp, sp, destination.GetStackIndex());
2476 }
2477 }
2478 }
2479
MoveConstant(Location location,int32_t value)2480 void CodeGeneratorARMVIXL::MoveConstant(Location location, int32_t value) {
2481 DCHECK(location.IsRegister());
2482 __ Mov(RegisterFrom(location), value);
2483 }
2484
MoveLocation(Location dst,Location src,DataType::Type dst_type)2485 void CodeGeneratorARMVIXL::MoveLocation(Location dst, Location src, DataType::Type dst_type) {
2486 // TODO(VIXL): Maybe refactor to have the 'move' implementation here and use it in
2487 // `ParallelMoveResolverARMVIXL::EmitMove`, as is done in the `arm64` backend.
2488 HParallelMove move(GetGraph()->GetAllocator());
2489 move.AddMove(src, dst, dst_type, nullptr);
2490 GetMoveResolver()->EmitNativeCode(&move);
2491 }
2492
AddLocationAsTemp(Location location,LocationSummary * locations)2493 void CodeGeneratorARMVIXL::AddLocationAsTemp(Location location, LocationSummary* locations) {
2494 if (location.IsRegister()) {
2495 locations->AddTemp(location);
2496 } else if (location.IsRegisterPair()) {
2497 locations->AddTemp(LocationFrom(LowRegisterFrom(location)));
2498 locations->AddTemp(LocationFrom(HighRegisterFrom(location)));
2499 } else {
2500 UNIMPLEMENTED(FATAL) << "AddLocationAsTemp not implemented for location " << location;
2501 }
2502 }
2503
InvokeRuntime(QuickEntrypointEnum entrypoint,HInstruction * instruction,uint32_t dex_pc,SlowPathCode * slow_path)2504 void CodeGeneratorARMVIXL::InvokeRuntime(QuickEntrypointEnum entrypoint,
2505 HInstruction* instruction,
2506 uint32_t dex_pc,
2507 SlowPathCode* slow_path) {
2508 ValidateInvokeRuntime(entrypoint, instruction, slow_path);
2509
2510 ThreadOffset32 entrypoint_offset = GetThreadOffset<kArmPointerSize>(entrypoint);
2511 // Reduce code size for AOT by using shared trampolines for slow path runtime calls across the
2512 // entire oat file. This adds an extra branch and we do not want to slow down the main path.
2513 // For JIT, thunk sharing is per-method, so the gains would be smaller or even negative.
2514 if (slow_path == nullptr || Runtime::Current()->UseJitCompilation()) {
2515 __ Ldr(lr, MemOperand(tr, entrypoint_offset.Int32Value()));
2516 // Ensure the pc position is recorded immediately after the `blx` instruction.
2517 // blx in T32 has only 16bit encoding that's why a stricter check for the scope is used.
2518 ExactAssemblyScope aas(GetVIXLAssembler(),
2519 vixl32::k16BitT32InstructionSizeInBytes,
2520 CodeBufferCheckScope::kExactSize);
2521 __ blx(lr);
2522 if (EntrypointRequiresStackMap(entrypoint)) {
2523 RecordPcInfo(instruction, dex_pc, slow_path);
2524 }
2525 } else {
2526 // Ensure the pc position is recorded immediately after the `bl` instruction.
2527 ExactAssemblyScope aas(GetVIXLAssembler(),
2528 vixl32::k32BitT32InstructionSizeInBytes,
2529 CodeBufferCheckScope::kExactSize);
2530 EmitEntrypointThunkCall(entrypoint_offset);
2531 if (EntrypointRequiresStackMap(entrypoint)) {
2532 RecordPcInfo(instruction, dex_pc, slow_path);
2533 }
2534 }
2535 }
2536
InvokeRuntimeWithoutRecordingPcInfo(int32_t entry_point_offset,HInstruction * instruction,SlowPathCode * slow_path)2537 void CodeGeneratorARMVIXL::InvokeRuntimeWithoutRecordingPcInfo(int32_t entry_point_offset,
2538 HInstruction* instruction,
2539 SlowPathCode* slow_path) {
2540 ValidateInvokeRuntimeWithoutRecordingPcInfo(instruction, slow_path);
2541 __ Ldr(lr, MemOperand(tr, entry_point_offset));
2542 __ Blx(lr);
2543 }
2544
HandleGoto(HInstruction * got,HBasicBlock * successor)2545 void InstructionCodeGeneratorARMVIXL::HandleGoto(HInstruction* got, HBasicBlock* successor) {
2546 if (successor->IsExitBlock()) {
2547 DCHECK(got->GetPrevious()->AlwaysThrows());
2548 return; // no code needed
2549 }
2550
2551 HBasicBlock* block = got->GetBlock();
2552 HInstruction* previous = got->GetPrevious();
2553 HLoopInformation* info = block->GetLoopInformation();
2554
2555 if (info != nullptr && info->IsBackEdge(*block) && info->HasSuspendCheck()) {
2556 codegen_->MaybeIncrementHotness(/* is_frame_entry= */ false);
2557 GenerateSuspendCheck(info->GetSuspendCheck(), successor);
2558 return;
2559 }
2560 if (block->IsEntryBlock() && (previous != nullptr) && previous->IsSuspendCheck()) {
2561 GenerateSuspendCheck(previous->AsSuspendCheck(), nullptr);
2562 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 2);
2563 }
2564 if (!codegen_->GoesToNextBlock(block, successor)) {
2565 __ B(codegen_->GetLabelOf(successor));
2566 }
2567 }
2568
VisitGoto(HGoto * got)2569 void LocationsBuilderARMVIXL::VisitGoto(HGoto* got) {
2570 got->SetLocations(nullptr);
2571 }
2572
VisitGoto(HGoto * got)2573 void InstructionCodeGeneratorARMVIXL::VisitGoto(HGoto* got) {
2574 HandleGoto(got, got->GetSuccessor());
2575 }
2576
VisitTryBoundary(HTryBoundary * try_boundary)2577 void LocationsBuilderARMVIXL::VisitTryBoundary(HTryBoundary* try_boundary) {
2578 try_boundary->SetLocations(nullptr);
2579 }
2580
VisitTryBoundary(HTryBoundary * try_boundary)2581 void InstructionCodeGeneratorARMVIXL::VisitTryBoundary(HTryBoundary* try_boundary) {
2582 HBasicBlock* successor = try_boundary->GetNormalFlowSuccessor();
2583 if (!successor->IsExitBlock()) {
2584 HandleGoto(try_boundary, successor);
2585 }
2586 }
2587
VisitExit(HExit * exit)2588 void LocationsBuilderARMVIXL::VisitExit(HExit* exit) {
2589 exit->SetLocations(nullptr);
2590 }
2591
VisitExit(HExit * exit ATTRIBUTE_UNUSED)2592 void InstructionCodeGeneratorARMVIXL::VisitExit(HExit* exit ATTRIBUTE_UNUSED) {
2593 }
2594
GenerateCompareTestAndBranch(HCondition * condition,vixl32::Label * true_target,vixl32::Label * false_target,bool is_far_target)2595 void InstructionCodeGeneratorARMVIXL::GenerateCompareTestAndBranch(HCondition* condition,
2596 vixl32::Label* true_target,
2597 vixl32::Label* false_target,
2598 bool is_far_target) {
2599 if (true_target == false_target) {
2600 DCHECK(true_target != nullptr);
2601 __ B(true_target);
2602 return;
2603 }
2604
2605 vixl32::Label* non_fallthrough_target;
2606 bool invert;
2607 bool emit_both_branches;
2608
2609 if (true_target == nullptr) {
2610 // The true target is fallthrough.
2611 DCHECK(false_target != nullptr);
2612 non_fallthrough_target = false_target;
2613 invert = true;
2614 emit_both_branches = false;
2615 } else {
2616 non_fallthrough_target = true_target;
2617 invert = false;
2618 // Either the false target is fallthrough, or there is no fallthrough
2619 // and both branches must be emitted.
2620 emit_both_branches = (false_target != nullptr);
2621 }
2622
2623 const auto cond = GenerateTest(condition, invert, codegen_);
2624
2625 __ B(cond.first, non_fallthrough_target, is_far_target);
2626
2627 if (emit_both_branches) {
2628 // No target falls through, we need to branch.
2629 __ B(false_target);
2630 }
2631 }
2632
GenerateTestAndBranch(HInstruction * instruction,size_t condition_input_index,vixl32::Label * true_target,vixl32::Label * false_target,bool far_target)2633 void InstructionCodeGeneratorARMVIXL::GenerateTestAndBranch(HInstruction* instruction,
2634 size_t condition_input_index,
2635 vixl32::Label* true_target,
2636 vixl32::Label* false_target,
2637 bool far_target) {
2638 HInstruction* cond = instruction->InputAt(condition_input_index);
2639
2640 if (true_target == nullptr && false_target == nullptr) {
2641 // Nothing to do. The code always falls through.
2642 return;
2643 } else if (cond->IsIntConstant()) {
2644 // Constant condition, statically compared against "true" (integer value 1).
2645 if (cond->AsIntConstant()->IsTrue()) {
2646 if (true_target != nullptr) {
2647 __ B(true_target);
2648 }
2649 } else {
2650 DCHECK(cond->AsIntConstant()->IsFalse()) << Int32ConstantFrom(cond);
2651 if (false_target != nullptr) {
2652 __ B(false_target);
2653 }
2654 }
2655 return;
2656 }
2657
2658 // The following code generates these patterns:
2659 // (1) true_target == nullptr && false_target != nullptr
2660 // - opposite condition true => branch to false_target
2661 // (2) true_target != nullptr && false_target == nullptr
2662 // - condition true => branch to true_target
2663 // (3) true_target != nullptr && false_target != nullptr
2664 // - condition true => branch to true_target
2665 // - branch to false_target
2666 if (IsBooleanValueOrMaterializedCondition(cond)) {
2667 // Condition has been materialized, compare the output to 0.
2668 if (kIsDebugBuild) {
2669 Location cond_val = instruction->GetLocations()->InAt(condition_input_index);
2670 DCHECK(cond_val.IsRegister());
2671 }
2672 if (true_target == nullptr) {
2673 __ CompareAndBranchIfZero(InputRegisterAt(instruction, condition_input_index),
2674 false_target,
2675 far_target);
2676 } else {
2677 __ CompareAndBranchIfNonZero(InputRegisterAt(instruction, condition_input_index),
2678 true_target,
2679 far_target);
2680 }
2681 } else {
2682 // Condition has not been materialized. Use its inputs as the comparison and
2683 // its condition as the branch condition.
2684 HCondition* condition = cond->AsCondition();
2685
2686 // If this is a long or FP comparison that has been folded into
2687 // the HCondition, generate the comparison directly.
2688 DataType::Type type = condition->InputAt(0)->GetType();
2689 if (type == DataType::Type::kInt64 || DataType::IsFloatingPointType(type)) {
2690 GenerateCompareTestAndBranch(condition, true_target, false_target, far_target);
2691 return;
2692 }
2693
2694 vixl32::Label* non_fallthrough_target;
2695 vixl32::Condition arm_cond = vixl32::Condition::None();
2696 const vixl32::Register left = InputRegisterAt(cond, 0);
2697 const Operand right = InputOperandAt(cond, 1);
2698
2699 if (true_target == nullptr) {
2700 arm_cond = ARMCondition(condition->GetOppositeCondition());
2701 non_fallthrough_target = false_target;
2702 } else {
2703 arm_cond = ARMCondition(condition->GetCondition());
2704 non_fallthrough_target = true_target;
2705 }
2706
2707 if (right.IsImmediate() && right.GetImmediate() == 0 && (arm_cond.Is(ne) || arm_cond.Is(eq))) {
2708 if (arm_cond.Is(eq)) {
2709 __ CompareAndBranchIfZero(left, non_fallthrough_target, far_target);
2710 } else {
2711 DCHECK(arm_cond.Is(ne));
2712 __ CompareAndBranchIfNonZero(left, non_fallthrough_target, far_target);
2713 }
2714 } else {
2715 __ Cmp(left, right);
2716 __ B(arm_cond, non_fallthrough_target, far_target);
2717 }
2718 }
2719
2720 // If neither branch falls through (case 3), the conditional branch to `true_target`
2721 // was already emitted (case 2) and we need to emit a jump to `false_target`.
2722 if (true_target != nullptr && false_target != nullptr) {
2723 __ B(false_target);
2724 }
2725 }
2726
VisitIf(HIf * if_instr)2727 void LocationsBuilderARMVIXL::VisitIf(HIf* if_instr) {
2728 LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(if_instr);
2729 if (IsBooleanValueOrMaterializedCondition(if_instr->InputAt(0))) {
2730 locations->SetInAt(0, Location::RequiresRegister());
2731 }
2732 }
2733
VisitIf(HIf * if_instr)2734 void InstructionCodeGeneratorARMVIXL::VisitIf(HIf* if_instr) {
2735 HBasicBlock* true_successor = if_instr->IfTrueSuccessor();
2736 HBasicBlock* false_successor = if_instr->IfFalseSuccessor();
2737 vixl32::Label* true_target = codegen_->GoesToNextBlock(if_instr->GetBlock(), true_successor) ?
2738 nullptr : codegen_->GetLabelOf(true_successor);
2739 vixl32::Label* false_target = codegen_->GoesToNextBlock(if_instr->GetBlock(), false_successor) ?
2740 nullptr : codegen_->GetLabelOf(false_successor);
2741 GenerateTestAndBranch(if_instr, /* condition_input_index= */ 0, true_target, false_target);
2742 }
2743
VisitDeoptimize(HDeoptimize * deoptimize)2744 void LocationsBuilderARMVIXL::VisitDeoptimize(HDeoptimize* deoptimize) {
2745 LocationSummary* locations = new (GetGraph()->GetAllocator())
2746 LocationSummary(deoptimize, LocationSummary::kCallOnSlowPath);
2747 InvokeRuntimeCallingConventionARMVIXL calling_convention;
2748 RegisterSet caller_saves = RegisterSet::Empty();
2749 caller_saves.Add(LocationFrom(calling_convention.GetRegisterAt(0)));
2750 locations->SetCustomSlowPathCallerSaves(caller_saves);
2751 if (IsBooleanValueOrMaterializedCondition(deoptimize->InputAt(0))) {
2752 locations->SetInAt(0, Location::RequiresRegister());
2753 }
2754 }
2755
VisitDeoptimize(HDeoptimize * deoptimize)2756 void InstructionCodeGeneratorARMVIXL::VisitDeoptimize(HDeoptimize* deoptimize) {
2757 SlowPathCodeARMVIXL* slow_path =
2758 deopt_slow_paths_.NewSlowPath<DeoptimizationSlowPathARMVIXL>(deoptimize);
2759 GenerateTestAndBranch(deoptimize,
2760 /* condition_input_index= */ 0,
2761 slow_path->GetEntryLabel(),
2762 /* false_target= */ nullptr);
2763 }
2764
VisitShouldDeoptimizeFlag(HShouldDeoptimizeFlag * flag)2765 void LocationsBuilderARMVIXL::VisitShouldDeoptimizeFlag(HShouldDeoptimizeFlag* flag) {
2766 LocationSummary* locations = new (GetGraph()->GetAllocator())
2767 LocationSummary(flag, LocationSummary::kNoCall);
2768 locations->SetOut(Location::RequiresRegister());
2769 }
2770
VisitShouldDeoptimizeFlag(HShouldDeoptimizeFlag * flag)2771 void InstructionCodeGeneratorARMVIXL::VisitShouldDeoptimizeFlag(HShouldDeoptimizeFlag* flag) {
2772 GetAssembler()->LoadFromOffset(kLoadWord,
2773 OutputRegister(flag),
2774 sp,
2775 codegen_->GetStackOffsetOfShouldDeoptimizeFlag());
2776 }
2777
VisitSelect(HSelect * select)2778 void LocationsBuilderARMVIXL::VisitSelect(HSelect* select) {
2779 LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(select);
2780 const bool is_floating_point = DataType::IsFloatingPointType(select->GetType());
2781
2782 if (is_floating_point) {
2783 locations->SetInAt(0, Location::RequiresFpuRegister());
2784 locations->SetInAt(1, Location::FpuRegisterOrConstant(select->GetTrueValue()));
2785 } else {
2786 locations->SetInAt(0, Location::RequiresRegister());
2787 locations->SetInAt(1, Arm8BitEncodableConstantOrRegister(select->GetTrueValue()));
2788 }
2789
2790 if (IsBooleanValueOrMaterializedCondition(select->GetCondition())) {
2791 locations->SetInAt(2, Location::RegisterOrConstant(select->GetCondition()));
2792 // The code generator handles overlap with the values, but not with the condition.
2793 locations->SetOut(Location::SameAsFirstInput());
2794 } else if (is_floating_point) {
2795 locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
2796 } else {
2797 if (!locations->InAt(1).IsConstant()) {
2798 locations->SetInAt(0, Arm8BitEncodableConstantOrRegister(select->GetFalseValue()));
2799 }
2800
2801 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
2802 }
2803 }
2804
VisitSelect(HSelect * select)2805 void InstructionCodeGeneratorARMVIXL::VisitSelect(HSelect* select) {
2806 HInstruction* const condition = select->GetCondition();
2807 const LocationSummary* const locations = select->GetLocations();
2808 const DataType::Type type = select->GetType();
2809 const Location first = locations->InAt(0);
2810 const Location out = locations->Out();
2811 const Location second = locations->InAt(1);
2812
2813 // In the unlucky case the output of this instruction overlaps
2814 // with an input of an "emitted-at-use-site" condition, and
2815 // the output of this instruction is not one of its inputs, we'll
2816 // need to fallback to branches instead of conditional ARM instructions.
2817 bool output_overlaps_with_condition_inputs =
2818 !IsBooleanValueOrMaterializedCondition(condition) &&
2819 !out.Equals(first) &&
2820 !out.Equals(second) &&
2821 (condition->GetLocations()->InAt(0).Equals(out) ||
2822 condition->GetLocations()->InAt(1).Equals(out));
2823 DCHECK(!output_overlaps_with_condition_inputs || condition->IsCondition());
2824 Location src;
2825
2826 if (condition->IsIntConstant()) {
2827 if (condition->AsIntConstant()->IsFalse()) {
2828 src = first;
2829 } else {
2830 src = second;
2831 }
2832
2833 codegen_->MoveLocation(out, src, type);
2834 return;
2835 }
2836
2837 if (!DataType::IsFloatingPointType(type) && !output_overlaps_with_condition_inputs) {
2838 bool invert = false;
2839
2840 if (out.Equals(second)) {
2841 src = first;
2842 invert = true;
2843 } else if (out.Equals(first)) {
2844 src = second;
2845 } else if (second.IsConstant()) {
2846 DCHECK(CanEncodeConstantAs8BitImmediate(second.GetConstant()));
2847 src = second;
2848 } else if (first.IsConstant()) {
2849 DCHECK(CanEncodeConstantAs8BitImmediate(first.GetConstant()));
2850 src = first;
2851 invert = true;
2852 } else {
2853 src = second;
2854 }
2855
2856 if (CanGenerateConditionalMove(out, src)) {
2857 if (!out.Equals(first) && !out.Equals(second)) {
2858 codegen_->MoveLocation(out, src.Equals(first) ? second : first, type);
2859 }
2860
2861 std::pair<vixl32::Condition, vixl32::Condition> cond(eq, ne);
2862
2863 if (IsBooleanValueOrMaterializedCondition(condition)) {
2864 __ Cmp(InputRegisterAt(select, 2), 0);
2865 cond = invert ? std::make_pair(eq, ne) : std::make_pair(ne, eq);
2866 } else {
2867 cond = GenerateTest(condition->AsCondition(), invert, codegen_);
2868 }
2869
2870 const size_t instr_count = out.IsRegisterPair() ? 4 : 2;
2871 // We use the scope because of the IT block that follows.
2872 ExactAssemblyScope guard(GetVIXLAssembler(),
2873 instr_count * vixl32::k16BitT32InstructionSizeInBytes,
2874 CodeBufferCheckScope::kExactSize);
2875
2876 if (out.IsRegister()) {
2877 __ it(cond.first);
2878 __ mov(cond.first, RegisterFrom(out), OperandFrom(src, type));
2879 } else {
2880 DCHECK(out.IsRegisterPair());
2881
2882 Operand operand_high(0);
2883 Operand operand_low(0);
2884
2885 if (src.IsConstant()) {
2886 const int64_t value = Int64ConstantFrom(src);
2887
2888 operand_high = High32Bits(value);
2889 operand_low = Low32Bits(value);
2890 } else {
2891 DCHECK(src.IsRegisterPair());
2892 operand_high = HighRegisterFrom(src);
2893 operand_low = LowRegisterFrom(src);
2894 }
2895
2896 __ it(cond.first);
2897 __ mov(cond.first, LowRegisterFrom(out), operand_low);
2898 __ it(cond.first);
2899 __ mov(cond.first, HighRegisterFrom(out), operand_high);
2900 }
2901
2902 return;
2903 }
2904 }
2905
2906 vixl32::Label* false_target = nullptr;
2907 vixl32::Label* true_target = nullptr;
2908 vixl32::Label select_end;
2909 vixl32::Label other_case;
2910 vixl32::Label* const target = codegen_->GetFinalLabel(select, &select_end);
2911
2912 if (out.Equals(second)) {
2913 true_target = target;
2914 src = first;
2915 } else {
2916 false_target = target;
2917 src = second;
2918
2919 if (!out.Equals(first)) {
2920 if (output_overlaps_with_condition_inputs) {
2921 false_target = &other_case;
2922 } else {
2923 codegen_->MoveLocation(out, first, type);
2924 }
2925 }
2926 }
2927
2928 GenerateTestAndBranch(select, 2, true_target, false_target, /* far_target= */ false);
2929 codegen_->MoveLocation(out, src, type);
2930 if (output_overlaps_with_condition_inputs) {
2931 __ B(target);
2932 __ Bind(&other_case);
2933 codegen_->MoveLocation(out, first, type);
2934 }
2935
2936 if (select_end.IsReferenced()) {
2937 __ Bind(&select_end);
2938 }
2939 }
2940
VisitNativeDebugInfo(HNativeDebugInfo * info)2941 void LocationsBuilderARMVIXL::VisitNativeDebugInfo(HNativeDebugInfo* info) {
2942 new (GetGraph()->GetAllocator()) LocationSummary(info);
2943 }
2944
VisitNativeDebugInfo(HNativeDebugInfo *)2945 void InstructionCodeGeneratorARMVIXL::VisitNativeDebugInfo(HNativeDebugInfo*) {
2946 // MaybeRecordNativeDebugInfo is already called implicitly in CodeGenerator::Compile.
2947 }
2948
GenerateNop()2949 void CodeGeneratorARMVIXL::GenerateNop() {
2950 __ Nop();
2951 }
2952
2953 // `temp` is an extra temporary register that is used for some conditions;
2954 // callers may not specify it, in which case the method will use a scratch
2955 // register instead.
GenerateConditionWithZero(IfCondition condition,vixl32::Register out,vixl32::Register in,vixl32::Register temp)2956 void CodeGeneratorARMVIXL::GenerateConditionWithZero(IfCondition condition,
2957 vixl32::Register out,
2958 vixl32::Register in,
2959 vixl32::Register temp) {
2960 switch (condition) {
2961 case kCondEQ:
2962 // x <= 0 iff x == 0 when the comparison is unsigned.
2963 case kCondBE:
2964 if (!temp.IsValid() || (out.IsLow() && !out.Is(in))) {
2965 temp = out;
2966 }
2967
2968 // Avoid 32-bit instructions if possible; note that `in` and `temp` must be
2969 // different as well.
2970 if (in.IsLow() && temp.IsLow() && !in.Is(temp)) {
2971 // temp = - in; only 0 sets the carry flag.
2972 __ Rsbs(temp, in, 0);
2973
2974 if (out.Is(in)) {
2975 std::swap(in, temp);
2976 }
2977
2978 // out = - in + in + carry = carry
2979 __ Adc(out, temp, in);
2980 } else {
2981 // If `in` is 0, then it has 32 leading zeros, and less than that otherwise.
2982 __ Clz(out, in);
2983 // Any number less than 32 logically shifted right by 5 bits results in 0;
2984 // the same operation on 32 yields 1.
2985 __ Lsr(out, out, 5);
2986 }
2987
2988 break;
2989 case kCondNE:
2990 // x > 0 iff x != 0 when the comparison is unsigned.
2991 case kCondA: {
2992 UseScratchRegisterScope temps(GetVIXLAssembler());
2993
2994 if (out.Is(in)) {
2995 if (!temp.IsValid() || in.Is(temp)) {
2996 temp = temps.Acquire();
2997 }
2998 } else if (!temp.IsValid() || !temp.IsLow()) {
2999 temp = out;
3000 }
3001
3002 // temp = in - 1; only 0 does not set the carry flag.
3003 __ Subs(temp, in, 1);
3004 // out = in + ~temp + carry = in + (-(in - 1) - 1) + carry = in - in + 1 - 1 + carry = carry
3005 __ Sbc(out, in, temp);
3006 break;
3007 }
3008 case kCondGE:
3009 __ Mvn(out, in);
3010 in = out;
3011 FALLTHROUGH_INTENDED;
3012 case kCondLT:
3013 // We only care about the sign bit.
3014 __ Lsr(out, in, 31);
3015 break;
3016 case kCondAE:
3017 // Trivially true.
3018 __ Mov(out, 1);
3019 break;
3020 case kCondB:
3021 // Trivially false.
3022 __ Mov(out, 0);
3023 break;
3024 default:
3025 LOG(FATAL) << "Unexpected condition " << condition;
3026 UNREACHABLE();
3027 }
3028 }
3029
HandleCondition(HCondition * cond)3030 void LocationsBuilderARMVIXL::HandleCondition(HCondition* cond) {
3031 LocationSummary* locations =
3032 new (GetGraph()->GetAllocator()) LocationSummary(cond, LocationSummary::kNoCall);
3033 const DataType::Type type = cond->InputAt(0)->GetType();
3034 if (DataType::IsFloatingPointType(type)) {
3035 locations->SetInAt(0, Location::RequiresFpuRegister());
3036 locations->SetInAt(1, ArithmeticZeroOrFpuRegister(cond->InputAt(1)));
3037 } else {
3038 locations->SetInAt(0, Location::RequiresRegister());
3039 locations->SetInAt(1, Location::RegisterOrConstant(cond->InputAt(1)));
3040 }
3041 if (!cond->IsEmittedAtUseSite()) {
3042 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
3043 }
3044 }
3045
HandleCondition(HCondition * cond)3046 void InstructionCodeGeneratorARMVIXL::HandleCondition(HCondition* cond) {
3047 if (cond->IsEmittedAtUseSite()) {
3048 return;
3049 }
3050
3051 const DataType::Type type = cond->GetLeft()->GetType();
3052
3053 if (DataType::IsFloatingPointType(type)) {
3054 GenerateConditionGeneric(cond, codegen_);
3055 return;
3056 }
3057
3058 DCHECK(DataType::IsIntegralType(type) || type == DataType::Type::kReference) << type;
3059
3060 const IfCondition condition = cond->GetCondition();
3061
3062 // A condition with only one boolean input, or two boolean inputs without being equality or
3063 // inequality results from transformations done by the instruction simplifier, and is handled
3064 // as a regular condition with integral inputs.
3065 if (type == DataType::Type::kBool &&
3066 cond->GetRight()->GetType() == DataType::Type::kBool &&
3067 (condition == kCondEQ || condition == kCondNE)) {
3068 vixl32::Register left = InputRegisterAt(cond, 0);
3069 const vixl32::Register out = OutputRegister(cond);
3070 const Location right_loc = cond->GetLocations()->InAt(1);
3071
3072 // The constant case is handled by the instruction simplifier.
3073 DCHECK(!right_loc.IsConstant());
3074
3075 vixl32::Register right = RegisterFrom(right_loc);
3076
3077 // Avoid 32-bit instructions if possible.
3078 if (out.Is(right)) {
3079 std::swap(left, right);
3080 }
3081
3082 __ Eor(out, left, right);
3083
3084 if (condition == kCondEQ) {
3085 __ Eor(out, out, 1);
3086 }
3087
3088 return;
3089 }
3090
3091 GenerateConditionIntegralOrNonPrimitive(cond, codegen_);
3092 }
3093
VisitEqual(HEqual * comp)3094 void LocationsBuilderARMVIXL::VisitEqual(HEqual* comp) {
3095 HandleCondition(comp);
3096 }
3097
VisitEqual(HEqual * comp)3098 void InstructionCodeGeneratorARMVIXL::VisitEqual(HEqual* comp) {
3099 HandleCondition(comp);
3100 }
3101
VisitNotEqual(HNotEqual * comp)3102 void LocationsBuilderARMVIXL::VisitNotEqual(HNotEqual* comp) {
3103 HandleCondition(comp);
3104 }
3105
VisitNotEqual(HNotEqual * comp)3106 void InstructionCodeGeneratorARMVIXL::VisitNotEqual(HNotEqual* comp) {
3107 HandleCondition(comp);
3108 }
3109
VisitLessThan(HLessThan * comp)3110 void LocationsBuilderARMVIXL::VisitLessThan(HLessThan* comp) {
3111 HandleCondition(comp);
3112 }
3113
VisitLessThan(HLessThan * comp)3114 void InstructionCodeGeneratorARMVIXL::VisitLessThan(HLessThan* comp) {
3115 HandleCondition(comp);
3116 }
3117
VisitLessThanOrEqual(HLessThanOrEqual * comp)3118 void LocationsBuilderARMVIXL::VisitLessThanOrEqual(HLessThanOrEqual* comp) {
3119 HandleCondition(comp);
3120 }
3121
VisitLessThanOrEqual(HLessThanOrEqual * comp)3122 void InstructionCodeGeneratorARMVIXL::VisitLessThanOrEqual(HLessThanOrEqual* comp) {
3123 HandleCondition(comp);
3124 }
3125
VisitGreaterThan(HGreaterThan * comp)3126 void LocationsBuilderARMVIXL::VisitGreaterThan(HGreaterThan* comp) {
3127 HandleCondition(comp);
3128 }
3129
VisitGreaterThan(HGreaterThan * comp)3130 void InstructionCodeGeneratorARMVIXL::VisitGreaterThan(HGreaterThan* comp) {
3131 HandleCondition(comp);
3132 }
3133
VisitGreaterThanOrEqual(HGreaterThanOrEqual * comp)3134 void LocationsBuilderARMVIXL::VisitGreaterThanOrEqual(HGreaterThanOrEqual* comp) {
3135 HandleCondition(comp);
3136 }
3137
VisitGreaterThanOrEqual(HGreaterThanOrEqual * comp)3138 void InstructionCodeGeneratorARMVIXL::VisitGreaterThanOrEqual(HGreaterThanOrEqual* comp) {
3139 HandleCondition(comp);
3140 }
3141
VisitBelow(HBelow * comp)3142 void LocationsBuilderARMVIXL::VisitBelow(HBelow* comp) {
3143 HandleCondition(comp);
3144 }
3145
VisitBelow(HBelow * comp)3146 void InstructionCodeGeneratorARMVIXL::VisitBelow(HBelow* comp) {
3147 HandleCondition(comp);
3148 }
3149
VisitBelowOrEqual(HBelowOrEqual * comp)3150 void LocationsBuilderARMVIXL::VisitBelowOrEqual(HBelowOrEqual* comp) {
3151 HandleCondition(comp);
3152 }
3153
VisitBelowOrEqual(HBelowOrEqual * comp)3154 void InstructionCodeGeneratorARMVIXL::VisitBelowOrEqual(HBelowOrEqual* comp) {
3155 HandleCondition(comp);
3156 }
3157
VisitAbove(HAbove * comp)3158 void LocationsBuilderARMVIXL::VisitAbove(HAbove* comp) {
3159 HandleCondition(comp);
3160 }
3161
VisitAbove(HAbove * comp)3162 void InstructionCodeGeneratorARMVIXL::VisitAbove(HAbove* comp) {
3163 HandleCondition(comp);
3164 }
3165
VisitAboveOrEqual(HAboveOrEqual * comp)3166 void LocationsBuilderARMVIXL::VisitAboveOrEqual(HAboveOrEqual* comp) {
3167 HandleCondition(comp);
3168 }
3169
VisitAboveOrEqual(HAboveOrEqual * comp)3170 void InstructionCodeGeneratorARMVIXL::VisitAboveOrEqual(HAboveOrEqual* comp) {
3171 HandleCondition(comp);
3172 }
3173
VisitIntConstant(HIntConstant * constant)3174 void LocationsBuilderARMVIXL::VisitIntConstant(HIntConstant* constant) {
3175 LocationSummary* locations =
3176 new (GetGraph()->GetAllocator()) LocationSummary(constant, LocationSummary::kNoCall);
3177 locations->SetOut(Location::ConstantLocation(constant));
3178 }
3179
VisitIntConstant(HIntConstant * constant ATTRIBUTE_UNUSED)3180 void InstructionCodeGeneratorARMVIXL::VisitIntConstant(HIntConstant* constant ATTRIBUTE_UNUSED) {
3181 // Will be generated at use site.
3182 }
3183
VisitNullConstant(HNullConstant * constant)3184 void LocationsBuilderARMVIXL::VisitNullConstant(HNullConstant* constant) {
3185 LocationSummary* locations =
3186 new (GetGraph()->GetAllocator()) LocationSummary(constant, LocationSummary::kNoCall);
3187 locations->SetOut(Location::ConstantLocation(constant));
3188 }
3189
VisitNullConstant(HNullConstant * constant ATTRIBUTE_UNUSED)3190 void InstructionCodeGeneratorARMVIXL::VisitNullConstant(HNullConstant* constant ATTRIBUTE_UNUSED) {
3191 // Will be generated at use site.
3192 }
3193
VisitLongConstant(HLongConstant * constant)3194 void LocationsBuilderARMVIXL::VisitLongConstant(HLongConstant* constant) {
3195 LocationSummary* locations =
3196 new (GetGraph()->GetAllocator()) LocationSummary(constant, LocationSummary::kNoCall);
3197 locations->SetOut(Location::ConstantLocation(constant));
3198 }
3199
VisitLongConstant(HLongConstant * constant ATTRIBUTE_UNUSED)3200 void InstructionCodeGeneratorARMVIXL::VisitLongConstant(HLongConstant* constant ATTRIBUTE_UNUSED) {
3201 // Will be generated at use site.
3202 }
3203
VisitFloatConstant(HFloatConstant * constant)3204 void LocationsBuilderARMVIXL::VisitFloatConstant(HFloatConstant* constant) {
3205 LocationSummary* locations =
3206 new (GetGraph()->GetAllocator()) LocationSummary(constant, LocationSummary::kNoCall);
3207 locations->SetOut(Location::ConstantLocation(constant));
3208 }
3209
VisitFloatConstant(HFloatConstant * constant ATTRIBUTE_UNUSED)3210 void InstructionCodeGeneratorARMVIXL::VisitFloatConstant(
3211 HFloatConstant* constant ATTRIBUTE_UNUSED) {
3212 // Will be generated at use site.
3213 }
3214
VisitDoubleConstant(HDoubleConstant * constant)3215 void LocationsBuilderARMVIXL::VisitDoubleConstant(HDoubleConstant* constant) {
3216 LocationSummary* locations =
3217 new (GetGraph()->GetAllocator()) LocationSummary(constant, LocationSummary::kNoCall);
3218 locations->SetOut(Location::ConstantLocation(constant));
3219 }
3220
VisitDoubleConstant(HDoubleConstant * constant ATTRIBUTE_UNUSED)3221 void InstructionCodeGeneratorARMVIXL::VisitDoubleConstant(
3222 HDoubleConstant* constant ATTRIBUTE_UNUSED) {
3223 // Will be generated at use site.
3224 }
3225
VisitConstructorFence(HConstructorFence * constructor_fence)3226 void LocationsBuilderARMVIXL::VisitConstructorFence(HConstructorFence* constructor_fence) {
3227 constructor_fence->SetLocations(nullptr);
3228 }
3229
VisitConstructorFence(HConstructorFence * constructor_fence ATTRIBUTE_UNUSED)3230 void InstructionCodeGeneratorARMVIXL::VisitConstructorFence(
3231 HConstructorFence* constructor_fence ATTRIBUTE_UNUSED) {
3232 codegen_->GenerateMemoryBarrier(MemBarrierKind::kStoreStore);
3233 }
3234
VisitMemoryBarrier(HMemoryBarrier * memory_barrier)3235 void LocationsBuilderARMVIXL::VisitMemoryBarrier(HMemoryBarrier* memory_barrier) {
3236 memory_barrier->SetLocations(nullptr);
3237 }
3238
VisitMemoryBarrier(HMemoryBarrier * memory_barrier)3239 void InstructionCodeGeneratorARMVIXL::VisitMemoryBarrier(HMemoryBarrier* memory_barrier) {
3240 codegen_->GenerateMemoryBarrier(memory_barrier->GetBarrierKind());
3241 }
3242
VisitReturnVoid(HReturnVoid * ret)3243 void LocationsBuilderARMVIXL::VisitReturnVoid(HReturnVoid* ret) {
3244 ret->SetLocations(nullptr);
3245 }
3246
VisitReturnVoid(HReturnVoid * ret ATTRIBUTE_UNUSED)3247 void InstructionCodeGeneratorARMVIXL::VisitReturnVoid(HReturnVoid* ret ATTRIBUTE_UNUSED) {
3248 codegen_->GenerateFrameExit();
3249 }
3250
VisitReturn(HReturn * ret)3251 void LocationsBuilderARMVIXL::VisitReturn(HReturn* ret) {
3252 LocationSummary* locations =
3253 new (GetGraph()->GetAllocator()) LocationSummary(ret, LocationSummary::kNoCall);
3254 locations->SetInAt(0, parameter_visitor_.GetReturnLocation(ret->InputAt(0)->GetType()));
3255 }
3256
VisitReturn(HReturn * ret)3257 void InstructionCodeGeneratorARMVIXL::VisitReturn(HReturn* ret) {
3258 if (GetGraph()->IsCompilingOsr()) {
3259 // To simplify callers of an OSR method, we put the return value in both
3260 // floating point and core registers.
3261 switch (ret->InputAt(0)->GetType()) {
3262 case DataType::Type::kFloat32:
3263 __ Vmov(r0, s0);
3264 break;
3265 case DataType::Type::kFloat64:
3266 __ Vmov(r0, r1, d0);
3267 break;
3268 default:
3269 break;
3270 }
3271 }
3272 codegen_->GenerateFrameExit();
3273 }
3274
VisitInvokeUnresolved(HInvokeUnresolved * invoke)3275 void LocationsBuilderARMVIXL::VisitInvokeUnresolved(HInvokeUnresolved* invoke) {
3276 // The trampoline uses the same calling convention as dex calling conventions,
3277 // except instead of loading arg0/r0 with the target Method*, arg0/r0 will contain
3278 // the method_idx.
3279 HandleInvoke(invoke);
3280 }
3281
VisitInvokeUnresolved(HInvokeUnresolved * invoke)3282 void InstructionCodeGeneratorARMVIXL::VisitInvokeUnresolved(HInvokeUnresolved* invoke) {
3283 codegen_->GenerateInvokeUnresolvedRuntimeCall(invoke);
3284 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 3);
3285 }
3286
VisitInvokeStaticOrDirect(HInvokeStaticOrDirect * invoke)3287 void LocationsBuilderARMVIXL::VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) {
3288 // Explicit clinit checks triggered by static invokes must have been pruned by
3289 // art::PrepareForRegisterAllocation.
3290 DCHECK(!invoke->IsStaticWithExplicitClinitCheck());
3291
3292 IntrinsicLocationsBuilderARMVIXL intrinsic(codegen_);
3293 if (intrinsic.TryDispatch(invoke)) {
3294 return;
3295 }
3296
3297 HandleInvoke(invoke);
3298 }
3299
TryGenerateIntrinsicCode(HInvoke * invoke,CodeGeneratorARMVIXL * codegen)3300 static bool TryGenerateIntrinsicCode(HInvoke* invoke, CodeGeneratorARMVIXL* codegen) {
3301 if (invoke->GetLocations()->Intrinsified()) {
3302 IntrinsicCodeGeneratorARMVIXL intrinsic(codegen);
3303 intrinsic.Dispatch(invoke);
3304 return true;
3305 }
3306 return false;
3307 }
3308
VisitInvokeStaticOrDirect(HInvokeStaticOrDirect * invoke)3309 void InstructionCodeGeneratorARMVIXL::VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) {
3310 // Explicit clinit checks triggered by static invokes must have been pruned by
3311 // art::PrepareForRegisterAllocation.
3312 DCHECK(!invoke->IsStaticWithExplicitClinitCheck());
3313
3314 if (TryGenerateIntrinsicCode(invoke, codegen_)) {
3315 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 4);
3316 return;
3317 }
3318
3319 LocationSummary* locations = invoke->GetLocations();
3320 codegen_->GenerateStaticOrDirectCall(
3321 invoke, locations->HasTemps() ? locations->GetTemp(0) : Location::NoLocation());
3322
3323 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 5);
3324 }
3325
HandleInvoke(HInvoke * invoke)3326 void LocationsBuilderARMVIXL::HandleInvoke(HInvoke* invoke) {
3327 InvokeDexCallingConventionVisitorARMVIXL calling_convention_visitor;
3328 CodeGenerator::CreateCommonInvokeLocationSummary(invoke, &calling_convention_visitor);
3329 }
3330
VisitInvokeVirtual(HInvokeVirtual * invoke)3331 void LocationsBuilderARMVIXL::VisitInvokeVirtual(HInvokeVirtual* invoke) {
3332 IntrinsicLocationsBuilderARMVIXL intrinsic(codegen_);
3333 if (intrinsic.TryDispatch(invoke)) {
3334 return;
3335 }
3336
3337 HandleInvoke(invoke);
3338 }
3339
VisitInvokeVirtual(HInvokeVirtual * invoke)3340 void InstructionCodeGeneratorARMVIXL::VisitInvokeVirtual(HInvokeVirtual* invoke) {
3341 if (TryGenerateIntrinsicCode(invoke, codegen_)) {
3342 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 6);
3343 return;
3344 }
3345
3346 codegen_->GenerateVirtualCall(invoke, invoke->GetLocations()->GetTemp(0));
3347 DCHECK(!codegen_->IsLeafMethod());
3348
3349 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 7);
3350 }
3351
VisitInvokeInterface(HInvokeInterface * invoke)3352 void LocationsBuilderARMVIXL::VisitInvokeInterface(HInvokeInterface* invoke) {
3353 HandleInvoke(invoke);
3354 // Add the hidden argument.
3355 invoke->GetLocations()->AddTemp(LocationFrom(r12));
3356 }
3357
MaybeGenerateInlineCacheCheck(HInstruction * instruction,vixl32::Register klass)3358 void CodeGeneratorARMVIXL::MaybeGenerateInlineCacheCheck(HInstruction* instruction,
3359 vixl32::Register klass) {
3360 DCHECK_EQ(r0.GetCode(), klass.GetCode());
3361 // We know the destination of an intrinsic, so no need to record inline
3362 // caches.
3363 if (!instruction->GetLocations()->Intrinsified() &&
3364 GetGraph()->IsCompilingBaseline() &&
3365 !Runtime::Current()->IsAotCompiler()) {
3366 DCHECK(!instruction->GetEnvironment()->IsFromInlinedInvoke());
3367 ScopedObjectAccess soa(Thread::Current());
3368 ProfilingInfo* info = GetGraph()->GetArtMethod()->GetProfilingInfo(kRuntimePointerSize);
3369 if (info != nullptr) {
3370 InlineCache* cache = info->GetInlineCache(instruction->GetDexPc());
3371 uint32_t address = reinterpret_cast32<uint32_t>(cache);
3372 vixl32::Label done;
3373 UseScratchRegisterScope temps(GetVIXLAssembler());
3374 temps.Exclude(ip);
3375 __ Mov(r4, address);
3376 __ Ldr(ip, MemOperand(r4, InlineCache::ClassesOffset().Int32Value()));
3377 // Fast path for a monomorphic cache.
3378 __ Cmp(klass, ip);
3379 __ B(eq, &done, /* is_far_target= */ false);
3380 InvokeRuntime(kQuickUpdateInlineCache, instruction, instruction->GetDexPc());
3381 __ Bind(&done);
3382 }
3383 }
3384 }
3385
VisitInvokeInterface(HInvokeInterface * invoke)3386 void InstructionCodeGeneratorARMVIXL::VisitInvokeInterface(HInvokeInterface* invoke) {
3387 // TODO: b/18116999, our IMTs can miss an IncompatibleClassChangeError.
3388 LocationSummary* locations = invoke->GetLocations();
3389 vixl32::Register temp = RegisterFrom(locations->GetTemp(0));
3390 vixl32::Register hidden_reg = RegisterFrom(locations->GetTemp(1));
3391 Location receiver = locations->InAt(0);
3392 uint32_t class_offset = mirror::Object::ClassOffset().Int32Value();
3393
3394 DCHECK(!receiver.IsStackSlot());
3395
3396 // Ensure the pc position is recorded immediately after the `ldr` instruction.
3397 {
3398 ExactAssemblyScope aas(GetVIXLAssembler(),
3399 vixl32::kMaxInstructionSizeInBytes,
3400 CodeBufferCheckScope::kMaximumSize);
3401 // /* HeapReference<Class> */ temp = receiver->klass_
3402 __ ldr(temp, MemOperand(RegisterFrom(receiver), class_offset));
3403 codegen_->MaybeRecordImplicitNullCheck(invoke);
3404 }
3405 // Instead of simply (possibly) unpoisoning `temp` here, we should
3406 // emit a read barrier for the previous class reference load.
3407 // However this is not required in practice, as this is an
3408 // intermediate/temporary reference and because the current
3409 // concurrent copying collector keeps the from-space memory
3410 // intact/accessible until the end of the marking phase (the
3411 // concurrent copying collector may not in the future).
3412 GetAssembler()->MaybeUnpoisonHeapReference(temp);
3413
3414 // If we're compiling baseline, update the inline cache.
3415 codegen_->MaybeGenerateInlineCacheCheck(invoke, temp);
3416
3417 GetAssembler()->LoadFromOffset(kLoadWord,
3418 temp,
3419 temp,
3420 mirror::Class::ImtPtrOffset(kArmPointerSize).Uint32Value());
3421
3422 uint32_t method_offset = static_cast<uint32_t>(ImTable::OffsetOfElement(
3423 invoke->GetImtIndex(), kArmPointerSize));
3424 // temp = temp->GetImtEntryAt(method_offset);
3425 GetAssembler()->LoadFromOffset(kLoadWord, temp, temp, method_offset);
3426 uint32_t entry_point =
3427 ArtMethod::EntryPointFromQuickCompiledCodeOffset(kArmPointerSize).Int32Value();
3428 // LR = temp->GetEntryPoint();
3429 GetAssembler()->LoadFromOffset(kLoadWord, lr, temp, entry_point);
3430
3431 // Set the hidden (in r12) argument. It is done here, right before a BLX to prevent other
3432 // instruction from clobbering it as they might use r12 as a scratch register.
3433 DCHECK(hidden_reg.Is(r12));
3434
3435 {
3436 // The VIXL macro assembler may clobber any of the scratch registers that are available to it,
3437 // so it checks if the application is using them (by passing them to the macro assembler
3438 // methods). The following application of UseScratchRegisterScope corrects VIXL's notion of
3439 // what is available, and is the opposite of the standard usage: Instead of requesting a
3440 // temporary location, it imposes an external constraint (i.e. a specific register is reserved
3441 // for the hidden argument). Note that this works even if VIXL needs a scratch register itself
3442 // (to materialize the constant), since the destination register becomes available for such use
3443 // internally for the duration of the macro instruction.
3444 UseScratchRegisterScope temps(GetVIXLAssembler());
3445 temps.Exclude(hidden_reg);
3446 __ Mov(hidden_reg, invoke->GetDexMethodIndex());
3447 }
3448 {
3449 // Ensure the pc position is recorded immediately after the `blx` instruction.
3450 // blx in T32 has only 16bit encoding that's why a stricter check for the scope is used.
3451 ExactAssemblyScope aas(GetVIXLAssembler(),
3452 vixl32::k16BitT32InstructionSizeInBytes,
3453 CodeBufferCheckScope::kExactSize);
3454 // LR();
3455 __ blx(lr);
3456 codegen_->RecordPcInfo(invoke, invoke->GetDexPc());
3457 DCHECK(!codegen_->IsLeafMethod());
3458 }
3459
3460 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 8);
3461 }
3462
VisitInvokePolymorphic(HInvokePolymorphic * invoke)3463 void LocationsBuilderARMVIXL::VisitInvokePolymorphic(HInvokePolymorphic* invoke) {
3464 HandleInvoke(invoke);
3465 }
3466
VisitInvokePolymorphic(HInvokePolymorphic * invoke)3467 void InstructionCodeGeneratorARMVIXL::VisitInvokePolymorphic(HInvokePolymorphic* invoke) {
3468 codegen_->GenerateInvokePolymorphicCall(invoke);
3469 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 9);
3470 }
3471
VisitInvokeCustom(HInvokeCustom * invoke)3472 void LocationsBuilderARMVIXL::VisitInvokeCustom(HInvokeCustom* invoke) {
3473 HandleInvoke(invoke);
3474 }
3475
VisitInvokeCustom(HInvokeCustom * invoke)3476 void InstructionCodeGeneratorARMVIXL::VisitInvokeCustom(HInvokeCustom* invoke) {
3477 codegen_->GenerateInvokeCustomCall(invoke);
3478 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 10);
3479 }
3480
VisitNeg(HNeg * neg)3481 void LocationsBuilderARMVIXL::VisitNeg(HNeg* neg) {
3482 LocationSummary* locations =
3483 new (GetGraph()->GetAllocator()) LocationSummary(neg, LocationSummary::kNoCall);
3484 switch (neg->GetResultType()) {
3485 case DataType::Type::kInt32: {
3486 locations->SetInAt(0, Location::RequiresRegister());
3487 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
3488 break;
3489 }
3490 case DataType::Type::kInt64: {
3491 locations->SetInAt(0, Location::RequiresRegister());
3492 locations->SetOut(Location::RequiresRegister(), Location::kOutputOverlap);
3493 break;
3494 }
3495
3496 case DataType::Type::kFloat32:
3497 case DataType::Type::kFloat64:
3498 locations->SetInAt(0, Location::RequiresFpuRegister());
3499 locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
3500 break;
3501
3502 default:
3503 LOG(FATAL) << "Unexpected neg type " << neg->GetResultType();
3504 }
3505 }
3506
VisitNeg(HNeg * neg)3507 void InstructionCodeGeneratorARMVIXL::VisitNeg(HNeg* neg) {
3508 LocationSummary* locations = neg->GetLocations();
3509 Location out = locations->Out();
3510 Location in = locations->InAt(0);
3511 switch (neg->GetResultType()) {
3512 case DataType::Type::kInt32:
3513 __ Rsb(OutputRegister(neg), InputRegisterAt(neg, 0), 0);
3514 break;
3515
3516 case DataType::Type::kInt64:
3517 // out.lo = 0 - in.lo (and update the carry/borrow (C) flag)
3518 __ Rsbs(LowRegisterFrom(out), LowRegisterFrom(in), 0);
3519 // We cannot emit an RSC (Reverse Subtract with Carry)
3520 // instruction here, as it does not exist in the Thumb-2
3521 // instruction set. We use the following approach
3522 // using SBC and SUB instead.
3523 //
3524 // out.hi = -C
3525 __ Sbc(HighRegisterFrom(out), HighRegisterFrom(out), HighRegisterFrom(out));
3526 // out.hi = out.hi - in.hi
3527 __ Sub(HighRegisterFrom(out), HighRegisterFrom(out), HighRegisterFrom(in));
3528 break;
3529
3530 case DataType::Type::kFloat32:
3531 case DataType::Type::kFloat64:
3532 __ Vneg(OutputVRegister(neg), InputVRegister(neg));
3533 break;
3534
3535 default:
3536 LOG(FATAL) << "Unexpected neg type " << neg->GetResultType();
3537 }
3538 }
3539
VisitTypeConversion(HTypeConversion * conversion)3540 void LocationsBuilderARMVIXL::VisitTypeConversion(HTypeConversion* conversion) {
3541 DataType::Type result_type = conversion->GetResultType();
3542 DataType::Type input_type = conversion->GetInputType();
3543 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
3544 << input_type << " -> " << result_type;
3545
3546 // The float-to-long, double-to-long and long-to-float type conversions
3547 // rely on a call to the runtime.
3548 LocationSummary::CallKind call_kind =
3549 (((input_type == DataType::Type::kFloat32 || input_type == DataType::Type::kFloat64)
3550 && result_type == DataType::Type::kInt64)
3551 || (input_type == DataType::Type::kInt64 && result_type == DataType::Type::kFloat32))
3552 ? LocationSummary::kCallOnMainOnly
3553 : LocationSummary::kNoCall;
3554 LocationSummary* locations =
3555 new (GetGraph()->GetAllocator()) LocationSummary(conversion, call_kind);
3556
3557 switch (result_type) {
3558 case DataType::Type::kUint8:
3559 case DataType::Type::kInt8:
3560 case DataType::Type::kUint16:
3561 case DataType::Type::kInt16:
3562 DCHECK(DataType::IsIntegralType(input_type)) << input_type;
3563 locations->SetInAt(0, Location::RequiresRegister());
3564 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
3565 break;
3566
3567 case DataType::Type::kInt32:
3568 switch (input_type) {
3569 case DataType::Type::kInt64:
3570 locations->SetInAt(0, Location::Any());
3571 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
3572 break;
3573
3574 case DataType::Type::kFloat32:
3575 locations->SetInAt(0, Location::RequiresFpuRegister());
3576 locations->SetOut(Location::RequiresRegister());
3577 locations->AddTemp(Location::RequiresFpuRegister());
3578 break;
3579
3580 case DataType::Type::kFloat64:
3581 locations->SetInAt(0, Location::RequiresFpuRegister());
3582 locations->SetOut(Location::RequiresRegister());
3583 locations->AddTemp(Location::RequiresFpuRegister());
3584 break;
3585
3586 default:
3587 LOG(FATAL) << "Unexpected type conversion from " << input_type
3588 << " to " << result_type;
3589 }
3590 break;
3591
3592 case DataType::Type::kInt64:
3593 switch (input_type) {
3594 case DataType::Type::kBool:
3595 case DataType::Type::kUint8:
3596 case DataType::Type::kInt8:
3597 case DataType::Type::kUint16:
3598 case DataType::Type::kInt16:
3599 case DataType::Type::kInt32:
3600 locations->SetInAt(0, Location::RequiresRegister());
3601 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
3602 break;
3603
3604 case DataType::Type::kFloat32: {
3605 InvokeRuntimeCallingConventionARMVIXL calling_convention;
3606 locations->SetInAt(0, LocationFrom(calling_convention.GetFpuRegisterAt(0)));
3607 locations->SetOut(LocationFrom(r0, r1));
3608 break;
3609 }
3610
3611 case DataType::Type::kFloat64: {
3612 InvokeRuntimeCallingConventionARMVIXL calling_convention;
3613 locations->SetInAt(0, LocationFrom(calling_convention.GetFpuRegisterAt(0),
3614 calling_convention.GetFpuRegisterAt(1)));
3615 locations->SetOut(LocationFrom(r0, r1));
3616 break;
3617 }
3618
3619 default:
3620 LOG(FATAL) << "Unexpected type conversion from " << input_type
3621 << " to " << result_type;
3622 }
3623 break;
3624
3625 case DataType::Type::kFloat32:
3626 switch (input_type) {
3627 case DataType::Type::kBool:
3628 case DataType::Type::kUint8:
3629 case DataType::Type::kInt8:
3630 case DataType::Type::kUint16:
3631 case DataType::Type::kInt16:
3632 case DataType::Type::kInt32:
3633 locations->SetInAt(0, Location::RequiresRegister());
3634 locations->SetOut(Location::RequiresFpuRegister());
3635 break;
3636
3637 case DataType::Type::kInt64: {
3638 InvokeRuntimeCallingConventionARMVIXL calling_convention;
3639 locations->SetInAt(0, LocationFrom(calling_convention.GetRegisterAt(0),
3640 calling_convention.GetRegisterAt(1)));
3641 locations->SetOut(LocationFrom(calling_convention.GetFpuRegisterAt(0)));
3642 break;
3643 }
3644
3645 case DataType::Type::kFloat64:
3646 locations->SetInAt(0, Location::RequiresFpuRegister());
3647 locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
3648 break;
3649
3650 default:
3651 LOG(FATAL) << "Unexpected type conversion from " << input_type
3652 << " to " << result_type;
3653 }
3654 break;
3655
3656 case DataType::Type::kFloat64:
3657 switch (input_type) {
3658 case DataType::Type::kBool:
3659 case DataType::Type::kUint8:
3660 case DataType::Type::kInt8:
3661 case DataType::Type::kUint16:
3662 case DataType::Type::kInt16:
3663 case DataType::Type::kInt32:
3664 locations->SetInAt(0, Location::RequiresRegister());
3665 locations->SetOut(Location::RequiresFpuRegister());
3666 break;
3667
3668 case DataType::Type::kInt64:
3669 locations->SetInAt(0, Location::RequiresRegister());
3670 locations->SetOut(Location::RequiresFpuRegister());
3671 locations->AddTemp(Location::RequiresFpuRegister());
3672 locations->AddTemp(Location::RequiresFpuRegister());
3673 break;
3674
3675 case DataType::Type::kFloat32:
3676 locations->SetInAt(0, Location::RequiresFpuRegister());
3677 locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
3678 break;
3679
3680 default:
3681 LOG(FATAL) << "Unexpected type conversion from " << input_type
3682 << " to " << result_type;
3683 }
3684 break;
3685
3686 default:
3687 LOG(FATAL) << "Unexpected type conversion from " << input_type
3688 << " to " << result_type;
3689 }
3690 }
3691
VisitTypeConversion(HTypeConversion * conversion)3692 void InstructionCodeGeneratorARMVIXL::VisitTypeConversion(HTypeConversion* conversion) {
3693 LocationSummary* locations = conversion->GetLocations();
3694 Location out = locations->Out();
3695 Location in = locations->InAt(0);
3696 DataType::Type result_type = conversion->GetResultType();
3697 DataType::Type input_type = conversion->GetInputType();
3698 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
3699 << input_type << " -> " << result_type;
3700 switch (result_type) {
3701 case DataType::Type::kUint8:
3702 switch (input_type) {
3703 case DataType::Type::kInt8:
3704 case DataType::Type::kUint16:
3705 case DataType::Type::kInt16:
3706 case DataType::Type::kInt32:
3707 __ Ubfx(OutputRegister(conversion), InputRegisterAt(conversion, 0), 0, 8);
3708 break;
3709 case DataType::Type::kInt64:
3710 __ Ubfx(OutputRegister(conversion), LowRegisterFrom(in), 0, 8);
3711 break;
3712
3713 default:
3714 LOG(FATAL) << "Unexpected type conversion from " << input_type
3715 << " to " << result_type;
3716 }
3717 break;
3718
3719 case DataType::Type::kInt8:
3720 switch (input_type) {
3721 case DataType::Type::kUint8:
3722 case DataType::Type::kUint16:
3723 case DataType::Type::kInt16:
3724 case DataType::Type::kInt32:
3725 __ Sbfx(OutputRegister(conversion), InputRegisterAt(conversion, 0), 0, 8);
3726 break;
3727 case DataType::Type::kInt64:
3728 __ Sbfx(OutputRegister(conversion), LowRegisterFrom(in), 0, 8);
3729 break;
3730
3731 default:
3732 LOG(FATAL) << "Unexpected type conversion from " << input_type
3733 << " to " << result_type;
3734 }
3735 break;
3736
3737 case DataType::Type::kUint16:
3738 switch (input_type) {
3739 case DataType::Type::kInt8:
3740 case DataType::Type::kInt16:
3741 case DataType::Type::kInt32:
3742 __ Ubfx(OutputRegister(conversion), InputRegisterAt(conversion, 0), 0, 16);
3743 break;
3744 case DataType::Type::kInt64:
3745 __ Ubfx(OutputRegister(conversion), LowRegisterFrom(in), 0, 16);
3746 break;
3747
3748 default:
3749 LOG(FATAL) << "Unexpected type conversion from " << input_type
3750 << " to " << result_type;
3751 }
3752 break;
3753
3754 case DataType::Type::kInt16:
3755 switch (input_type) {
3756 case DataType::Type::kUint16:
3757 case DataType::Type::kInt32:
3758 __ Sbfx(OutputRegister(conversion), InputRegisterAt(conversion, 0), 0, 16);
3759 break;
3760 case DataType::Type::kInt64:
3761 __ Sbfx(OutputRegister(conversion), LowRegisterFrom(in), 0, 16);
3762 break;
3763
3764 default:
3765 LOG(FATAL) << "Unexpected type conversion from " << input_type
3766 << " to " << result_type;
3767 }
3768 break;
3769
3770 case DataType::Type::kInt32:
3771 switch (input_type) {
3772 case DataType::Type::kInt64:
3773 DCHECK(out.IsRegister());
3774 if (in.IsRegisterPair()) {
3775 __ Mov(OutputRegister(conversion), LowRegisterFrom(in));
3776 } else if (in.IsDoubleStackSlot()) {
3777 GetAssembler()->LoadFromOffset(kLoadWord,
3778 OutputRegister(conversion),
3779 sp,
3780 in.GetStackIndex());
3781 } else {
3782 DCHECK(in.IsConstant());
3783 DCHECK(in.GetConstant()->IsLongConstant());
3784 int64_t value = in.GetConstant()->AsLongConstant()->GetValue();
3785 __ Mov(OutputRegister(conversion), static_cast<int32_t>(value));
3786 }
3787 break;
3788
3789 case DataType::Type::kFloat32: {
3790 vixl32::SRegister temp = LowSRegisterFrom(locations->GetTemp(0));
3791 __ Vcvt(S32, F32, temp, InputSRegisterAt(conversion, 0));
3792 __ Vmov(OutputRegister(conversion), temp);
3793 break;
3794 }
3795
3796 case DataType::Type::kFloat64: {
3797 vixl32::SRegister temp_s = LowSRegisterFrom(locations->GetTemp(0));
3798 __ Vcvt(S32, F64, temp_s, DRegisterFrom(in));
3799 __ Vmov(OutputRegister(conversion), temp_s);
3800 break;
3801 }
3802
3803 default:
3804 LOG(FATAL) << "Unexpected type conversion from " << input_type
3805 << " to " << result_type;
3806 }
3807 break;
3808
3809 case DataType::Type::kInt64:
3810 switch (input_type) {
3811 case DataType::Type::kBool:
3812 case DataType::Type::kUint8:
3813 case DataType::Type::kInt8:
3814 case DataType::Type::kUint16:
3815 case DataType::Type::kInt16:
3816 case DataType::Type::kInt32:
3817 DCHECK(out.IsRegisterPair());
3818 DCHECK(in.IsRegister());
3819 __ Mov(LowRegisterFrom(out), InputRegisterAt(conversion, 0));
3820 // Sign extension.
3821 __ Asr(HighRegisterFrom(out), LowRegisterFrom(out), 31);
3822 break;
3823
3824 case DataType::Type::kFloat32:
3825 codegen_->InvokeRuntime(kQuickF2l, conversion, conversion->GetDexPc());
3826 CheckEntrypointTypes<kQuickF2l, int64_t, float>();
3827 break;
3828
3829 case DataType::Type::kFloat64:
3830 codegen_->InvokeRuntime(kQuickD2l, conversion, conversion->GetDexPc());
3831 CheckEntrypointTypes<kQuickD2l, int64_t, double>();
3832 break;
3833
3834 default:
3835 LOG(FATAL) << "Unexpected type conversion from " << input_type
3836 << " to " << result_type;
3837 }
3838 break;
3839
3840 case DataType::Type::kFloat32:
3841 switch (input_type) {
3842 case DataType::Type::kBool:
3843 case DataType::Type::kUint8:
3844 case DataType::Type::kInt8:
3845 case DataType::Type::kUint16:
3846 case DataType::Type::kInt16:
3847 case DataType::Type::kInt32:
3848 __ Vmov(OutputSRegister(conversion), InputRegisterAt(conversion, 0));
3849 __ Vcvt(F32, S32, OutputSRegister(conversion), OutputSRegister(conversion));
3850 break;
3851
3852 case DataType::Type::kInt64:
3853 codegen_->InvokeRuntime(kQuickL2f, conversion, conversion->GetDexPc());
3854 CheckEntrypointTypes<kQuickL2f, float, int64_t>();
3855 break;
3856
3857 case DataType::Type::kFloat64:
3858 __ Vcvt(F32, F64, OutputSRegister(conversion), DRegisterFrom(in));
3859 break;
3860
3861 default:
3862 LOG(FATAL) << "Unexpected type conversion from " << input_type
3863 << " to " << result_type;
3864 }
3865 break;
3866
3867 case DataType::Type::kFloat64:
3868 switch (input_type) {
3869 case DataType::Type::kBool:
3870 case DataType::Type::kUint8:
3871 case DataType::Type::kInt8:
3872 case DataType::Type::kUint16:
3873 case DataType::Type::kInt16:
3874 case DataType::Type::kInt32:
3875 __ Vmov(LowSRegisterFrom(out), InputRegisterAt(conversion, 0));
3876 __ Vcvt(F64, S32, DRegisterFrom(out), LowSRegisterFrom(out));
3877 break;
3878
3879 case DataType::Type::kInt64: {
3880 vixl32::Register low = LowRegisterFrom(in);
3881 vixl32::Register high = HighRegisterFrom(in);
3882 vixl32::SRegister out_s = LowSRegisterFrom(out);
3883 vixl32::DRegister out_d = DRegisterFrom(out);
3884 vixl32::SRegister temp_s = LowSRegisterFrom(locations->GetTemp(0));
3885 vixl32::DRegister temp_d = DRegisterFrom(locations->GetTemp(0));
3886 vixl32::DRegister constant_d = DRegisterFrom(locations->GetTemp(1));
3887
3888 // temp_d = int-to-double(high)
3889 __ Vmov(temp_s, high);
3890 __ Vcvt(F64, S32, temp_d, temp_s);
3891 // constant_d = k2Pow32EncodingForDouble
3892 __ Vmov(constant_d, bit_cast<double, int64_t>(k2Pow32EncodingForDouble));
3893 // out_d = unsigned-to-double(low)
3894 __ Vmov(out_s, low);
3895 __ Vcvt(F64, U32, out_d, out_s);
3896 // out_d += temp_d * constant_d
3897 __ Vmla(F64, out_d, temp_d, constant_d);
3898 break;
3899 }
3900
3901 case DataType::Type::kFloat32:
3902 __ Vcvt(F64, F32, DRegisterFrom(out), InputSRegisterAt(conversion, 0));
3903 break;
3904
3905 default:
3906 LOG(FATAL) << "Unexpected type conversion from " << input_type
3907 << " to " << result_type;
3908 }
3909 break;
3910
3911 default:
3912 LOG(FATAL) << "Unexpected type conversion from " << input_type
3913 << " to " << result_type;
3914 }
3915 }
3916
VisitAdd(HAdd * add)3917 void LocationsBuilderARMVIXL::VisitAdd(HAdd* add) {
3918 LocationSummary* locations =
3919 new (GetGraph()->GetAllocator()) LocationSummary(add, LocationSummary::kNoCall);
3920 switch (add->GetResultType()) {
3921 case DataType::Type::kInt32: {
3922 locations->SetInAt(0, Location::RequiresRegister());
3923 locations->SetInAt(1, Location::RegisterOrConstant(add->InputAt(1)));
3924 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
3925 break;
3926 }
3927
3928 case DataType::Type::kInt64: {
3929 locations->SetInAt(0, Location::RequiresRegister());
3930 locations->SetInAt(1, ArmEncodableConstantOrRegister(add->InputAt(1), ADD));
3931 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
3932 break;
3933 }
3934
3935 case DataType::Type::kFloat32:
3936 case DataType::Type::kFloat64: {
3937 locations->SetInAt(0, Location::RequiresFpuRegister());
3938 locations->SetInAt(1, Location::RequiresFpuRegister());
3939 locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
3940 break;
3941 }
3942
3943 default:
3944 LOG(FATAL) << "Unexpected add type " << add->GetResultType();
3945 }
3946 }
3947
VisitAdd(HAdd * add)3948 void InstructionCodeGeneratorARMVIXL::VisitAdd(HAdd* add) {
3949 LocationSummary* locations = add->GetLocations();
3950 Location out = locations->Out();
3951 Location first = locations->InAt(0);
3952 Location second = locations->InAt(1);
3953
3954 switch (add->GetResultType()) {
3955 case DataType::Type::kInt32: {
3956 __ Add(OutputRegister(add), InputRegisterAt(add, 0), InputOperandAt(add, 1));
3957 }
3958 break;
3959
3960 case DataType::Type::kInt64: {
3961 if (second.IsConstant()) {
3962 uint64_t value = static_cast<uint64_t>(Int64FromConstant(second.GetConstant()));
3963 GenerateAddLongConst(out, first, value);
3964 } else {
3965 DCHECK(second.IsRegisterPair());
3966 __ Adds(LowRegisterFrom(out), LowRegisterFrom(first), LowRegisterFrom(second));
3967 __ Adc(HighRegisterFrom(out), HighRegisterFrom(first), HighRegisterFrom(second));
3968 }
3969 break;
3970 }
3971
3972 case DataType::Type::kFloat32:
3973 case DataType::Type::kFloat64:
3974 __ Vadd(OutputVRegister(add), InputVRegisterAt(add, 0), InputVRegisterAt(add, 1));
3975 break;
3976
3977 default:
3978 LOG(FATAL) << "Unexpected add type " << add->GetResultType();
3979 }
3980 }
3981
VisitSub(HSub * sub)3982 void LocationsBuilderARMVIXL::VisitSub(HSub* sub) {
3983 LocationSummary* locations =
3984 new (GetGraph()->GetAllocator()) LocationSummary(sub, LocationSummary::kNoCall);
3985 switch (sub->GetResultType()) {
3986 case DataType::Type::kInt32: {
3987 locations->SetInAt(0, Location::RequiresRegister());
3988 locations->SetInAt(1, Location::RegisterOrConstant(sub->InputAt(1)));
3989 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
3990 break;
3991 }
3992
3993 case DataType::Type::kInt64: {
3994 locations->SetInAt(0, Location::RequiresRegister());
3995 locations->SetInAt(1, ArmEncodableConstantOrRegister(sub->InputAt(1), SUB));
3996 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
3997 break;
3998 }
3999 case DataType::Type::kFloat32:
4000 case DataType::Type::kFloat64: {
4001 locations->SetInAt(0, Location::RequiresFpuRegister());
4002 locations->SetInAt(1, Location::RequiresFpuRegister());
4003 locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
4004 break;
4005 }
4006 default:
4007 LOG(FATAL) << "Unexpected sub type " << sub->GetResultType();
4008 }
4009 }
4010
VisitSub(HSub * sub)4011 void InstructionCodeGeneratorARMVIXL::VisitSub(HSub* sub) {
4012 LocationSummary* locations = sub->GetLocations();
4013 Location out = locations->Out();
4014 Location first = locations->InAt(0);
4015 Location second = locations->InAt(1);
4016 switch (sub->GetResultType()) {
4017 case DataType::Type::kInt32: {
4018 __ Sub(OutputRegister(sub), InputRegisterAt(sub, 0), InputOperandAt(sub, 1));
4019 break;
4020 }
4021
4022 case DataType::Type::kInt64: {
4023 if (second.IsConstant()) {
4024 uint64_t value = static_cast<uint64_t>(Int64FromConstant(second.GetConstant()));
4025 GenerateAddLongConst(out, first, -value);
4026 } else {
4027 DCHECK(second.IsRegisterPair());
4028 __ Subs(LowRegisterFrom(out), LowRegisterFrom(first), LowRegisterFrom(second));
4029 __ Sbc(HighRegisterFrom(out), HighRegisterFrom(first), HighRegisterFrom(second));
4030 }
4031 break;
4032 }
4033
4034 case DataType::Type::kFloat32:
4035 case DataType::Type::kFloat64:
4036 __ Vsub(OutputVRegister(sub), InputVRegisterAt(sub, 0), InputVRegisterAt(sub, 1));
4037 break;
4038
4039 default:
4040 LOG(FATAL) << "Unexpected sub type " << sub->GetResultType();
4041 }
4042 }
4043
VisitMul(HMul * mul)4044 void LocationsBuilderARMVIXL::VisitMul(HMul* mul) {
4045 LocationSummary* locations =
4046 new (GetGraph()->GetAllocator()) LocationSummary(mul, LocationSummary::kNoCall);
4047 switch (mul->GetResultType()) {
4048 case DataType::Type::kInt32:
4049 case DataType::Type::kInt64: {
4050 locations->SetInAt(0, Location::RequiresRegister());
4051 locations->SetInAt(1, Location::RequiresRegister());
4052 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
4053 break;
4054 }
4055
4056 case DataType::Type::kFloat32:
4057 case DataType::Type::kFloat64: {
4058 locations->SetInAt(0, Location::RequiresFpuRegister());
4059 locations->SetInAt(1, Location::RequiresFpuRegister());
4060 locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
4061 break;
4062 }
4063
4064 default:
4065 LOG(FATAL) << "Unexpected mul type " << mul->GetResultType();
4066 }
4067 }
4068
VisitMul(HMul * mul)4069 void InstructionCodeGeneratorARMVIXL::VisitMul(HMul* mul) {
4070 LocationSummary* locations = mul->GetLocations();
4071 Location out = locations->Out();
4072 Location first = locations->InAt(0);
4073 Location second = locations->InAt(1);
4074 switch (mul->GetResultType()) {
4075 case DataType::Type::kInt32: {
4076 __ Mul(OutputRegister(mul), InputRegisterAt(mul, 0), InputRegisterAt(mul, 1));
4077 break;
4078 }
4079 case DataType::Type::kInt64: {
4080 vixl32::Register out_hi = HighRegisterFrom(out);
4081 vixl32::Register out_lo = LowRegisterFrom(out);
4082 vixl32::Register in1_hi = HighRegisterFrom(first);
4083 vixl32::Register in1_lo = LowRegisterFrom(first);
4084 vixl32::Register in2_hi = HighRegisterFrom(second);
4085 vixl32::Register in2_lo = LowRegisterFrom(second);
4086
4087 // Extra checks to protect caused by the existence of R1_R2.
4088 // The algorithm is wrong if out.hi is either in1.lo or in2.lo:
4089 // (e.g. in1=r0_r1, in2=r2_r3 and out=r1_r2);
4090 DCHECK(!out_hi.Is(in1_lo));
4091 DCHECK(!out_hi.Is(in2_lo));
4092
4093 // input: in1 - 64 bits, in2 - 64 bits
4094 // output: out
4095 // formula: out.hi : out.lo = (in1.lo * in2.hi + in1.hi * in2.lo)* 2^32 + in1.lo * in2.lo
4096 // parts: out.hi = in1.lo * in2.hi + in1.hi * in2.lo + (in1.lo * in2.lo)[63:32]
4097 // parts: out.lo = (in1.lo * in2.lo)[31:0]
4098
4099 UseScratchRegisterScope temps(GetVIXLAssembler());
4100 vixl32::Register temp = temps.Acquire();
4101 // temp <- in1.lo * in2.hi
4102 __ Mul(temp, in1_lo, in2_hi);
4103 // out.hi <- in1.lo * in2.hi + in1.hi * in2.lo
4104 __ Mla(out_hi, in1_hi, in2_lo, temp);
4105 // out.lo <- (in1.lo * in2.lo)[31:0];
4106 __ Umull(out_lo, temp, in1_lo, in2_lo);
4107 // out.hi <- in2.hi * in1.lo + in2.lo * in1.hi + (in1.lo * in2.lo)[63:32]
4108 __ Add(out_hi, out_hi, temp);
4109 break;
4110 }
4111
4112 case DataType::Type::kFloat32:
4113 case DataType::Type::kFloat64:
4114 __ Vmul(OutputVRegister(mul), InputVRegisterAt(mul, 0), InputVRegisterAt(mul, 1));
4115 break;
4116
4117 default:
4118 LOG(FATAL) << "Unexpected mul type " << mul->GetResultType();
4119 }
4120 }
4121
DivRemOneOrMinusOne(HBinaryOperation * instruction)4122 void InstructionCodeGeneratorARMVIXL::DivRemOneOrMinusOne(HBinaryOperation* instruction) {
4123 DCHECK(instruction->IsDiv() || instruction->IsRem());
4124 DCHECK(instruction->GetResultType() == DataType::Type::kInt32);
4125
4126 Location second = instruction->GetLocations()->InAt(1);
4127 DCHECK(second.IsConstant());
4128
4129 vixl32::Register out = OutputRegister(instruction);
4130 vixl32::Register dividend = InputRegisterAt(instruction, 0);
4131 int32_t imm = Int32ConstantFrom(second);
4132 DCHECK(imm == 1 || imm == -1);
4133
4134 if (instruction->IsRem()) {
4135 __ Mov(out, 0);
4136 } else {
4137 if (imm == 1) {
4138 __ Mov(out, dividend);
4139 } else {
4140 __ Rsb(out, dividend, 0);
4141 }
4142 }
4143 }
4144
DivRemByPowerOfTwo(HBinaryOperation * instruction)4145 void InstructionCodeGeneratorARMVIXL::DivRemByPowerOfTwo(HBinaryOperation* instruction) {
4146 DCHECK(instruction->IsDiv() || instruction->IsRem());
4147 DCHECK(instruction->GetResultType() == DataType::Type::kInt32);
4148
4149 LocationSummary* locations = instruction->GetLocations();
4150 Location second = locations->InAt(1);
4151 DCHECK(second.IsConstant());
4152
4153 vixl32::Register out = OutputRegister(instruction);
4154 vixl32::Register dividend = InputRegisterAt(instruction, 0);
4155 vixl32::Register temp = RegisterFrom(locations->GetTemp(0));
4156 int32_t imm = Int32ConstantFrom(second);
4157 uint32_t abs_imm = static_cast<uint32_t>(AbsOrMin(imm));
4158 int ctz_imm = CTZ(abs_imm);
4159
4160 if (ctz_imm == 1) {
4161 __ Lsr(temp, dividend, 32 - ctz_imm);
4162 } else {
4163 __ Asr(temp, dividend, 31);
4164 __ Lsr(temp, temp, 32 - ctz_imm);
4165 }
4166 __ Add(out, temp, dividend);
4167
4168 if (instruction->IsDiv()) {
4169 __ Asr(out, out, ctz_imm);
4170 if (imm < 0) {
4171 __ Rsb(out, out, 0);
4172 }
4173 } else {
4174 __ Ubfx(out, out, 0, ctz_imm);
4175 __ Sub(out, out, temp);
4176 }
4177 }
4178
GenerateDivRemWithAnyConstant(HBinaryOperation * instruction)4179 void InstructionCodeGeneratorARMVIXL::GenerateDivRemWithAnyConstant(HBinaryOperation* instruction) {
4180 DCHECK(instruction->IsDiv() || instruction->IsRem());
4181 DCHECK(instruction->GetResultType() == DataType::Type::kInt32);
4182
4183 LocationSummary* locations = instruction->GetLocations();
4184 Location second = locations->InAt(1);
4185 DCHECK(second.IsConstant());
4186
4187 vixl32::Register out = OutputRegister(instruction);
4188 vixl32::Register dividend = InputRegisterAt(instruction, 0);
4189 vixl32::Register temp1 = RegisterFrom(locations->GetTemp(0));
4190 vixl32::Register temp2 = RegisterFrom(locations->GetTemp(1));
4191 int32_t imm = Int32ConstantFrom(second);
4192
4193 int64_t magic;
4194 int shift;
4195 CalculateMagicAndShiftForDivRem(imm, /* is_long= */ false, &magic, &shift);
4196
4197 // TODO(VIXL): Change the static cast to Operand::From() after VIXL is fixed.
4198 __ Mov(temp1, static_cast<int32_t>(magic));
4199 __ Smull(temp2, temp1, dividend, temp1);
4200
4201 if (imm > 0 && magic < 0) {
4202 __ Add(temp1, temp1, dividend);
4203 } else if (imm < 0 && magic > 0) {
4204 __ Sub(temp1, temp1, dividend);
4205 }
4206
4207 if (shift != 0) {
4208 __ Asr(temp1, temp1, shift);
4209 }
4210
4211 if (instruction->IsDiv()) {
4212 __ Sub(out, temp1, Operand(temp1, vixl32::Shift(ASR), 31));
4213 } else {
4214 __ Sub(temp1, temp1, Operand(temp1, vixl32::Shift(ASR), 31));
4215 // TODO: Strength reduction for mls.
4216 __ Mov(temp2, imm);
4217 __ Mls(out, temp1, temp2, dividend);
4218 }
4219 }
4220
GenerateDivRemConstantIntegral(HBinaryOperation * instruction)4221 void InstructionCodeGeneratorARMVIXL::GenerateDivRemConstantIntegral(
4222 HBinaryOperation* instruction) {
4223 DCHECK(instruction->IsDiv() || instruction->IsRem());
4224 DCHECK(instruction->GetResultType() == DataType::Type::kInt32);
4225
4226 Location second = instruction->GetLocations()->InAt(1);
4227 DCHECK(second.IsConstant());
4228
4229 int32_t imm = Int32ConstantFrom(second);
4230 if (imm == 0) {
4231 // Do not generate anything. DivZeroCheck would prevent any code to be executed.
4232 } else if (imm == 1 || imm == -1) {
4233 DivRemOneOrMinusOne(instruction);
4234 } else if (IsPowerOfTwo(AbsOrMin(imm))) {
4235 DivRemByPowerOfTwo(instruction);
4236 } else {
4237 DCHECK(imm <= -2 || imm >= 2);
4238 GenerateDivRemWithAnyConstant(instruction);
4239 }
4240 }
4241
VisitDiv(HDiv * div)4242 void LocationsBuilderARMVIXL::VisitDiv(HDiv* div) {
4243 LocationSummary::CallKind call_kind = LocationSummary::kNoCall;
4244 if (div->GetResultType() == DataType::Type::kInt64) {
4245 // pLdiv runtime call.
4246 call_kind = LocationSummary::kCallOnMainOnly;
4247 } else if (div->GetResultType() == DataType::Type::kInt32 && div->InputAt(1)->IsConstant()) {
4248 // sdiv will be replaced by other instruction sequence.
4249 } else if (div->GetResultType() == DataType::Type::kInt32 &&
4250 !codegen_->GetInstructionSetFeatures().HasDivideInstruction()) {
4251 // pIdivmod runtime call.
4252 call_kind = LocationSummary::kCallOnMainOnly;
4253 }
4254
4255 LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(div, call_kind);
4256
4257 switch (div->GetResultType()) {
4258 case DataType::Type::kInt32: {
4259 if (div->InputAt(1)->IsConstant()) {
4260 locations->SetInAt(0, Location::RequiresRegister());
4261 locations->SetInAt(1, Location::ConstantLocation(div->InputAt(1)->AsConstant()));
4262 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
4263 int32_t value = Int32ConstantFrom(div->InputAt(1));
4264 if (value == 1 || value == 0 || value == -1) {
4265 // No temp register required.
4266 } else {
4267 locations->AddTemp(Location::RequiresRegister());
4268 if (!IsPowerOfTwo(AbsOrMin(value))) {
4269 locations->AddTemp(Location::RequiresRegister());
4270 }
4271 }
4272 } else if (codegen_->GetInstructionSetFeatures().HasDivideInstruction()) {
4273 locations->SetInAt(0, Location::RequiresRegister());
4274 locations->SetInAt(1, Location::RequiresRegister());
4275 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
4276 } else {
4277 InvokeRuntimeCallingConventionARMVIXL calling_convention;
4278 locations->SetInAt(0, LocationFrom(calling_convention.GetRegisterAt(0)));
4279 locations->SetInAt(1, LocationFrom(calling_convention.GetRegisterAt(1)));
4280 // Note: divmod will compute both the quotient and the remainder as the pair R0 and R1, but
4281 // we only need the former.
4282 locations->SetOut(LocationFrom(r0));
4283 }
4284 break;
4285 }
4286 case DataType::Type::kInt64: {
4287 InvokeRuntimeCallingConventionARMVIXL calling_convention;
4288 locations->SetInAt(0, LocationFrom(
4289 calling_convention.GetRegisterAt(0), calling_convention.GetRegisterAt(1)));
4290 locations->SetInAt(1, LocationFrom(
4291 calling_convention.GetRegisterAt(2), calling_convention.GetRegisterAt(3)));
4292 locations->SetOut(LocationFrom(r0, r1));
4293 break;
4294 }
4295 case DataType::Type::kFloat32:
4296 case DataType::Type::kFloat64: {
4297 locations->SetInAt(0, Location::RequiresFpuRegister());
4298 locations->SetInAt(1, Location::RequiresFpuRegister());
4299 locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
4300 break;
4301 }
4302
4303 default:
4304 LOG(FATAL) << "Unexpected div type " << div->GetResultType();
4305 }
4306 }
4307
VisitDiv(HDiv * div)4308 void InstructionCodeGeneratorARMVIXL::VisitDiv(HDiv* div) {
4309 Location lhs = div->GetLocations()->InAt(0);
4310 Location rhs = div->GetLocations()->InAt(1);
4311
4312 switch (div->GetResultType()) {
4313 case DataType::Type::kInt32: {
4314 if (rhs.IsConstant()) {
4315 GenerateDivRemConstantIntegral(div);
4316 } else if (codegen_->GetInstructionSetFeatures().HasDivideInstruction()) {
4317 __ Sdiv(OutputRegister(div), InputRegisterAt(div, 0), InputRegisterAt(div, 1));
4318 } else {
4319 InvokeRuntimeCallingConventionARMVIXL calling_convention;
4320 DCHECK(calling_convention.GetRegisterAt(0).Is(RegisterFrom(lhs)));
4321 DCHECK(calling_convention.GetRegisterAt(1).Is(RegisterFrom(rhs)));
4322 DCHECK(r0.Is(OutputRegister(div)));
4323
4324 codegen_->InvokeRuntime(kQuickIdivmod, div, div->GetDexPc());
4325 CheckEntrypointTypes<kQuickIdivmod, int32_t, int32_t, int32_t>();
4326 }
4327 break;
4328 }
4329
4330 case DataType::Type::kInt64: {
4331 InvokeRuntimeCallingConventionARMVIXL calling_convention;
4332 DCHECK(calling_convention.GetRegisterAt(0).Is(LowRegisterFrom(lhs)));
4333 DCHECK(calling_convention.GetRegisterAt(1).Is(HighRegisterFrom(lhs)));
4334 DCHECK(calling_convention.GetRegisterAt(2).Is(LowRegisterFrom(rhs)));
4335 DCHECK(calling_convention.GetRegisterAt(3).Is(HighRegisterFrom(rhs)));
4336 DCHECK(LowRegisterFrom(div->GetLocations()->Out()).Is(r0));
4337 DCHECK(HighRegisterFrom(div->GetLocations()->Out()).Is(r1));
4338
4339 codegen_->InvokeRuntime(kQuickLdiv, div, div->GetDexPc());
4340 CheckEntrypointTypes<kQuickLdiv, int64_t, int64_t, int64_t>();
4341 break;
4342 }
4343
4344 case DataType::Type::kFloat32:
4345 case DataType::Type::kFloat64:
4346 __ Vdiv(OutputVRegister(div), InputVRegisterAt(div, 0), InputVRegisterAt(div, 1));
4347 break;
4348
4349 default:
4350 LOG(FATAL) << "Unexpected div type " << div->GetResultType();
4351 }
4352 }
4353
VisitRem(HRem * rem)4354 void LocationsBuilderARMVIXL::VisitRem(HRem* rem) {
4355 DataType::Type type = rem->GetResultType();
4356
4357 // Most remainders are implemented in the runtime.
4358 LocationSummary::CallKind call_kind = LocationSummary::kCallOnMainOnly;
4359 if (rem->GetResultType() == DataType::Type::kInt32 && rem->InputAt(1)->IsConstant()) {
4360 // sdiv will be replaced by other instruction sequence.
4361 call_kind = LocationSummary::kNoCall;
4362 } else if ((rem->GetResultType() == DataType::Type::kInt32)
4363 && codegen_->GetInstructionSetFeatures().HasDivideInstruction()) {
4364 // Have hardware divide instruction for int, do it with three instructions.
4365 call_kind = LocationSummary::kNoCall;
4366 }
4367
4368 LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(rem, call_kind);
4369
4370 switch (type) {
4371 case DataType::Type::kInt32: {
4372 if (rem->InputAt(1)->IsConstant()) {
4373 locations->SetInAt(0, Location::RequiresRegister());
4374 locations->SetInAt(1, Location::ConstantLocation(rem->InputAt(1)->AsConstant()));
4375 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
4376 int32_t value = Int32ConstantFrom(rem->InputAt(1));
4377 if (value == 1 || value == 0 || value == -1) {
4378 // No temp register required.
4379 } else {
4380 locations->AddTemp(Location::RequiresRegister());
4381 if (!IsPowerOfTwo(AbsOrMin(value))) {
4382 locations->AddTemp(Location::RequiresRegister());
4383 }
4384 }
4385 } else if (codegen_->GetInstructionSetFeatures().HasDivideInstruction()) {
4386 locations->SetInAt(0, Location::RequiresRegister());
4387 locations->SetInAt(1, Location::RequiresRegister());
4388 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
4389 locations->AddTemp(Location::RequiresRegister());
4390 } else {
4391 InvokeRuntimeCallingConventionARMVIXL calling_convention;
4392 locations->SetInAt(0, LocationFrom(calling_convention.GetRegisterAt(0)));
4393 locations->SetInAt(1, LocationFrom(calling_convention.GetRegisterAt(1)));
4394 // Note: divmod will compute both the quotient and the remainder as the pair R0 and R1, but
4395 // we only need the latter.
4396 locations->SetOut(LocationFrom(r1));
4397 }
4398 break;
4399 }
4400 case DataType::Type::kInt64: {
4401 InvokeRuntimeCallingConventionARMVIXL calling_convention;
4402 locations->SetInAt(0, LocationFrom(
4403 calling_convention.GetRegisterAt(0), calling_convention.GetRegisterAt(1)));
4404 locations->SetInAt(1, LocationFrom(
4405 calling_convention.GetRegisterAt(2), calling_convention.GetRegisterAt(3)));
4406 // The runtime helper puts the output in R2,R3.
4407 locations->SetOut(LocationFrom(r2, r3));
4408 break;
4409 }
4410 case DataType::Type::kFloat32: {
4411 InvokeRuntimeCallingConventionARMVIXL calling_convention;
4412 locations->SetInAt(0, LocationFrom(calling_convention.GetFpuRegisterAt(0)));
4413 locations->SetInAt(1, LocationFrom(calling_convention.GetFpuRegisterAt(1)));
4414 locations->SetOut(LocationFrom(s0));
4415 break;
4416 }
4417
4418 case DataType::Type::kFloat64: {
4419 InvokeRuntimeCallingConventionARMVIXL calling_convention;
4420 locations->SetInAt(0, LocationFrom(
4421 calling_convention.GetFpuRegisterAt(0), calling_convention.GetFpuRegisterAt(1)));
4422 locations->SetInAt(1, LocationFrom(
4423 calling_convention.GetFpuRegisterAt(2), calling_convention.GetFpuRegisterAt(3)));
4424 locations->SetOut(LocationFrom(s0, s1));
4425 break;
4426 }
4427
4428 default:
4429 LOG(FATAL) << "Unexpected rem type " << type;
4430 }
4431 }
4432
VisitRem(HRem * rem)4433 void InstructionCodeGeneratorARMVIXL::VisitRem(HRem* rem) {
4434 LocationSummary* locations = rem->GetLocations();
4435 Location second = locations->InAt(1);
4436
4437 DataType::Type type = rem->GetResultType();
4438 switch (type) {
4439 case DataType::Type::kInt32: {
4440 vixl32::Register reg1 = InputRegisterAt(rem, 0);
4441 vixl32::Register out_reg = OutputRegister(rem);
4442 if (second.IsConstant()) {
4443 GenerateDivRemConstantIntegral(rem);
4444 } else if (codegen_->GetInstructionSetFeatures().HasDivideInstruction()) {
4445 vixl32::Register reg2 = RegisterFrom(second);
4446 vixl32::Register temp = RegisterFrom(locations->GetTemp(0));
4447
4448 // temp = reg1 / reg2 (integer division)
4449 // dest = reg1 - temp * reg2
4450 __ Sdiv(temp, reg1, reg2);
4451 __ Mls(out_reg, temp, reg2, reg1);
4452 } else {
4453 InvokeRuntimeCallingConventionARMVIXL calling_convention;
4454 DCHECK(reg1.Is(calling_convention.GetRegisterAt(0)));
4455 DCHECK(RegisterFrom(second).Is(calling_convention.GetRegisterAt(1)));
4456 DCHECK(out_reg.Is(r1));
4457
4458 codegen_->InvokeRuntime(kQuickIdivmod, rem, rem->GetDexPc());
4459 CheckEntrypointTypes<kQuickIdivmod, int32_t, int32_t, int32_t>();
4460 }
4461 break;
4462 }
4463
4464 case DataType::Type::kInt64: {
4465 codegen_->InvokeRuntime(kQuickLmod, rem, rem->GetDexPc());
4466 CheckEntrypointTypes<kQuickLmod, int64_t, int64_t, int64_t>();
4467 break;
4468 }
4469
4470 case DataType::Type::kFloat32: {
4471 codegen_->InvokeRuntime(kQuickFmodf, rem, rem->GetDexPc());
4472 CheckEntrypointTypes<kQuickFmodf, float, float, float>();
4473 break;
4474 }
4475
4476 case DataType::Type::kFloat64: {
4477 codegen_->InvokeRuntime(kQuickFmod, rem, rem->GetDexPc());
4478 CheckEntrypointTypes<kQuickFmod, double, double, double>();
4479 break;
4480 }
4481
4482 default:
4483 LOG(FATAL) << "Unexpected rem type " << type;
4484 }
4485 }
4486
CreateMinMaxLocations(ArenaAllocator * allocator,HBinaryOperation * minmax)4487 static void CreateMinMaxLocations(ArenaAllocator* allocator, HBinaryOperation* minmax) {
4488 LocationSummary* locations = new (allocator) LocationSummary(minmax);
4489 switch (minmax->GetResultType()) {
4490 case DataType::Type::kInt32:
4491 locations->SetInAt(0, Location::RequiresRegister());
4492 locations->SetInAt(1, Location::RequiresRegister());
4493 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
4494 break;
4495 case DataType::Type::kInt64:
4496 locations->SetInAt(0, Location::RequiresRegister());
4497 locations->SetInAt(1, Location::RequiresRegister());
4498 locations->SetOut(Location::SameAsFirstInput());
4499 break;
4500 case DataType::Type::kFloat32:
4501 locations->SetInAt(0, Location::RequiresFpuRegister());
4502 locations->SetInAt(1, Location::RequiresFpuRegister());
4503 locations->SetOut(Location::SameAsFirstInput());
4504 locations->AddTemp(Location::RequiresRegister());
4505 break;
4506 case DataType::Type::kFloat64:
4507 locations->SetInAt(0, Location::RequiresFpuRegister());
4508 locations->SetInAt(1, Location::RequiresFpuRegister());
4509 locations->SetOut(Location::SameAsFirstInput());
4510 break;
4511 default:
4512 LOG(FATAL) << "Unexpected type for HMinMax " << minmax->GetResultType();
4513 }
4514 }
4515
GenerateMinMaxInt(LocationSummary * locations,bool is_min)4516 void InstructionCodeGeneratorARMVIXL::GenerateMinMaxInt(LocationSummary* locations, bool is_min) {
4517 Location op1_loc = locations->InAt(0);
4518 Location op2_loc = locations->InAt(1);
4519 Location out_loc = locations->Out();
4520
4521 vixl32::Register op1 = RegisterFrom(op1_loc);
4522 vixl32::Register op2 = RegisterFrom(op2_loc);
4523 vixl32::Register out = RegisterFrom(out_loc);
4524
4525 __ Cmp(op1, op2);
4526
4527 {
4528 ExactAssemblyScope aas(GetVIXLAssembler(),
4529 3 * kMaxInstructionSizeInBytes,
4530 CodeBufferCheckScope::kMaximumSize);
4531
4532 __ ite(is_min ? lt : gt);
4533 __ mov(is_min ? lt : gt, out, op1);
4534 __ mov(is_min ? ge : le, out, op2);
4535 }
4536 }
4537
GenerateMinMaxLong(LocationSummary * locations,bool is_min)4538 void InstructionCodeGeneratorARMVIXL::GenerateMinMaxLong(LocationSummary* locations, bool is_min) {
4539 Location op1_loc = locations->InAt(0);
4540 Location op2_loc = locations->InAt(1);
4541 Location out_loc = locations->Out();
4542
4543 // Optimization: don't generate any code if inputs are the same.
4544 if (op1_loc.Equals(op2_loc)) {
4545 DCHECK(out_loc.Equals(op1_loc)); // out_loc is set as SameAsFirstInput() in location builder.
4546 return;
4547 }
4548
4549 vixl32::Register op1_lo = LowRegisterFrom(op1_loc);
4550 vixl32::Register op1_hi = HighRegisterFrom(op1_loc);
4551 vixl32::Register op2_lo = LowRegisterFrom(op2_loc);
4552 vixl32::Register op2_hi = HighRegisterFrom(op2_loc);
4553 vixl32::Register out_lo = LowRegisterFrom(out_loc);
4554 vixl32::Register out_hi = HighRegisterFrom(out_loc);
4555 UseScratchRegisterScope temps(GetVIXLAssembler());
4556 const vixl32::Register temp = temps.Acquire();
4557
4558 DCHECK(op1_lo.Is(out_lo));
4559 DCHECK(op1_hi.Is(out_hi));
4560
4561 // Compare op1 >= op2, or op1 < op2.
4562 __ Cmp(out_lo, op2_lo);
4563 __ Sbcs(temp, out_hi, op2_hi);
4564
4565 // Now GE/LT condition code is correct for the long comparison.
4566 {
4567 vixl32::ConditionType cond = is_min ? ge : lt;
4568 ExactAssemblyScope it_scope(GetVIXLAssembler(),
4569 3 * kMaxInstructionSizeInBytes,
4570 CodeBufferCheckScope::kMaximumSize);
4571 __ itt(cond);
4572 __ mov(cond, out_lo, op2_lo);
4573 __ mov(cond, out_hi, op2_hi);
4574 }
4575 }
4576
GenerateMinMaxFloat(HInstruction * minmax,bool is_min)4577 void InstructionCodeGeneratorARMVIXL::GenerateMinMaxFloat(HInstruction* minmax, bool is_min) {
4578 LocationSummary* locations = minmax->GetLocations();
4579 Location op1_loc = locations->InAt(0);
4580 Location op2_loc = locations->InAt(1);
4581 Location out_loc = locations->Out();
4582
4583 // Optimization: don't generate any code if inputs are the same.
4584 if (op1_loc.Equals(op2_loc)) {
4585 DCHECK(out_loc.Equals(op1_loc)); // out_loc is set as SameAsFirstInput() in location builder.
4586 return;
4587 }
4588
4589 vixl32::SRegister op1 = SRegisterFrom(op1_loc);
4590 vixl32::SRegister op2 = SRegisterFrom(op2_loc);
4591 vixl32::SRegister out = SRegisterFrom(out_loc);
4592
4593 UseScratchRegisterScope temps(GetVIXLAssembler());
4594 const vixl32::Register temp1 = temps.Acquire();
4595 vixl32::Register temp2 = RegisterFrom(locations->GetTemp(0));
4596 vixl32::Label nan, done;
4597 vixl32::Label* final_label = codegen_->GetFinalLabel(minmax, &done);
4598
4599 DCHECK(op1.Is(out));
4600
4601 __ Vcmp(op1, op2);
4602 __ Vmrs(RegisterOrAPSR_nzcv(kPcCode), FPSCR);
4603 __ B(vs, &nan, /* is_far_target= */ false); // if un-ordered, go to NaN handling.
4604
4605 // op1 <> op2
4606 vixl32::ConditionType cond = is_min ? gt : lt;
4607 {
4608 ExactAssemblyScope it_scope(GetVIXLAssembler(),
4609 2 * kMaxInstructionSizeInBytes,
4610 CodeBufferCheckScope::kMaximumSize);
4611 __ it(cond);
4612 __ vmov(cond, F32, out, op2);
4613 }
4614 // for <>(not equal), we've done min/max calculation.
4615 __ B(ne, final_label, /* is_far_target= */ false);
4616
4617 // handle op1 == op2, max(+0.0,-0.0), min(+0.0,-0.0).
4618 __ Vmov(temp1, op1);
4619 __ Vmov(temp2, op2);
4620 if (is_min) {
4621 __ Orr(temp1, temp1, temp2);
4622 } else {
4623 __ And(temp1, temp1, temp2);
4624 }
4625 __ Vmov(out, temp1);
4626 __ B(final_label);
4627
4628 // handle NaN input.
4629 __ Bind(&nan);
4630 __ Movt(temp1, High16Bits(kNanFloat)); // 0x7FC0xxxx is a NaN.
4631 __ Vmov(out, temp1);
4632
4633 if (done.IsReferenced()) {
4634 __ Bind(&done);
4635 }
4636 }
4637
GenerateMinMaxDouble(HInstruction * minmax,bool is_min)4638 void InstructionCodeGeneratorARMVIXL::GenerateMinMaxDouble(HInstruction* minmax, bool is_min) {
4639 LocationSummary* locations = minmax->GetLocations();
4640 Location op1_loc = locations->InAt(0);
4641 Location op2_loc = locations->InAt(1);
4642 Location out_loc = locations->Out();
4643
4644 // Optimization: don't generate any code if inputs are the same.
4645 if (op1_loc.Equals(op2_loc)) {
4646 DCHECK(out_loc.Equals(op1_loc)); // out_loc is set as SameAsFirstInput() in.
4647 return;
4648 }
4649
4650 vixl32::DRegister op1 = DRegisterFrom(op1_loc);
4651 vixl32::DRegister op2 = DRegisterFrom(op2_loc);
4652 vixl32::DRegister out = DRegisterFrom(out_loc);
4653 vixl32::Label handle_nan_eq, done;
4654 vixl32::Label* final_label = codegen_->GetFinalLabel(minmax, &done);
4655
4656 DCHECK(op1.Is(out));
4657
4658 __ Vcmp(op1, op2);
4659 __ Vmrs(RegisterOrAPSR_nzcv(kPcCode), FPSCR);
4660 __ B(vs, &handle_nan_eq, /* is_far_target= */ false); // if un-ordered, go to NaN handling.
4661
4662 // op1 <> op2
4663 vixl32::ConditionType cond = is_min ? gt : lt;
4664 {
4665 ExactAssemblyScope it_scope(GetVIXLAssembler(),
4666 2 * kMaxInstructionSizeInBytes,
4667 CodeBufferCheckScope::kMaximumSize);
4668 __ it(cond);
4669 __ vmov(cond, F64, out, op2);
4670 }
4671 // for <>(not equal), we've done min/max calculation.
4672 __ B(ne, final_label, /* is_far_target= */ false);
4673
4674 // handle op1 == op2, max(+0.0,-0.0).
4675 if (!is_min) {
4676 __ Vand(F64, out, op1, op2);
4677 __ B(final_label);
4678 }
4679
4680 // handle op1 == op2, min(+0.0,-0.0), NaN input.
4681 __ Bind(&handle_nan_eq);
4682 __ Vorr(F64, out, op1, op2); // assemble op1/-0.0/NaN.
4683
4684 if (done.IsReferenced()) {
4685 __ Bind(&done);
4686 }
4687 }
4688
GenerateMinMax(HBinaryOperation * minmax,bool is_min)4689 void InstructionCodeGeneratorARMVIXL::GenerateMinMax(HBinaryOperation* minmax, bool is_min) {
4690 DataType::Type type = minmax->GetResultType();
4691 switch (type) {
4692 case DataType::Type::kInt32:
4693 GenerateMinMaxInt(minmax->GetLocations(), is_min);
4694 break;
4695 case DataType::Type::kInt64:
4696 GenerateMinMaxLong(minmax->GetLocations(), is_min);
4697 break;
4698 case DataType::Type::kFloat32:
4699 GenerateMinMaxFloat(minmax, is_min);
4700 break;
4701 case DataType::Type::kFloat64:
4702 GenerateMinMaxDouble(minmax, is_min);
4703 break;
4704 default:
4705 LOG(FATAL) << "Unexpected type for HMinMax " << type;
4706 }
4707 }
4708
VisitMin(HMin * min)4709 void LocationsBuilderARMVIXL::VisitMin(HMin* min) {
4710 CreateMinMaxLocations(GetGraph()->GetAllocator(), min);
4711 }
4712
VisitMin(HMin * min)4713 void InstructionCodeGeneratorARMVIXL::VisitMin(HMin* min) {
4714 GenerateMinMax(min, /*is_min*/ true);
4715 }
4716
VisitMax(HMax * max)4717 void LocationsBuilderARMVIXL::VisitMax(HMax* max) {
4718 CreateMinMaxLocations(GetGraph()->GetAllocator(), max);
4719 }
4720
VisitMax(HMax * max)4721 void InstructionCodeGeneratorARMVIXL::VisitMax(HMax* max) {
4722 GenerateMinMax(max, /*is_min*/ false);
4723 }
4724
VisitAbs(HAbs * abs)4725 void LocationsBuilderARMVIXL::VisitAbs(HAbs* abs) {
4726 LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(abs);
4727 switch (abs->GetResultType()) {
4728 case DataType::Type::kInt32:
4729 case DataType::Type::kInt64:
4730 locations->SetInAt(0, Location::RequiresRegister());
4731 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
4732 locations->AddTemp(Location::RequiresRegister());
4733 break;
4734 case DataType::Type::kFloat32:
4735 case DataType::Type::kFloat64:
4736 locations->SetInAt(0, Location::RequiresFpuRegister());
4737 locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
4738 break;
4739 default:
4740 LOG(FATAL) << "Unexpected type for abs operation " << abs->GetResultType();
4741 }
4742 }
4743
VisitAbs(HAbs * abs)4744 void InstructionCodeGeneratorARMVIXL::VisitAbs(HAbs* abs) {
4745 LocationSummary* locations = abs->GetLocations();
4746 switch (abs->GetResultType()) {
4747 case DataType::Type::kInt32: {
4748 vixl32::Register in_reg = RegisterFrom(locations->InAt(0));
4749 vixl32::Register out_reg = RegisterFrom(locations->Out());
4750 vixl32::Register mask = RegisterFrom(locations->GetTemp(0));
4751 __ Asr(mask, in_reg, 31);
4752 __ Add(out_reg, in_reg, mask);
4753 __ Eor(out_reg, out_reg, mask);
4754 break;
4755 }
4756 case DataType::Type::kInt64: {
4757 Location in = locations->InAt(0);
4758 vixl32::Register in_reg_lo = LowRegisterFrom(in);
4759 vixl32::Register in_reg_hi = HighRegisterFrom(in);
4760 Location output = locations->Out();
4761 vixl32::Register out_reg_lo = LowRegisterFrom(output);
4762 vixl32::Register out_reg_hi = HighRegisterFrom(output);
4763 DCHECK(!out_reg_lo.Is(in_reg_hi)) << "Diagonal overlap unexpected.";
4764 vixl32::Register mask = RegisterFrom(locations->GetTemp(0));
4765 __ Asr(mask, in_reg_hi, 31);
4766 __ Adds(out_reg_lo, in_reg_lo, mask);
4767 __ Adc(out_reg_hi, in_reg_hi, mask);
4768 __ Eor(out_reg_lo, out_reg_lo, mask);
4769 __ Eor(out_reg_hi, out_reg_hi, mask);
4770 break;
4771 }
4772 case DataType::Type::kFloat32:
4773 case DataType::Type::kFloat64:
4774 __ Vabs(OutputVRegister(abs), InputVRegisterAt(abs, 0));
4775 break;
4776 default:
4777 LOG(FATAL) << "Unexpected type for abs operation " << abs->GetResultType();
4778 }
4779 }
4780
VisitDivZeroCheck(HDivZeroCheck * instruction)4781 void LocationsBuilderARMVIXL::VisitDivZeroCheck(HDivZeroCheck* instruction) {
4782 LocationSummary* locations = codegen_->CreateThrowingSlowPathLocations(instruction);
4783 locations->SetInAt(0, Location::RegisterOrConstant(instruction->InputAt(0)));
4784 }
4785
VisitDivZeroCheck(HDivZeroCheck * instruction)4786 void InstructionCodeGeneratorARMVIXL::VisitDivZeroCheck(HDivZeroCheck* instruction) {
4787 DivZeroCheckSlowPathARMVIXL* slow_path =
4788 new (codegen_->GetScopedAllocator()) DivZeroCheckSlowPathARMVIXL(instruction);
4789 codegen_->AddSlowPath(slow_path);
4790
4791 LocationSummary* locations = instruction->GetLocations();
4792 Location value = locations->InAt(0);
4793
4794 switch (instruction->GetType()) {
4795 case DataType::Type::kBool:
4796 case DataType::Type::kUint8:
4797 case DataType::Type::kInt8:
4798 case DataType::Type::kUint16:
4799 case DataType::Type::kInt16:
4800 case DataType::Type::kInt32: {
4801 if (value.IsRegister()) {
4802 __ CompareAndBranchIfZero(InputRegisterAt(instruction, 0), slow_path->GetEntryLabel());
4803 } else {
4804 DCHECK(value.IsConstant()) << value;
4805 if (Int32ConstantFrom(value) == 0) {
4806 __ B(slow_path->GetEntryLabel());
4807 }
4808 }
4809 break;
4810 }
4811 case DataType::Type::kInt64: {
4812 if (value.IsRegisterPair()) {
4813 UseScratchRegisterScope temps(GetVIXLAssembler());
4814 vixl32::Register temp = temps.Acquire();
4815 __ Orrs(temp, LowRegisterFrom(value), HighRegisterFrom(value));
4816 __ B(eq, slow_path->GetEntryLabel());
4817 } else {
4818 DCHECK(value.IsConstant()) << value;
4819 if (Int64ConstantFrom(value) == 0) {
4820 __ B(slow_path->GetEntryLabel());
4821 }
4822 }
4823 break;
4824 }
4825 default:
4826 LOG(FATAL) << "Unexpected type for HDivZeroCheck " << instruction->GetType();
4827 }
4828 }
4829
HandleIntegerRotate(HRor * ror)4830 void InstructionCodeGeneratorARMVIXL::HandleIntegerRotate(HRor* ror) {
4831 LocationSummary* locations = ror->GetLocations();
4832 vixl32::Register in = InputRegisterAt(ror, 0);
4833 Location rhs = locations->InAt(1);
4834 vixl32::Register out = OutputRegister(ror);
4835
4836 if (rhs.IsConstant()) {
4837 // Arm32 and Thumb2 assemblers require a rotation on the interval [1,31],
4838 // so map all rotations to a +ve. equivalent in that range.
4839 // (e.g. left *or* right by -2 bits == 30 bits in the same direction.)
4840 uint32_t rot = CodeGenerator::GetInt32ValueOf(rhs.GetConstant()) & 0x1F;
4841 if (rot) {
4842 // Rotate, mapping left rotations to right equivalents if necessary.
4843 // (e.g. left by 2 bits == right by 30.)
4844 __ Ror(out, in, rot);
4845 } else if (!out.Is(in)) {
4846 __ Mov(out, in);
4847 }
4848 } else {
4849 __ Ror(out, in, RegisterFrom(rhs));
4850 }
4851 }
4852
4853 // Gain some speed by mapping all Long rotates onto equivalent pairs of Integer
4854 // rotates by swapping input regs (effectively rotating by the first 32-bits of
4855 // a larger rotation) or flipping direction (thus treating larger right/left
4856 // rotations as sub-word sized rotations in the other direction) as appropriate.
HandleLongRotate(HRor * ror)4857 void InstructionCodeGeneratorARMVIXL::HandleLongRotate(HRor* ror) {
4858 LocationSummary* locations = ror->GetLocations();
4859 vixl32::Register in_reg_lo = LowRegisterFrom(locations->InAt(0));
4860 vixl32::Register in_reg_hi = HighRegisterFrom(locations->InAt(0));
4861 Location rhs = locations->InAt(1);
4862 vixl32::Register out_reg_lo = LowRegisterFrom(locations->Out());
4863 vixl32::Register out_reg_hi = HighRegisterFrom(locations->Out());
4864
4865 if (rhs.IsConstant()) {
4866 uint64_t rot = CodeGenerator::GetInt64ValueOf(rhs.GetConstant());
4867 // Map all rotations to +ve. equivalents on the interval [0,63].
4868 rot &= kMaxLongShiftDistance;
4869 // For rotates over a word in size, 'pre-rotate' by 32-bits to keep rotate
4870 // logic below to a simple pair of binary orr.
4871 // (e.g. 34 bits == in_reg swap + 2 bits right.)
4872 if (rot >= kArmBitsPerWord) {
4873 rot -= kArmBitsPerWord;
4874 std::swap(in_reg_hi, in_reg_lo);
4875 }
4876 // Rotate, or mov to out for zero or word size rotations.
4877 if (rot != 0u) {
4878 __ Lsr(out_reg_hi, in_reg_hi, Operand::From(rot));
4879 __ Orr(out_reg_hi, out_reg_hi, Operand(in_reg_lo, ShiftType::LSL, kArmBitsPerWord - rot));
4880 __ Lsr(out_reg_lo, in_reg_lo, Operand::From(rot));
4881 __ Orr(out_reg_lo, out_reg_lo, Operand(in_reg_hi, ShiftType::LSL, kArmBitsPerWord - rot));
4882 } else {
4883 __ Mov(out_reg_lo, in_reg_lo);
4884 __ Mov(out_reg_hi, in_reg_hi);
4885 }
4886 } else {
4887 vixl32::Register shift_right = RegisterFrom(locations->GetTemp(0));
4888 vixl32::Register shift_left = RegisterFrom(locations->GetTemp(1));
4889 vixl32::Label end;
4890 vixl32::Label shift_by_32_plus_shift_right;
4891 vixl32::Label* final_label = codegen_->GetFinalLabel(ror, &end);
4892
4893 __ And(shift_right, RegisterFrom(rhs), 0x1F);
4894 __ Lsrs(shift_left, RegisterFrom(rhs), 6);
4895 __ Rsb(LeaveFlags, shift_left, shift_right, Operand::From(kArmBitsPerWord));
4896 __ B(cc, &shift_by_32_plus_shift_right, /* is_far_target= */ false);
4897
4898 // out_reg_hi = (reg_hi << shift_left) | (reg_lo >> shift_right).
4899 // out_reg_lo = (reg_lo << shift_left) | (reg_hi >> shift_right).
4900 __ Lsl(out_reg_hi, in_reg_hi, shift_left);
4901 __ Lsr(out_reg_lo, in_reg_lo, shift_right);
4902 __ Add(out_reg_hi, out_reg_hi, out_reg_lo);
4903 __ Lsl(out_reg_lo, in_reg_lo, shift_left);
4904 __ Lsr(shift_left, in_reg_hi, shift_right);
4905 __ Add(out_reg_lo, out_reg_lo, shift_left);
4906 __ B(final_label);
4907
4908 __ Bind(&shift_by_32_plus_shift_right); // Shift by 32+shift_right.
4909 // out_reg_hi = (reg_hi >> shift_right) | (reg_lo << shift_left).
4910 // out_reg_lo = (reg_lo >> shift_right) | (reg_hi << shift_left).
4911 __ Lsr(out_reg_hi, in_reg_hi, shift_right);
4912 __ Lsl(out_reg_lo, in_reg_lo, shift_left);
4913 __ Add(out_reg_hi, out_reg_hi, out_reg_lo);
4914 __ Lsr(out_reg_lo, in_reg_lo, shift_right);
4915 __ Lsl(shift_right, in_reg_hi, shift_left);
4916 __ Add(out_reg_lo, out_reg_lo, shift_right);
4917
4918 if (end.IsReferenced()) {
4919 __ Bind(&end);
4920 }
4921 }
4922 }
4923
VisitRor(HRor * ror)4924 void LocationsBuilderARMVIXL::VisitRor(HRor* ror) {
4925 LocationSummary* locations =
4926 new (GetGraph()->GetAllocator()) LocationSummary(ror, LocationSummary::kNoCall);
4927 switch (ror->GetResultType()) {
4928 case DataType::Type::kInt32: {
4929 locations->SetInAt(0, Location::RequiresRegister());
4930 locations->SetInAt(1, Location::RegisterOrConstant(ror->InputAt(1)));
4931 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
4932 break;
4933 }
4934 case DataType::Type::kInt64: {
4935 locations->SetInAt(0, Location::RequiresRegister());
4936 if (ror->InputAt(1)->IsConstant()) {
4937 locations->SetInAt(1, Location::ConstantLocation(ror->InputAt(1)->AsConstant()));
4938 } else {
4939 locations->SetInAt(1, Location::RequiresRegister());
4940 locations->AddTemp(Location::RequiresRegister());
4941 locations->AddTemp(Location::RequiresRegister());
4942 }
4943 locations->SetOut(Location::RequiresRegister(), Location::kOutputOverlap);
4944 break;
4945 }
4946 default:
4947 LOG(FATAL) << "Unexpected operation type " << ror->GetResultType();
4948 }
4949 }
4950
VisitRor(HRor * ror)4951 void InstructionCodeGeneratorARMVIXL::VisitRor(HRor* ror) {
4952 DataType::Type type = ror->GetResultType();
4953 switch (type) {
4954 case DataType::Type::kInt32: {
4955 HandleIntegerRotate(ror);
4956 break;
4957 }
4958 case DataType::Type::kInt64: {
4959 HandleLongRotate(ror);
4960 break;
4961 }
4962 default:
4963 LOG(FATAL) << "Unexpected operation type " << type;
4964 UNREACHABLE();
4965 }
4966 }
4967
HandleShift(HBinaryOperation * op)4968 void LocationsBuilderARMVIXL::HandleShift(HBinaryOperation* op) {
4969 DCHECK(op->IsShl() || op->IsShr() || op->IsUShr());
4970
4971 LocationSummary* locations =
4972 new (GetGraph()->GetAllocator()) LocationSummary(op, LocationSummary::kNoCall);
4973
4974 switch (op->GetResultType()) {
4975 case DataType::Type::kInt32: {
4976 locations->SetInAt(0, Location::RequiresRegister());
4977 if (op->InputAt(1)->IsConstant()) {
4978 locations->SetInAt(1, Location::ConstantLocation(op->InputAt(1)->AsConstant()));
4979 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
4980 } else {
4981 locations->SetInAt(1, Location::RequiresRegister());
4982 // Make the output overlap, as it will be used to hold the masked
4983 // second input.
4984 locations->SetOut(Location::RequiresRegister(), Location::kOutputOverlap);
4985 }
4986 break;
4987 }
4988 case DataType::Type::kInt64: {
4989 locations->SetInAt(0, Location::RequiresRegister());
4990 if (op->InputAt(1)->IsConstant()) {
4991 locations->SetInAt(1, Location::ConstantLocation(op->InputAt(1)->AsConstant()));
4992 // For simplicity, use kOutputOverlap even though we only require that low registers
4993 // don't clash with high registers which the register allocator currently guarantees.
4994 locations->SetOut(Location::RequiresRegister(), Location::kOutputOverlap);
4995 } else {
4996 locations->SetInAt(1, Location::RequiresRegister());
4997 locations->AddTemp(Location::RequiresRegister());
4998 locations->SetOut(Location::RequiresRegister(), Location::kOutputOverlap);
4999 }
5000 break;
5001 }
5002 default:
5003 LOG(FATAL) << "Unexpected operation type " << op->GetResultType();
5004 }
5005 }
5006
HandleShift(HBinaryOperation * op)5007 void InstructionCodeGeneratorARMVIXL::HandleShift(HBinaryOperation* op) {
5008 DCHECK(op->IsShl() || op->IsShr() || op->IsUShr());
5009
5010 LocationSummary* locations = op->GetLocations();
5011 Location out = locations->Out();
5012 Location first = locations->InAt(0);
5013 Location second = locations->InAt(1);
5014
5015 DataType::Type type = op->GetResultType();
5016 switch (type) {
5017 case DataType::Type::kInt32: {
5018 vixl32::Register out_reg = OutputRegister(op);
5019 vixl32::Register first_reg = InputRegisterAt(op, 0);
5020 if (second.IsRegister()) {
5021 vixl32::Register second_reg = RegisterFrom(second);
5022 // ARM doesn't mask the shift count so we need to do it ourselves.
5023 __ And(out_reg, second_reg, kMaxIntShiftDistance);
5024 if (op->IsShl()) {
5025 __ Lsl(out_reg, first_reg, out_reg);
5026 } else if (op->IsShr()) {
5027 __ Asr(out_reg, first_reg, out_reg);
5028 } else {
5029 __ Lsr(out_reg, first_reg, out_reg);
5030 }
5031 } else {
5032 int32_t cst = Int32ConstantFrom(second);
5033 uint32_t shift_value = cst & kMaxIntShiftDistance;
5034 if (shift_value == 0) { // ARM does not support shifting with 0 immediate.
5035 __ Mov(out_reg, first_reg);
5036 } else if (op->IsShl()) {
5037 __ Lsl(out_reg, first_reg, shift_value);
5038 } else if (op->IsShr()) {
5039 __ Asr(out_reg, first_reg, shift_value);
5040 } else {
5041 __ Lsr(out_reg, first_reg, shift_value);
5042 }
5043 }
5044 break;
5045 }
5046 case DataType::Type::kInt64: {
5047 vixl32::Register o_h = HighRegisterFrom(out);
5048 vixl32::Register o_l = LowRegisterFrom(out);
5049
5050 vixl32::Register high = HighRegisterFrom(first);
5051 vixl32::Register low = LowRegisterFrom(first);
5052
5053 if (second.IsRegister()) {
5054 vixl32::Register temp = RegisterFrom(locations->GetTemp(0));
5055
5056 vixl32::Register second_reg = RegisterFrom(second);
5057
5058 if (op->IsShl()) {
5059 __ And(o_l, second_reg, kMaxLongShiftDistance);
5060 // Shift the high part
5061 __ Lsl(o_h, high, o_l);
5062 // Shift the low part and `or` what overflew on the high part
5063 __ Rsb(temp, o_l, Operand::From(kArmBitsPerWord));
5064 __ Lsr(temp, low, temp);
5065 __ Orr(o_h, o_h, temp);
5066 // If the shift is > 32 bits, override the high part
5067 __ Subs(temp, o_l, Operand::From(kArmBitsPerWord));
5068 {
5069 ExactAssemblyScope guard(GetVIXLAssembler(),
5070 2 * vixl32::kMaxInstructionSizeInBytes,
5071 CodeBufferCheckScope::kMaximumSize);
5072 __ it(pl);
5073 __ lsl(pl, o_h, low, temp);
5074 }
5075 // Shift the low part
5076 __ Lsl(o_l, low, o_l);
5077 } else if (op->IsShr()) {
5078 __ And(o_h, second_reg, kMaxLongShiftDistance);
5079 // Shift the low part
5080 __ Lsr(o_l, low, o_h);
5081 // Shift the high part and `or` what underflew on the low part
5082 __ Rsb(temp, o_h, Operand::From(kArmBitsPerWord));
5083 __ Lsl(temp, high, temp);
5084 __ Orr(o_l, o_l, temp);
5085 // If the shift is > 32 bits, override the low part
5086 __ Subs(temp, o_h, Operand::From(kArmBitsPerWord));
5087 {
5088 ExactAssemblyScope guard(GetVIXLAssembler(),
5089 2 * vixl32::kMaxInstructionSizeInBytes,
5090 CodeBufferCheckScope::kMaximumSize);
5091 __ it(pl);
5092 __ asr(pl, o_l, high, temp);
5093 }
5094 // Shift the high part
5095 __ Asr(o_h, high, o_h);
5096 } else {
5097 __ And(o_h, second_reg, kMaxLongShiftDistance);
5098 // same as Shr except we use `Lsr`s and not `Asr`s
5099 __ Lsr(o_l, low, o_h);
5100 __ Rsb(temp, o_h, Operand::From(kArmBitsPerWord));
5101 __ Lsl(temp, high, temp);
5102 __ Orr(o_l, o_l, temp);
5103 __ Subs(temp, o_h, Operand::From(kArmBitsPerWord));
5104 {
5105 ExactAssemblyScope guard(GetVIXLAssembler(),
5106 2 * vixl32::kMaxInstructionSizeInBytes,
5107 CodeBufferCheckScope::kMaximumSize);
5108 __ it(pl);
5109 __ lsr(pl, o_l, high, temp);
5110 }
5111 __ Lsr(o_h, high, o_h);
5112 }
5113 } else {
5114 // Register allocator doesn't create partial overlap.
5115 DCHECK(!o_l.Is(high));
5116 DCHECK(!o_h.Is(low));
5117 int32_t cst = Int32ConstantFrom(second);
5118 uint32_t shift_value = cst & kMaxLongShiftDistance;
5119 if (shift_value > 32) {
5120 if (op->IsShl()) {
5121 __ Lsl(o_h, low, shift_value - 32);
5122 __ Mov(o_l, 0);
5123 } else if (op->IsShr()) {
5124 __ Asr(o_l, high, shift_value - 32);
5125 __ Asr(o_h, high, 31);
5126 } else {
5127 __ Lsr(o_l, high, shift_value - 32);
5128 __ Mov(o_h, 0);
5129 }
5130 } else if (shift_value == 32) {
5131 if (op->IsShl()) {
5132 __ Mov(o_h, low);
5133 __ Mov(o_l, 0);
5134 } else if (op->IsShr()) {
5135 __ Mov(o_l, high);
5136 __ Asr(o_h, high, 31);
5137 } else {
5138 __ Mov(o_l, high);
5139 __ Mov(o_h, 0);
5140 }
5141 } else if (shift_value == 1) {
5142 if (op->IsShl()) {
5143 __ Lsls(o_l, low, 1);
5144 __ Adc(o_h, high, high);
5145 } else if (op->IsShr()) {
5146 __ Asrs(o_h, high, 1);
5147 __ Rrx(o_l, low);
5148 } else {
5149 __ Lsrs(o_h, high, 1);
5150 __ Rrx(o_l, low);
5151 }
5152 } else if (shift_value == 0) {
5153 __ Mov(o_l, low);
5154 __ Mov(o_h, high);
5155 } else {
5156 DCHECK(0 < shift_value && shift_value < 32) << shift_value;
5157 if (op->IsShl()) {
5158 __ Lsl(o_h, high, shift_value);
5159 __ Orr(o_h, o_h, Operand(low, ShiftType::LSR, 32 - shift_value));
5160 __ Lsl(o_l, low, shift_value);
5161 } else if (op->IsShr()) {
5162 __ Lsr(o_l, low, shift_value);
5163 __ Orr(o_l, o_l, Operand(high, ShiftType::LSL, 32 - shift_value));
5164 __ Asr(o_h, high, shift_value);
5165 } else {
5166 __ Lsr(o_l, low, shift_value);
5167 __ Orr(o_l, o_l, Operand(high, ShiftType::LSL, 32 - shift_value));
5168 __ Lsr(o_h, high, shift_value);
5169 }
5170 }
5171 }
5172 break;
5173 }
5174 default:
5175 LOG(FATAL) << "Unexpected operation type " << type;
5176 UNREACHABLE();
5177 }
5178 }
5179
VisitShl(HShl * shl)5180 void LocationsBuilderARMVIXL::VisitShl(HShl* shl) {
5181 HandleShift(shl);
5182 }
5183
VisitShl(HShl * shl)5184 void InstructionCodeGeneratorARMVIXL::VisitShl(HShl* shl) {
5185 HandleShift(shl);
5186 }
5187
VisitShr(HShr * shr)5188 void LocationsBuilderARMVIXL::VisitShr(HShr* shr) {
5189 HandleShift(shr);
5190 }
5191
VisitShr(HShr * shr)5192 void InstructionCodeGeneratorARMVIXL::VisitShr(HShr* shr) {
5193 HandleShift(shr);
5194 }
5195
VisitUShr(HUShr * ushr)5196 void LocationsBuilderARMVIXL::VisitUShr(HUShr* ushr) {
5197 HandleShift(ushr);
5198 }
5199
VisitUShr(HUShr * ushr)5200 void InstructionCodeGeneratorARMVIXL::VisitUShr(HUShr* ushr) {
5201 HandleShift(ushr);
5202 }
5203
VisitNewInstance(HNewInstance * instruction)5204 void LocationsBuilderARMVIXL::VisitNewInstance(HNewInstance* instruction) {
5205 LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(
5206 instruction, LocationSummary::kCallOnMainOnly);
5207 InvokeRuntimeCallingConventionARMVIXL calling_convention;
5208 locations->SetInAt(0, LocationFrom(calling_convention.GetRegisterAt(0)));
5209 locations->SetOut(LocationFrom(r0));
5210 }
5211
VisitNewInstance(HNewInstance * instruction)5212 void InstructionCodeGeneratorARMVIXL::VisitNewInstance(HNewInstance* instruction) {
5213 codegen_->InvokeRuntime(instruction->GetEntrypoint(), instruction, instruction->GetDexPc());
5214 CheckEntrypointTypes<kQuickAllocObjectWithChecks, void*, mirror::Class*>();
5215 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 11);
5216 }
5217
VisitNewArray(HNewArray * instruction)5218 void LocationsBuilderARMVIXL::VisitNewArray(HNewArray* instruction) {
5219 LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(
5220 instruction, LocationSummary::kCallOnMainOnly);
5221 InvokeRuntimeCallingConventionARMVIXL calling_convention;
5222 locations->SetOut(LocationFrom(r0));
5223 locations->SetInAt(0, LocationFrom(calling_convention.GetRegisterAt(0)));
5224 locations->SetInAt(1, LocationFrom(calling_convention.GetRegisterAt(1)));
5225 }
5226
VisitNewArray(HNewArray * instruction)5227 void InstructionCodeGeneratorARMVIXL::VisitNewArray(HNewArray* instruction) {
5228 // Note: if heap poisoning is enabled, the entry point takes care of poisoning the reference.
5229 QuickEntrypointEnum entrypoint = CodeGenerator::GetArrayAllocationEntrypoint(instruction);
5230 codegen_->InvokeRuntime(entrypoint, instruction, instruction->GetDexPc());
5231 CheckEntrypointTypes<kQuickAllocArrayResolved, void*, mirror::Class*, int32_t>();
5232 DCHECK(!codegen_->IsLeafMethod());
5233 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 12);
5234 }
5235
VisitParameterValue(HParameterValue * instruction)5236 void LocationsBuilderARMVIXL::VisitParameterValue(HParameterValue* instruction) {
5237 LocationSummary* locations =
5238 new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
5239 Location location = parameter_visitor_.GetNextLocation(instruction->GetType());
5240 if (location.IsStackSlot()) {
5241 location = Location::StackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
5242 } else if (location.IsDoubleStackSlot()) {
5243 location = Location::DoubleStackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
5244 }
5245 locations->SetOut(location);
5246 }
5247
VisitParameterValue(HParameterValue * instruction ATTRIBUTE_UNUSED)5248 void InstructionCodeGeneratorARMVIXL::VisitParameterValue(
5249 HParameterValue* instruction ATTRIBUTE_UNUSED) {
5250 // Nothing to do, the parameter is already at its location.
5251 }
5252
VisitCurrentMethod(HCurrentMethod * instruction)5253 void LocationsBuilderARMVIXL::VisitCurrentMethod(HCurrentMethod* instruction) {
5254 LocationSummary* locations =
5255 new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
5256 locations->SetOut(LocationFrom(kMethodRegister));
5257 }
5258
VisitCurrentMethod(HCurrentMethod * instruction ATTRIBUTE_UNUSED)5259 void InstructionCodeGeneratorARMVIXL::VisitCurrentMethod(
5260 HCurrentMethod* instruction ATTRIBUTE_UNUSED) {
5261 // Nothing to do, the method is already at its location.
5262 }
5263
VisitNot(HNot * not_)5264 void LocationsBuilderARMVIXL::VisitNot(HNot* not_) {
5265 LocationSummary* locations =
5266 new (GetGraph()->GetAllocator()) LocationSummary(not_, LocationSummary::kNoCall);
5267 locations->SetInAt(0, Location::RequiresRegister());
5268 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
5269 }
5270
VisitNot(HNot * not_)5271 void InstructionCodeGeneratorARMVIXL::VisitNot(HNot* not_) {
5272 LocationSummary* locations = not_->GetLocations();
5273 Location out = locations->Out();
5274 Location in = locations->InAt(0);
5275 switch (not_->GetResultType()) {
5276 case DataType::Type::kInt32:
5277 __ Mvn(OutputRegister(not_), InputRegisterAt(not_, 0));
5278 break;
5279
5280 case DataType::Type::kInt64:
5281 __ Mvn(LowRegisterFrom(out), LowRegisterFrom(in));
5282 __ Mvn(HighRegisterFrom(out), HighRegisterFrom(in));
5283 break;
5284
5285 default:
5286 LOG(FATAL) << "Unimplemented type for not operation " << not_->GetResultType();
5287 }
5288 }
5289
VisitBooleanNot(HBooleanNot * bool_not)5290 void LocationsBuilderARMVIXL::VisitBooleanNot(HBooleanNot* bool_not) {
5291 LocationSummary* locations =
5292 new (GetGraph()->GetAllocator()) LocationSummary(bool_not, LocationSummary::kNoCall);
5293 locations->SetInAt(0, Location::RequiresRegister());
5294 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
5295 }
5296
VisitBooleanNot(HBooleanNot * bool_not)5297 void InstructionCodeGeneratorARMVIXL::VisitBooleanNot(HBooleanNot* bool_not) {
5298 __ Eor(OutputRegister(bool_not), InputRegister(bool_not), 1);
5299 }
5300
VisitCompare(HCompare * compare)5301 void LocationsBuilderARMVIXL::VisitCompare(HCompare* compare) {
5302 LocationSummary* locations =
5303 new (GetGraph()->GetAllocator()) LocationSummary(compare, LocationSummary::kNoCall);
5304 switch (compare->InputAt(0)->GetType()) {
5305 case DataType::Type::kBool:
5306 case DataType::Type::kUint8:
5307 case DataType::Type::kInt8:
5308 case DataType::Type::kUint16:
5309 case DataType::Type::kInt16:
5310 case DataType::Type::kInt32:
5311 case DataType::Type::kInt64: {
5312 locations->SetInAt(0, Location::RequiresRegister());
5313 locations->SetInAt(1, Location::RequiresRegister());
5314 // Output overlaps because it is written before doing the low comparison.
5315 locations->SetOut(Location::RequiresRegister(), Location::kOutputOverlap);
5316 break;
5317 }
5318 case DataType::Type::kFloat32:
5319 case DataType::Type::kFloat64: {
5320 locations->SetInAt(0, Location::RequiresFpuRegister());
5321 locations->SetInAt(1, ArithmeticZeroOrFpuRegister(compare->InputAt(1)));
5322 locations->SetOut(Location::RequiresRegister());
5323 break;
5324 }
5325 default:
5326 LOG(FATAL) << "Unexpected type for compare operation " << compare->InputAt(0)->GetType();
5327 }
5328 }
5329
VisitCompare(HCompare * compare)5330 void InstructionCodeGeneratorARMVIXL::VisitCompare(HCompare* compare) {
5331 LocationSummary* locations = compare->GetLocations();
5332 vixl32::Register out = OutputRegister(compare);
5333 Location left = locations->InAt(0);
5334 Location right = locations->InAt(1);
5335
5336 vixl32::Label less, greater, done;
5337 vixl32::Label* final_label = codegen_->GetFinalLabel(compare, &done);
5338 DataType::Type type = compare->InputAt(0)->GetType();
5339 vixl32::Condition less_cond = vixl32::Condition::None();
5340 switch (type) {
5341 case DataType::Type::kBool:
5342 case DataType::Type::kUint8:
5343 case DataType::Type::kInt8:
5344 case DataType::Type::kUint16:
5345 case DataType::Type::kInt16:
5346 case DataType::Type::kInt32: {
5347 // Emit move to `out` before the `Cmp`, as `Mov` might affect the status flags.
5348 __ Mov(out, 0);
5349 __ Cmp(RegisterFrom(left), RegisterFrom(right)); // Signed compare.
5350 less_cond = lt;
5351 break;
5352 }
5353 case DataType::Type::kInt64: {
5354 __ Cmp(HighRegisterFrom(left), HighRegisterFrom(right)); // Signed compare.
5355 __ B(lt, &less, /* is_far_target= */ false);
5356 __ B(gt, &greater, /* is_far_target= */ false);
5357 // Emit move to `out` before the last `Cmp`, as `Mov` might affect the status flags.
5358 __ Mov(out, 0);
5359 __ Cmp(LowRegisterFrom(left), LowRegisterFrom(right)); // Unsigned compare.
5360 less_cond = lo;
5361 break;
5362 }
5363 case DataType::Type::kFloat32:
5364 case DataType::Type::kFloat64: {
5365 __ Mov(out, 0);
5366 GenerateVcmp(compare, codegen_);
5367 // To branch on the FP compare result we transfer FPSCR to APSR (encoded as PC in VMRS).
5368 __ Vmrs(RegisterOrAPSR_nzcv(kPcCode), FPSCR);
5369 less_cond = ARMFPCondition(kCondLT, compare->IsGtBias());
5370 break;
5371 }
5372 default:
5373 LOG(FATAL) << "Unexpected compare type " << type;
5374 UNREACHABLE();
5375 }
5376
5377 __ B(eq, final_label, /* is_far_target= */ false);
5378 __ B(less_cond, &less, /* is_far_target= */ false);
5379
5380 __ Bind(&greater);
5381 __ Mov(out, 1);
5382 __ B(final_label);
5383
5384 __ Bind(&less);
5385 __ Mov(out, -1);
5386
5387 if (done.IsReferenced()) {
5388 __ Bind(&done);
5389 }
5390 }
5391
VisitPhi(HPhi * instruction)5392 void LocationsBuilderARMVIXL::VisitPhi(HPhi* instruction) {
5393 LocationSummary* locations =
5394 new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
5395 for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
5396 locations->SetInAt(i, Location::Any());
5397 }
5398 locations->SetOut(Location::Any());
5399 }
5400
VisitPhi(HPhi * instruction ATTRIBUTE_UNUSED)5401 void InstructionCodeGeneratorARMVIXL::VisitPhi(HPhi* instruction ATTRIBUTE_UNUSED) {
5402 LOG(FATAL) << "Unreachable";
5403 }
5404
GenerateMemoryBarrier(MemBarrierKind kind)5405 void CodeGeneratorARMVIXL::GenerateMemoryBarrier(MemBarrierKind kind) {
5406 // TODO (ported from quick): revisit ARM barrier kinds.
5407 DmbOptions flavor = DmbOptions::ISH; // Quiet C++ warnings.
5408 switch (kind) {
5409 case MemBarrierKind::kAnyStore:
5410 case MemBarrierKind::kLoadAny:
5411 case MemBarrierKind::kAnyAny: {
5412 flavor = DmbOptions::ISH;
5413 break;
5414 }
5415 case MemBarrierKind::kStoreStore: {
5416 flavor = DmbOptions::ISHST;
5417 break;
5418 }
5419 default:
5420 LOG(FATAL) << "Unexpected memory barrier " << kind;
5421 }
5422 __ Dmb(flavor);
5423 }
5424
GenerateWideAtomicLoad(vixl32::Register addr,uint32_t offset,vixl32::Register out_lo,vixl32::Register out_hi)5425 void InstructionCodeGeneratorARMVIXL::GenerateWideAtomicLoad(vixl32::Register addr,
5426 uint32_t offset,
5427 vixl32::Register out_lo,
5428 vixl32::Register out_hi) {
5429 UseScratchRegisterScope temps(GetVIXLAssembler());
5430 if (offset != 0) {
5431 vixl32::Register temp = temps.Acquire();
5432 __ Add(temp, addr, offset);
5433 addr = temp;
5434 }
5435 __ Ldrexd(out_lo, out_hi, MemOperand(addr));
5436 }
5437
GenerateWideAtomicStore(vixl32::Register addr,uint32_t offset,vixl32::Register value_lo,vixl32::Register value_hi,vixl32::Register temp1,vixl32::Register temp2,HInstruction * instruction)5438 void InstructionCodeGeneratorARMVIXL::GenerateWideAtomicStore(vixl32::Register addr,
5439 uint32_t offset,
5440 vixl32::Register value_lo,
5441 vixl32::Register value_hi,
5442 vixl32::Register temp1,
5443 vixl32::Register temp2,
5444 HInstruction* instruction) {
5445 UseScratchRegisterScope temps(GetVIXLAssembler());
5446 vixl32::Label fail;
5447 if (offset != 0) {
5448 vixl32::Register temp = temps.Acquire();
5449 __ Add(temp, addr, offset);
5450 addr = temp;
5451 }
5452 __ Bind(&fail);
5453 {
5454 // Ensure the pc position is recorded immediately after the `ldrexd` instruction.
5455 ExactAssemblyScope aas(GetVIXLAssembler(),
5456 vixl32::kMaxInstructionSizeInBytes,
5457 CodeBufferCheckScope::kMaximumSize);
5458 // We need a load followed by store. (The address used in a STREX instruction must
5459 // be the same as the address in the most recently executed LDREX instruction.)
5460 __ ldrexd(temp1, temp2, MemOperand(addr));
5461 codegen_->MaybeRecordImplicitNullCheck(instruction);
5462 }
5463 __ Strexd(temp1, value_lo, value_hi, MemOperand(addr));
5464 __ CompareAndBranchIfNonZero(temp1, &fail);
5465 }
5466
HandleFieldSet(HInstruction * instruction,const FieldInfo & field_info)5467 void LocationsBuilderARMVIXL::HandleFieldSet(
5468 HInstruction* instruction, const FieldInfo& field_info) {
5469 DCHECK(instruction->IsInstanceFieldSet() || instruction->IsStaticFieldSet());
5470
5471 LocationSummary* locations =
5472 new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
5473 locations->SetInAt(0, Location::RequiresRegister());
5474
5475 DataType::Type field_type = field_info.GetFieldType();
5476 if (DataType::IsFloatingPointType(field_type)) {
5477 locations->SetInAt(1, Location::RequiresFpuRegister());
5478 } else {
5479 locations->SetInAt(1, Location::RequiresRegister());
5480 }
5481
5482 bool is_wide = field_type == DataType::Type::kInt64 || field_type == DataType::Type::kFloat64;
5483 bool generate_volatile = field_info.IsVolatile()
5484 && is_wide
5485 && !codegen_->GetInstructionSetFeatures().HasAtomicLdrdAndStrd();
5486 bool needs_write_barrier =
5487 CodeGenerator::StoreNeedsWriteBarrier(field_type, instruction->InputAt(1));
5488 // Temporary registers for the write barrier.
5489 // TODO: consider renaming StoreNeedsWriteBarrier to StoreNeedsGCMark.
5490 if (needs_write_barrier) {
5491 locations->AddTemp(Location::RequiresRegister()); // Possibly used for reference poisoning too.
5492 locations->AddTemp(Location::RequiresRegister());
5493 } else if (generate_volatile) {
5494 // ARM encoding have some additional constraints for ldrexd/strexd:
5495 // - registers need to be consecutive
5496 // - the first register should be even but not R14.
5497 // We don't test for ARM yet, and the assertion makes sure that we
5498 // revisit this if we ever enable ARM encoding.
5499 DCHECK_EQ(InstructionSet::kThumb2, codegen_->GetInstructionSet());
5500
5501 locations->AddTemp(Location::RequiresRegister());
5502 locations->AddTemp(Location::RequiresRegister());
5503 if (field_type == DataType::Type::kFloat64) {
5504 // For doubles we need two more registers to copy the value.
5505 locations->AddTemp(LocationFrom(r2));
5506 locations->AddTemp(LocationFrom(r3));
5507 }
5508 }
5509 }
5510
HandleFieldSet(HInstruction * instruction,const FieldInfo & field_info,bool value_can_be_null)5511 void InstructionCodeGeneratorARMVIXL::HandleFieldSet(HInstruction* instruction,
5512 const FieldInfo& field_info,
5513 bool value_can_be_null) {
5514 DCHECK(instruction->IsInstanceFieldSet() || instruction->IsStaticFieldSet());
5515
5516 LocationSummary* locations = instruction->GetLocations();
5517 vixl32::Register base = InputRegisterAt(instruction, 0);
5518 Location value = locations->InAt(1);
5519
5520 bool is_volatile = field_info.IsVolatile();
5521 bool atomic_ldrd_strd = codegen_->GetInstructionSetFeatures().HasAtomicLdrdAndStrd();
5522 DataType::Type field_type = field_info.GetFieldType();
5523 uint32_t offset = field_info.GetFieldOffset().Uint32Value();
5524 bool needs_write_barrier =
5525 CodeGenerator::StoreNeedsWriteBarrier(field_type, instruction->InputAt(1));
5526
5527 if (is_volatile) {
5528 codegen_->GenerateMemoryBarrier(MemBarrierKind::kAnyStore);
5529 }
5530
5531 switch (field_type) {
5532 case DataType::Type::kBool:
5533 case DataType::Type::kUint8:
5534 case DataType::Type::kInt8:
5535 case DataType::Type::kUint16:
5536 case DataType::Type::kInt16:
5537 case DataType::Type::kInt32: {
5538 // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
5539 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
5540 StoreOperandType operand_type = GetStoreOperandType(field_type);
5541 GetAssembler()->StoreToOffset(operand_type, RegisterFrom(value), base, offset);
5542 codegen_->MaybeRecordImplicitNullCheck(instruction);
5543 break;
5544 }
5545
5546 case DataType::Type::kReference: {
5547 vixl32::Register value_reg = RegisterFrom(value);
5548 if (kPoisonHeapReferences && needs_write_barrier) {
5549 // Note that in the case where `value` is a null reference,
5550 // we do not enter this block, as a null reference does not
5551 // need poisoning.
5552 DCHECK_EQ(field_type, DataType::Type::kReference);
5553 value_reg = RegisterFrom(locations->GetTemp(0));
5554 __ Mov(value_reg, RegisterFrom(value));
5555 GetAssembler()->PoisonHeapReference(value_reg);
5556 }
5557 // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
5558 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
5559 GetAssembler()->StoreToOffset(kStoreWord, value_reg, base, offset);
5560 codegen_->MaybeRecordImplicitNullCheck(instruction);
5561 break;
5562 }
5563
5564 case DataType::Type::kInt64: {
5565 if (is_volatile && !atomic_ldrd_strd) {
5566 GenerateWideAtomicStore(base,
5567 offset,
5568 LowRegisterFrom(value),
5569 HighRegisterFrom(value),
5570 RegisterFrom(locations->GetTemp(0)),
5571 RegisterFrom(locations->GetTemp(1)),
5572 instruction);
5573 } else {
5574 // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
5575 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
5576 GetAssembler()->StoreToOffset(kStoreWordPair, LowRegisterFrom(value), base, offset);
5577 codegen_->MaybeRecordImplicitNullCheck(instruction);
5578 }
5579 break;
5580 }
5581
5582 case DataType::Type::kFloat32: {
5583 // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
5584 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
5585 GetAssembler()->StoreSToOffset(SRegisterFrom(value), base, offset);
5586 codegen_->MaybeRecordImplicitNullCheck(instruction);
5587 break;
5588 }
5589
5590 case DataType::Type::kFloat64: {
5591 vixl32::DRegister value_reg = DRegisterFrom(value);
5592 if (is_volatile && !atomic_ldrd_strd) {
5593 vixl32::Register value_reg_lo = RegisterFrom(locations->GetTemp(0));
5594 vixl32::Register value_reg_hi = RegisterFrom(locations->GetTemp(1));
5595
5596 __ Vmov(value_reg_lo, value_reg_hi, value_reg);
5597
5598 GenerateWideAtomicStore(base,
5599 offset,
5600 value_reg_lo,
5601 value_reg_hi,
5602 RegisterFrom(locations->GetTemp(2)),
5603 RegisterFrom(locations->GetTemp(3)),
5604 instruction);
5605 } else {
5606 // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
5607 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
5608 GetAssembler()->StoreDToOffset(value_reg, base, offset);
5609 codegen_->MaybeRecordImplicitNullCheck(instruction);
5610 }
5611 break;
5612 }
5613
5614 case DataType::Type::kUint32:
5615 case DataType::Type::kUint64:
5616 case DataType::Type::kVoid:
5617 LOG(FATAL) << "Unreachable type " << field_type;
5618 UNREACHABLE();
5619 }
5620
5621 if (CodeGenerator::StoreNeedsWriteBarrier(field_type, instruction->InputAt(1))) {
5622 vixl32::Register temp = RegisterFrom(locations->GetTemp(0));
5623 vixl32::Register card = RegisterFrom(locations->GetTemp(1));
5624 codegen_->MarkGCCard(temp, card, base, RegisterFrom(value), value_can_be_null);
5625 }
5626
5627 if (is_volatile) {
5628 codegen_->GenerateMemoryBarrier(MemBarrierKind::kAnyAny);
5629 }
5630 }
5631
HandleFieldGet(HInstruction * instruction,const FieldInfo & field_info)5632 void LocationsBuilderARMVIXL::HandleFieldGet(HInstruction* instruction,
5633 const FieldInfo& field_info) {
5634 DCHECK(instruction->IsInstanceFieldGet() || instruction->IsStaticFieldGet());
5635
5636 bool object_field_get_with_read_barrier =
5637 kEmitCompilerReadBarrier && (field_info.GetFieldType() == DataType::Type::kReference);
5638 LocationSummary* locations =
5639 new (GetGraph()->GetAllocator()) LocationSummary(instruction,
5640 object_field_get_with_read_barrier
5641 ? LocationSummary::kCallOnSlowPath
5642 : LocationSummary::kNoCall);
5643 if (object_field_get_with_read_barrier && kUseBakerReadBarrier) {
5644 locations->SetCustomSlowPathCallerSaves(RegisterSet::Empty()); // No caller-save registers.
5645 }
5646 locations->SetInAt(0, Location::RequiresRegister());
5647
5648 bool volatile_for_double = field_info.IsVolatile()
5649 && (field_info.GetFieldType() == DataType::Type::kFloat64)
5650 && !codegen_->GetInstructionSetFeatures().HasAtomicLdrdAndStrd();
5651 // The output overlaps in case of volatile long: we don't want the
5652 // code generated by GenerateWideAtomicLoad to overwrite the
5653 // object's location. Likewise, in the case of an object field get
5654 // with read barriers enabled, we do not want the load to overwrite
5655 // the object's location, as we need it to emit the read barrier.
5656 bool overlap =
5657 (field_info.IsVolatile() && (field_info.GetFieldType() == DataType::Type::kInt64)) ||
5658 object_field_get_with_read_barrier;
5659
5660 if (DataType::IsFloatingPointType(instruction->GetType())) {
5661 locations->SetOut(Location::RequiresFpuRegister());
5662 } else {
5663 locations->SetOut(Location::RequiresRegister(),
5664 (overlap ? Location::kOutputOverlap : Location::kNoOutputOverlap));
5665 }
5666 if (volatile_for_double) {
5667 // ARM encoding have some additional constraints for ldrexd/strexd:
5668 // - registers need to be consecutive
5669 // - the first register should be even but not R14.
5670 // We don't test for ARM yet, and the assertion makes sure that we
5671 // revisit this if we ever enable ARM encoding.
5672 DCHECK_EQ(InstructionSet::kThumb2, codegen_->GetInstructionSet());
5673 locations->AddTemp(Location::RequiresRegister());
5674 locations->AddTemp(Location::RequiresRegister());
5675 } else if (object_field_get_with_read_barrier && kUseBakerReadBarrier) {
5676 // We need a temporary register for the read barrier load in
5677 // CodeGeneratorARMVIXL::GenerateFieldLoadWithBakerReadBarrier()
5678 // only if the offset is too big.
5679 if (field_info.GetFieldOffset().Uint32Value() >= kReferenceLoadMinFarOffset) {
5680 locations->AddTemp(Location::RequiresRegister());
5681 }
5682 }
5683 }
5684
ArithmeticZeroOrFpuRegister(HInstruction * input)5685 Location LocationsBuilderARMVIXL::ArithmeticZeroOrFpuRegister(HInstruction* input) {
5686 DCHECK(DataType::IsFloatingPointType(input->GetType())) << input->GetType();
5687 if ((input->IsFloatConstant() && (input->AsFloatConstant()->IsArithmeticZero())) ||
5688 (input->IsDoubleConstant() && (input->AsDoubleConstant()->IsArithmeticZero()))) {
5689 return Location::ConstantLocation(input->AsConstant());
5690 } else {
5691 return Location::RequiresFpuRegister();
5692 }
5693 }
5694
ArmEncodableConstantOrRegister(HInstruction * constant,Opcode opcode)5695 Location LocationsBuilderARMVIXL::ArmEncodableConstantOrRegister(HInstruction* constant,
5696 Opcode opcode) {
5697 DCHECK(!DataType::IsFloatingPointType(constant->GetType()));
5698 if (constant->IsConstant() &&
5699 CanEncodeConstantAsImmediate(constant->AsConstant(), opcode)) {
5700 return Location::ConstantLocation(constant->AsConstant());
5701 }
5702 return Location::RequiresRegister();
5703 }
5704
CanEncode32BitConstantAsImmediate(CodeGeneratorARMVIXL * codegen,uint32_t value,Opcode opcode,vixl32::FlagsUpdate flags_update=vixl32::FlagsUpdate::DontCare)5705 static bool CanEncode32BitConstantAsImmediate(
5706 CodeGeneratorARMVIXL* codegen,
5707 uint32_t value,
5708 Opcode opcode,
5709 vixl32::FlagsUpdate flags_update = vixl32::FlagsUpdate::DontCare) {
5710 ArmVIXLAssembler* assembler = codegen->GetAssembler();
5711 if (assembler->ShifterOperandCanHold(opcode, value, flags_update)) {
5712 return true;
5713 }
5714 Opcode neg_opcode = kNoOperand;
5715 uint32_t neg_value = 0;
5716 switch (opcode) {
5717 case AND: neg_opcode = BIC; neg_value = ~value; break;
5718 case ORR: neg_opcode = ORN; neg_value = ~value; break;
5719 case ADD: neg_opcode = SUB; neg_value = -value; break;
5720 case ADC: neg_opcode = SBC; neg_value = ~value; break;
5721 case SUB: neg_opcode = ADD; neg_value = -value; break;
5722 case SBC: neg_opcode = ADC; neg_value = ~value; break;
5723 case MOV: neg_opcode = MVN; neg_value = ~value; break;
5724 default:
5725 return false;
5726 }
5727
5728 if (assembler->ShifterOperandCanHold(neg_opcode, neg_value, flags_update)) {
5729 return true;
5730 }
5731
5732 return opcode == AND && IsPowerOfTwo(value + 1);
5733 }
5734
CanEncodeConstantAsImmediate(HConstant * input_cst,Opcode opcode)5735 bool LocationsBuilderARMVIXL::CanEncodeConstantAsImmediate(HConstant* input_cst, Opcode opcode) {
5736 uint64_t value = static_cast<uint64_t>(Int64FromConstant(input_cst));
5737 if (DataType::Is64BitType(input_cst->GetType())) {
5738 Opcode high_opcode = opcode;
5739 vixl32::FlagsUpdate low_flags_update = vixl32::FlagsUpdate::DontCare;
5740 switch (opcode) {
5741 case SUB:
5742 // Flip the operation to an ADD.
5743 value = -value;
5744 opcode = ADD;
5745 FALLTHROUGH_INTENDED;
5746 case ADD:
5747 if (Low32Bits(value) == 0u) {
5748 return CanEncode32BitConstantAsImmediate(codegen_, High32Bits(value), opcode);
5749 }
5750 high_opcode = ADC;
5751 low_flags_update = vixl32::FlagsUpdate::SetFlags;
5752 break;
5753 default:
5754 break;
5755 }
5756 return CanEncode32BitConstantAsImmediate(codegen_, High32Bits(value), high_opcode) &&
5757 CanEncode32BitConstantAsImmediate(codegen_, Low32Bits(value), opcode, low_flags_update);
5758 } else {
5759 return CanEncode32BitConstantAsImmediate(codegen_, Low32Bits(value), opcode);
5760 }
5761 }
5762
HandleFieldGet(HInstruction * instruction,const FieldInfo & field_info)5763 void InstructionCodeGeneratorARMVIXL::HandleFieldGet(HInstruction* instruction,
5764 const FieldInfo& field_info) {
5765 DCHECK(instruction->IsInstanceFieldGet() || instruction->IsStaticFieldGet());
5766
5767 LocationSummary* locations = instruction->GetLocations();
5768 vixl32::Register base = InputRegisterAt(instruction, 0);
5769 Location out = locations->Out();
5770 bool is_volatile = field_info.IsVolatile();
5771 bool atomic_ldrd_strd = codegen_->GetInstructionSetFeatures().HasAtomicLdrdAndStrd();
5772 DCHECK_EQ(DataType::Size(field_info.GetFieldType()), DataType::Size(instruction->GetType()));
5773 DataType::Type load_type = instruction->GetType();
5774 uint32_t offset = field_info.GetFieldOffset().Uint32Value();
5775
5776 switch (load_type) {
5777 case DataType::Type::kBool:
5778 case DataType::Type::kUint8:
5779 case DataType::Type::kInt8:
5780 case DataType::Type::kUint16:
5781 case DataType::Type::kInt16:
5782 case DataType::Type::kInt32: {
5783 // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
5784 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
5785 LoadOperandType operand_type = GetLoadOperandType(load_type);
5786 GetAssembler()->LoadFromOffset(operand_type, RegisterFrom(out), base, offset);
5787 codegen_->MaybeRecordImplicitNullCheck(instruction);
5788 break;
5789 }
5790
5791 case DataType::Type::kReference: {
5792 // /* HeapReference<Object> */ out = *(base + offset)
5793 if (kEmitCompilerReadBarrier && kUseBakerReadBarrier) {
5794 Location maybe_temp = (locations->GetTempCount() != 0) ? locations->GetTemp(0) : Location();
5795 // Note that a potential implicit null check is handled in this
5796 // CodeGeneratorARMVIXL::GenerateFieldLoadWithBakerReadBarrier call.
5797 codegen_->GenerateFieldLoadWithBakerReadBarrier(
5798 instruction, out, base, offset, maybe_temp, /* needs_null_check= */ true);
5799 if (is_volatile) {
5800 codegen_->GenerateMemoryBarrier(MemBarrierKind::kLoadAny);
5801 }
5802 } else {
5803 {
5804 // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
5805 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
5806 GetAssembler()->LoadFromOffset(kLoadWord, RegisterFrom(out), base, offset);
5807 codegen_->MaybeRecordImplicitNullCheck(instruction);
5808 }
5809 if (is_volatile) {
5810 codegen_->GenerateMemoryBarrier(MemBarrierKind::kLoadAny);
5811 }
5812 // If read barriers are enabled, emit read barriers other than
5813 // Baker's using a slow path (and also unpoison the loaded
5814 // reference, if heap poisoning is enabled).
5815 codegen_->MaybeGenerateReadBarrierSlow(instruction, out, out, locations->InAt(0), offset);
5816 }
5817 break;
5818 }
5819
5820 case DataType::Type::kInt64: {
5821 // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
5822 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
5823 if (is_volatile && !atomic_ldrd_strd) {
5824 GenerateWideAtomicLoad(base, offset, LowRegisterFrom(out), HighRegisterFrom(out));
5825 } else {
5826 GetAssembler()->LoadFromOffset(kLoadWordPair, LowRegisterFrom(out), base, offset);
5827 }
5828 codegen_->MaybeRecordImplicitNullCheck(instruction);
5829 break;
5830 }
5831
5832 case DataType::Type::kFloat32: {
5833 // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
5834 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
5835 GetAssembler()->LoadSFromOffset(SRegisterFrom(out), base, offset);
5836 codegen_->MaybeRecordImplicitNullCheck(instruction);
5837 break;
5838 }
5839
5840 case DataType::Type::kFloat64: {
5841 // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
5842 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
5843 vixl32::DRegister out_dreg = DRegisterFrom(out);
5844 if (is_volatile && !atomic_ldrd_strd) {
5845 vixl32::Register lo = RegisterFrom(locations->GetTemp(0));
5846 vixl32::Register hi = RegisterFrom(locations->GetTemp(1));
5847 GenerateWideAtomicLoad(base, offset, lo, hi);
5848 codegen_->MaybeRecordImplicitNullCheck(instruction);
5849 __ Vmov(out_dreg, lo, hi);
5850 } else {
5851 GetAssembler()->LoadDFromOffset(out_dreg, base, offset);
5852 codegen_->MaybeRecordImplicitNullCheck(instruction);
5853 }
5854 break;
5855 }
5856
5857 case DataType::Type::kUint32:
5858 case DataType::Type::kUint64:
5859 case DataType::Type::kVoid:
5860 LOG(FATAL) << "Unreachable type " << load_type;
5861 UNREACHABLE();
5862 }
5863
5864 if (is_volatile) {
5865 if (load_type == DataType::Type::kReference) {
5866 // Memory barriers, in the case of references, are also handled
5867 // in the previous switch statement.
5868 } else {
5869 codegen_->GenerateMemoryBarrier(MemBarrierKind::kLoadAny);
5870 }
5871 }
5872 }
5873
VisitInstanceFieldSet(HInstanceFieldSet * instruction)5874 void LocationsBuilderARMVIXL::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
5875 HandleFieldSet(instruction, instruction->GetFieldInfo());
5876 }
5877
VisitInstanceFieldSet(HInstanceFieldSet * instruction)5878 void InstructionCodeGeneratorARMVIXL::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
5879 HandleFieldSet(instruction, instruction->GetFieldInfo(), instruction->GetValueCanBeNull());
5880 }
5881
VisitInstanceFieldGet(HInstanceFieldGet * instruction)5882 void LocationsBuilderARMVIXL::VisitInstanceFieldGet(HInstanceFieldGet* instruction) {
5883 HandleFieldGet(instruction, instruction->GetFieldInfo());
5884 }
5885
VisitInstanceFieldGet(HInstanceFieldGet * instruction)5886 void InstructionCodeGeneratorARMVIXL::VisitInstanceFieldGet(HInstanceFieldGet* instruction) {
5887 HandleFieldGet(instruction, instruction->GetFieldInfo());
5888 }
5889
VisitStaticFieldGet(HStaticFieldGet * instruction)5890 void LocationsBuilderARMVIXL::VisitStaticFieldGet(HStaticFieldGet* instruction) {
5891 HandleFieldGet(instruction, instruction->GetFieldInfo());
5892 }
5893
VisitStaticFieldGet(HStaticFieldGet * instruction)5894 void InstructionCodeGeneratorARMVIXL::VisitStaticFieldGet(HStaticFieldGet* instruction) {
5895 HandleFieldGet(instruction, instruction->GetFieldInfo());
5896 }
5897
VisitStaticFieldSet(HStaticFieldSet * instruction)5898 void LocationsBuilderARMVIXL::VisitStaticFieldSet(HStaticFieldSet* instruction) {
5899 HandleFieldSet(instruction, instruction->GetFieldInfo());
5900 }
5901
VisitStaticFieldSet(HStaticFieldSet * instruction)5902 void InstructionCodeGeneratorARMVIXL::VisitStaticFieldSet(HStaticFieldSet* instruction) {
5903 HandleFieldSet(instruction, instruction->GetFieldInfo(), instruction->GetValueCanBeNull());
5904 }
5905
VisitStringBuilderAppend(HStringBuilderAppend * instruction)5906 void LocationsBuilderARMVIXL::VisitStringBuilderAppend(HStringBuilderAppend* instruction) {
5907 codegen_->CreateStringBuilderAppendLocations(instruction, LocationFrom(r0));
5908 }
5909
VisitStringBuilderAppend(HStringBuilderAppend * instruction)5910 void InstructionCodeGeneratorARMVIXL::VisitStringBuilderAppend(HStringBuilderAppend* instruction) {
5911 __ Mov(r0, instruction->GetFormat()->GetValue());
5912 codegen_->InvokeRuntime(kQuickStringBuilderAppend, instruction, instruction->GetDexPc());
5913 }
5914
VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet * instruction)5915 void LocationsBuilderARMVIXL::VisitUnresolvedInstanceFieldGet(
5916 HUnresolvedInstanceFieldGet* instruction) {
5917 FieldAccessCallingConventionARMVIXL calling_convention;
5918 codegen_->CreateUnresolvedFieldLocationSummary(
5919 instruction, instruction->GetFieldType(), calling_convention);
5920 }
5921
VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet * instruction)5922 void InstructionCodeGeneratorARMVIXL::VisitUnresolvedInstanceFieldGet(
5923 HUnresolvedInstanceFieldGet* instruction) {
5924 FieldAccessCallingConventionARMVIXL calling_convention;
5925 codegen_->GenerateUnresolvedFieldAccess(instruction,
5926 instruction->GetFieldType(),
5927 instruction->GetFieldIndex(),
5928 instruction->GetDexPc(),
5929 calling_convention);
5930 }
5931
VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet * instruction)5932 void LocationsBuilderARMVIXL::VisitUnresolvedInstanceFieldSet(
5933 HUnresolvedInstanceFieldSet* instruction) {
5934 FieldAccessCallingConventionARMVIXL calling_convention;
5935 codegen_->CreateUnresolvedFieldLocationSummary(
5936 instruction, instruction->GetFieldType(), calling_convention);
5937 }
5938
VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet * instruction)5939 void InstructionCodeGeneratorARMVIXL::VisitUnresolvedInstanceFieldSet(
5940 HUnresolvedInstanceFieldSet* instruction) {
5941 FieldAccessCallingConventionARMVIXL calling_convention;
5942 codegen_->GenerateUnresolvedFieldAccess(instruction,
5943 instruction->GetFieldType(),
5944 instruction->GetFieldIndex(),
5945 instruction->GetDexPc(),
5946 calling_convention);
5947 }
5948
VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet * instruction)5949 void LocationsBuilderARMVIXL::VisitUnresolvedStaticFieldGet(
5950 HUnresolvedStaticFieldGet* instruction) {
5951 FieldAccessCallingConventionARMVIXL calling_convention;
5952 codegen_->CreateUnresolvedFieldLocationSummary(
5953 instruction, instruction->GetFieldType(), calling_convention);
5954 }
5955
VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet * instruction)5956 void InstructionCodeGeneratorARMVIXL::VisitUnresolvedStaticFieldGet(
5957 HUnresolvedStaticFieldGet* instruction) {
5958 FieldAccessCallingConventionARMVIXL calling_convention;
5959 codegen_->GenerateUnresolvedFieldAccess(instruction,
5960 instruction->GetFieldType(),
5961 instruction->GetFieldIndex(),
5962 instruction->GetDexPc(),
5963 calling_convention);
5964 }
5965
VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet * instruction)5966 void LocationsBuilderARMVIXL::VisitUnresolvedStaticFieldSet(
5967 HUnresolvedStaticFieldSet* instruction) {
5968 FieldAccessCallingConventionARMVIXL calling_convention;
5969 codegen_->CreateUnresolvedFieldLocationSummary(
5970 instruction, instruction->GetFieldType(), calling_convention);
5971 }
5972
VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet * instruction)5973 void InstructionCodeGeneratorARMVIXL::VisitUnresolvedStaticFieldSet(
5974 HUnresolvedStaticFieldSet* instruction) {
5975 FieldAccessCallingConventionARMVIXL calling_convention;
5976 codegen_->GenerateUnresolvedFieldAccess(instruction,
5977 instruction->GetFieldType(),
5978 instruction->GetFieldIndex(),
5979 instruction->GetDexPc(),
5980 calling_convention);
5981 }
5982
VisitNullCheck(HNullCheck * instruction)5983 void LocationsBuilderARMVIXL::VisitNullCheck(HNullCheck* instruction) {
5984 LocationSummary* locations = codegen_->CreateThrowingSlowPathLocations(instruction);
5985 locations->SetInAt(0, Location::RequiresRegister());
5986 }
5987
GenerateImplicitNullCheck(HNullCheck * instruction)5988 void CodeGeneratorARMVIXL::GenerateImplicitNullCheck(HNullCheck* instruction) {
5989 if (CanMoveNullCheckToUser(instruction)) {
5990 return;
5991 }
5992
5993 UseScratchRegisterScope temps(GetVIXLAssembler());
5994 // Ensure the pc position is recorded immediately after the `ldr` instruction.
5995 ExactAssemblyScope aas(GetVIXLAssembler(),
5996 vixl32::kMaxInstructionSizeInBytes,
5997 CodeBufferCheckScope::kMaximumSize);
5998 __ ldr(temps.Acquire(), MemOperand(InputRegisterAt(instruction, 0)));
5999 RecordPcInfo(instruction, instruction->GetDexPc());
6000 }
6001
GenerateExplicitNullCheck(HNullCheck * instruction)6002 void CodeGeneratorARMVIXL::GenerateExplicitNullCheck(HNullCheck* instruction) {
6003 NullCheckSlowPathARMVIXL* slow_path =
6004 new (GetScopedAllocator()) NullCheckSlowPathARMVIXL(instruction);
6005 AddSlowPath(slow_path);
6006 __ CompareAndBranchIfZero(InputRegisterAt(instruction, 0), slow_path->GetEntryLabel());
6007 }
6008
VisitNullCheck(HNullCheck * instruction)6009 void InstructionCodeGeneratorARMVIXL::VisitNullCheck(HNullCheck* instruction) {
6010 codegen_->GenerateNullCheck(instruction);
6011 }
6012
LoadFromShiftedRegOffset(DataType::Type type,Location out_loc,vixl32::Register base,vixl32::Register reg_index,vixl32::Condition cond)6013 void CodeGeneratorARMVIXL::LoadFromShiftedRegOffset(DataType::Type type,
6014 Location out_loc,
6015 vixl32::Register base,
6016 vixl32::Register reg_index,
6017 vixl32::Condition cond) {
6018 uint32_t shift_count = DataType::SizeShift(type);
6019 MemOperand mem_address(base, reg_index, vixl32::LSL, shift_count);
6020
6021 switch (type) {
6022 case DataType::Type::kBool:
6023 case DataType::Type::kUint8:
6024 __ Ldrb(cond, RegisterFrom(out_loc), mem_address);
6025 break;
6026 case DataType::Type::kInt8:
6027 __ Ldrsb(cond, RegisterFrom(out_loc), mem_address);
6028 break;
6029 case DataType::Type::kUint16:
6030 __ Ldrh(cond, RegisterFrom(out_loc), mem_address);
6031 break;
6032 case DataType::Type::kInt16:
6033 __ Ldrsh(cond, RegisterFrom(out_loc), mem_address);
6034 break;
6035 case DataType::Type::kReference:
6036 case DataType::Type::kInt32:
6037 __ Ldr(cond, RegisterFrom(out_loc), mem_address);
6038 break;
6039 // T32 doesn't support LoadFromShiftedRegOffset mem address mode for these types.
6040 case DataType::Type::kInt64:
6041 case DataType::Type::kFloat32:
6042 case DataType::Type::kFloat64:
6043 default:
6044 LOG(FATAL) << "Unreachable type " << type;
6045 UNREACHABLE();
6046 }
6047 }
6048
StoreToShiftedRegOffset(DataType::Type type,Location loc,vixl32::Register base,vixl32::Register reg_index,vixl32::Condition cond)6049 void CodeGeneratorARMVIXL::StoreToShiftedRegOffset(DataType::Type type,
6050 Location loc,
6051 vixl32::Register base,
6052 vixl32::Register reg_index,
6053 vixl32::Condition cond) {
6054 uint32_t shift_count = DataType::SizeShift(type);
6055 MemOperand mem_address(base, reg_index, vixl32::LSL, shift_count);
6056
6057 switch (type) {
6058 case DataType::Type::kBool:
6059 case DataType::Type::kUint8:
6060 case DataType::Type::kInt8:
6061 __ Strb(cond, RegisterFrom(loc), mem_address);
6062 break;
6063 case DataType::Type::kUint16:
6064 case DataType::Type::kInt16:
6065 __ Strh(cond, RegisterFrom(loc), mem_address);
6066 break;
6067 case DataType::Type::kReference:
6068 case DataType::Type::kInt32:
6069 __ Str(cond, RegisterFrom(loc), mem_address);
6070 break;
6071 // T32 doesn't support StoreToShiftedRegOffset mem address mode for these types.
6072 case DataType::Type::kInt64:
6073 case DataType::Type::kFloat32:
6074 case DataType::Type::kFloat64:
6075 default:
6076 LOG(FATAL) << "Unreachable type " << type;
6077 UNREACHABLE();
6078 }
6079 }
6080
VisitArrayGet(HArrayGet * instruction)6081 void LocationsBuilderARMVIXL::VisitArrayGet(HArrayGet* instruction) {
6082 bool object_array_get_with_read_barrier =
6083 kEmitCompilerReadBarrier && (instruction->GetType() == DataType::Type::kReference);
6084 LocationSummary* locations =
6085 new (GetGraph()->GetAllocator()) LocationSummary(instruction,
6086 object_array_get_with_read_barrier
6087 ? LocationSummary::kCallOnSlowPath
6088 : LocationSummary::kNoCall);
6089 if (object_array_get_with_read_barrier && kUseBakerReadBarrier) {
6090 locations->SetCustomSlowPathCallerSaves(RegisterSet::Empty()); // No caller-save registers.
6091 }
6092 locations->SetInAt(0, Location::RequiresRegister());
6093 locations->SetInAt(1, Location::RegisterOrConstant(instruction->InputAt(1)));
6094 if (DataType::IsFloatingPointType(instruction->GetType())) {
6095 locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
6096 } else {
6097 // The output overlaps in the case of an object array get with
6098 // read barriers enabled: we do not want the move to overwrite the
6099 // array's location, as we need it to emit the read barrier.
6100 locations->SetOut(
6101 Location::RequiresRegister(),
6102 object_array_get_with_read_barrier ? Location::kOutputOverlap : Location::kNoOutputOverlap);
6103 }
6104 if (object_array_get_with_read_barrier && kUseBakerReadBarrier) {
6105 if (instruction->GetIndex()->IsConstant()) {
6106 // Array loads with constant index are treated as field loads.
6107 // We need a temporary register for the read barrier load in
6108 // CodeGeneratorARMVIXL::GenerateFieldLoadWithBakerReadBarrier()
6109 // only if the offset is too big.
6110 uint32_t offset = CodeGenerator::GetArrayDataOffset(instruction);
6111 uint32_t index = instruction->GetIndex()->AsIntConstant()->GetValue();
6112 offset += index << DataType::SizeShift(DataType::Type::kReference);
6113 if (offset >= kReferenceLoadMinFarOffset) {
6114 locations->AddTemp(Location::RequiresRegister());
6115 }
6116 } else {
6117 // We need a non-scratch temporary for the array data pointer in
6118 // CodeGeneratorARMVIXL::GenerateArrayLoadWithBakerReadBarrier().
6119 locations->AddTemp(Location::RequiresRegister());
6120 }
6121 } else if (mirror::kUseStringCompression && instruction->IsStringCharAt()) {
6122 // Also need a temporary for String compression feature.
6123 locations->AddTemp(Location::RequiresRegister());
6124 }
6125 }
6126
VisitArrayGet(HArrayGet * instruction)6127 void InstructionCodeGeneratorARMVIXL::VisitArrayGet(HArrayGet* instruction) {
6128 LocationSummary* locations = instruction->GetLocations();
6129 Location obj_loc = locations->InAt(0);
6130 vixl32::Register obj = InputRegisterAt(instruction, 0);
6131 Location index = locations->InAt(1);
6132 Location out_loc = locations->Out();
6133 uint32_t data_offset = CodeGenerator::GetArrayDataOffset(instruction);
6134 DataType::Type type = instruction->GetType();
6135 const bool maybe_compressed_char_at = mirror::kUseStringCompression &&
6136 instruction->IsStringCharAt();
6137 HInstruction* array_instr = instruction->GetArray();
6138 bool has_intermediate_address = array_instr->IsIntermediateAddress();
6139
6140 switch (type) {
6141 case DataType::Type::kBool:
6142 case DataType::Type::kUint8:
6143 case DataType::Type::kInt8:
6144 case DataType::Type::kUint16:
6145 case DataType::Type::kInt16:
6146 case DataType::Type::kInt32: {
6147 vixl32::Register length;
6148 if (maybe_compressed_char_at) {
6149 length = RegisterFrom(locations->GetTemp(0));
6150 uint32_t count_offset = mirror::String::CountOffset().Uint32Value();
6151 // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
6152 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
6153 GetAssembler()->LoadFromOffset(kLoadWord, length, obj, count_offset);
6154 codegen_->MaybeRecordImplicitNullCheck(instruction);
6155 }
6156 if (index.IsConstant()) {
6157 int32_t const_index = Int32ConstantFrom(index);
6158 if (maybe_compressed_char_at) {
6159 vixl32::Label uncompressed_load, done;
6160 vixl32::Label* final_label = codegen_->GetFinalLabel(instruction, &done);
6161 __ Lsrs(length, length, 1u); // LSRS has a 16-bit encoding, TST (immediate) does not.
6162 static_assert(static_cast<uint32_t>(mirror::StringCompressionFlag::kCompressed) == 0u,
6163 "Expecting 0=compressed, 1=uncompressed");
6164 __ B(cs, &uncompressed_load, /* is_far_target= */ false);
6165 GetAssembler()->LoadFromOffset(kLoadUnsignedByte,
6166 RegisterFrom(out_loc),
6167 obj,
6168 data_offset + const_index);
6169 __ B(final_label);
6170 __ Bind(&uncompressed_load);
6171 GetAssembler()->LoadFromOffset(GetLoadOperandType(DataType::Type::kUint16),
6172 RegisterFrom(out_loc),
6173 obj,
6174 data_offset + (const_index << 1));
6175 if (done.IsReferenced()) {
6176 __ Bind(&done);
6177 }
6178 } else {
6179 uint32_t full_offset = data_offset + (const_index << DataType::SizeShift(type));
6180
6181 // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
6182 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
6183 LoadOperandType load_type = GetLoadOperandType(type);
6184 GetAssembler()->LoadFromOffset(load_type, RegisterFrom(out_loc), obj, full_offset);
6185 codegen_->MaybeRecordImplicitNullCheck(instruction);
6186 }
6187 } else {
6188 UseScratchRegisterScope temps(GetVIXLAssembler());
6189 vixl32::Register temp = temps.Acquire();
6190
6191 if (has_intermediate_address) {
6192 // We do not need to compute the intermediate address from the array: the
6193 // input instruction has done it already. See the comment in
6194 // `TryExtractArrayAccessAddress()`.
6195 if (kIsDebugBuild) {
6196 HIntermediateAddress* tmp = array_instr->AsIntermediateAddress();
6197 DCHECK_EQ(Uint64ConstantFrom(tmp->GetOffset()), data_offset);
6198 }
6199 temp = obj;
6200 } else {
6201 __ Add(temp, obj, data_offset);
6202 }
6203 if (maybe_compressed_char_at) {
6204 vixl32::Label uncompressed_load, done;
6205 vixl32::Label* final_label = codegen_->GetFinalLabel(instruction, &done);
6206 __ Lsrs(length, length, 1u); // LSRS has a 16-bit encoding, TST (immediate) does not.
6207 static_assert(static_cast<uint32_t>(mirror::StringCompressionFlag::kCompressed) == 0u,
6208 "Expecting 0=compressed, 1=uncompressed");
6209 __ B(cs, &uncompressed_load, /* is_far_target= */ false);
6210 __ Ldrb(RegisterFrom(out_loc), MemOperand(temp, RegisterFrom(index), vixl32::LSL, 0));
6211 __ B(final_label);
6212 __ Bind(&uncompressed_load);
6213 __ Ldrh(RegisterFrom(out_loc), MemOperand(temp, RegisterFrom(index), vixl32::LSL, 1));
6214 if (done.IsReferenced()) {
6215 __ Bind(&done);
6216 }
6217 } else {
6218 // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
6219 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
6220 codegen_->LoadFromShiftedRegOffset(type, out_loc, temp, RegisterFrom(index));
6221 codegen_->MaybeRecordImplicitNullCheck(instruction);
6222 }
6223 }
6224 break;
6225 }
6226
6227 case DataType::Type::kReference: {
6228 // The read barrier instrumentation of object ArrayGet
6229 // instructions does not support the HIntermediateAddress
6230 // instruction.
6231 DCHECK(!(has_intermediate_address && kEmitCompilerReadBarrier));
6232
6233 static_assert(
6234 sizeof(mirror::HeapReference<mirror::Object>) == sizeof(int32_t),
6235 "art::mirror::HeapReference<art::mirror::Object> and int32_t have different sizes.");
6236 // /* HeapReference<Object> */ out =
6237 // *(obj + data_offset + index * sizeof(HeapReference<Object>))
6238 if (kEmitCompilerReadBarrier && kUseBakerReadBarrier) {
6239 // Note that a potential implicit null check is handled in this
6240 // CodeGeneratorARMVIXL::GenerateArrayLoadWithBakerReadBarrier call.
6241 DCHECK(!instruction->CanDoImplicitNullCheckOn(instruction->InputAt(0)));
6242 if (index.IsConstant()) {
6243 // Array load with a constant index can be treated as a field load.
6244 Location maybe_temp =
6245 (locations->GetTempCount() != 0) ? locations->GetTemp(0) : Location();
6246 data_offset += Int32ConstantFrom(index) << DataType::SizeShift(type);
6247 codegen_->GenerateFieldLoadWithBakerReadBarrier(instruction,
6248 out_loc,
6249 obj,
6250 data_offset,
6251 maybe_temp,
6252 /* needs_null_check= */ false);
6253 } else {
6254 Location temp = locations->GetTemp(0);
6255 codegen_->GenerateArrayLoadWithBakerReadBarrier(
6256 out_loc, obj, data_offset, index, temp, /* needs_null_check= */ false);
6257 }
6258 } else {
6259 vixl32::Register out = OutputRegister(instruction);
6260 if (index.IsConstant()) {
6261 size_t offset = (Int32ConstantFrom(index) << TIMES_4) + data_offset;
6262 {
6263 // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
6264 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
6265 GetAssembler()->LoadFromOffset(kLoadWord, out, obj, offset);
6266 codegen_->MaybeRecordImplicitNullCheck(instruction);
6267 }
6268 // If read barriers are enabled, emit read barriers other than
6269 // Baker's using a slow path (and also unpoison the loaded
6270 // reference, if heap poisoning is enabled).
6271 codegen_->MaybeGenerateReadBarrierSlow(instruction, out_loc, out_loc, obj_loc, offset);
6272 } else {
6273 UseScratchRegisterScope temps(GetVIXLAssembler());
6274 vixl32::Register temp = temps.Acquire();
6275
6276 if (has_intermediate_address) {
6277 // We do not need to compute the intermediate address from the array: the
6278 // input instruction has done it already. See the comment in
6279 // `TryExtractArrayAccessAddress()`.
6280 if (kIsDebugBuild) {
6281 HIntermediateAddress* tmp = array_instr->AsIntermediateAddress();
6282 DCHECK_EQ(Uint64ConstantFrom(tmp->GetOffset()), data_offset);
6283 }
6284 temp = obj;
6285 } else {
6286 __ Add(temp, obj, data_offset);
6287 }
6288 {
6289 // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
6290 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
6291 codegen_->LoadFromShiftedRegOffset(type, out_loc, temp, RegisterFrom(index));
6292 temps.Close();
6293 codegen_->MaybeRecordImplicitNullCheck(instruction);
6294 }
6295 // If read barriers are enabled, emit read barriers other than
6296 // Baker's using a slow path (and also unpoison the loaded
6297 // reference, if heap poisoning is enabled).
6298 codegen_->MaybeGenerateReadBarrierSlow(
6299 instruction, out_loc, out_loc, obj_loc, data_offset, index);
6300 }
6301 }
6302 break;
6303 }
6304
6305 case DataType::Type::kInt64: {
6306 // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
6307 // As two macro instructions can be emitted the max size is doubled.
6308 EmissionCheckScope guard(GetVIXLAssembler(), 2 * kMaxMacroInstructionSizeInBytes);
6309 if (index.IsConstant()) {
6310 size_t offset =
6311 (Int32ConstantFrom(index) << TIMES_8) + data_offset;
6312 GetAssembler()->LoadFromOffset(kLoadWordPair, LowRegisterFrom(out_loc), obj, offset);
6313 } else {
6314 UseScratchRegisterScope temps(GetVIXLAssembler());
6315 vixl32::Register temp = temps.Acquire();
6316 __ Add(temp, obj, Operand(RegisterFrom(index), vixl32::LSL, TIMES_8));
6317 GetAssembler()->LoadFromOffset(kLoadWordPair, LowRegisterFrom(out_loc), temp, data_offset);
6318 }
6319 codegen_->MaybeRecordImplicitNullCheck(instruction);
6320 break;
6321 }
6322
6323 case DataType::Type::kFloat32: {
6324 // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
6325 // As two macro instructions can be emitted the max size is doubled.
6326 EmissionCheckScope guard(GetVIXLAssembler(), 2 * kMaxMacroInstructionSizeInBytes);
6327 vixl32::SRegister out = SRegisterFrom(out_loc);
6328 if (index.IsConstant()) {
6329 size_t offset = (Int32ConstantFrom(index) << TIMES_4) + data_offset;
6330 GetAssembler()->LoadSFromOffset(out, obj, offset);
6331 } else {
6332 UseScratchRegisterScope temps(GetVIXLAssembler());
6333 vixl32::Register temp = temps.Acquire();
6334 __ Add(temp, obj, Operand(RegisterFrom(index), vixl32::LSL, TIMES_4));
6335 GetAssembler()->LoadSFromOffset(out, temp, data_offset);
6336 }
6337 codegen_->MaybeRecordImplicitNullCheck(instruction);
6338 break;
6339 }
6340
6341 case DataType::Type::kFloat64: {
6342 // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
6343 // As two macro instructions can be emitted the max size is doubled.
6344 EmissionCheckScope guard(GetVIXLAssembler(), 2 * kMaxMacroInstructionSizeInBytes);
6345 if (index.IsConstant()) {
6346 size_t offset = (Int32ConstantFrom(index) << TIMES_8) + data_offset;
6347 GetAssembler()->LoadDFromOffset(DRegisterFrom(out_loc), obj, offset);
6348 } else {
6349 UseScratchRegisterScope temps(GetVIXLAssembler());
6350 vixl32::Register temp = temps.Acquire();
6351 __ Add(temp, obj, Operand(RegisterFrom(index), vixl32::LSL, TIMES_8));
6352 GetAssembler()->LoadDFromOffset(DRegisterFrom(out_loc), temp, data_offset);
6353 }
6354 codegen_->MaybeRecordImplicitNullCheck(instruction);
6355 break;
6356 }
6357
6358 case DataType::Type::kUint32:
6359 case DataType::Type::kUint64:
6360 case DataType::Type::kVoid:
6361 LOG(FATAL) << "Unreachable type " << type;
6362 UNREACHABLE();
6363 }
6364 }
6365
VisitArraySet(HArraySet * instruction)6366 void LocationsBuilderARMVIXL::VisitArraySet(HArraySet* instruction) {
6367 DataType::Type value_type = instruction->GetComponentType();
6368
6369 bool needs_write_barrier =
6370 CodeGenerator::StoreNeedsWriteBarrier(value_type, instruction->GetValue());
6371 bool needs_type_check = instruction->NeedsTypeCheck();
6372
6373 LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(
6374 instruction,
6375 needs_type_check ? LocationSummary::kCallOnSlowPath : LocationSummary::kNoCall);
6376
6377 locations->SetInAt(0, Location::RequiresRegister());
6378 locations->SetInAt(1, Location::RegisterOrConstant(instruction->InputAt(1)));
6379 if (DataType::IsFloatingPointType(value_type)) {
6380 locations->SetInAt(2, Location::RequiresFpuRegister());
6381 } else {
6382 locations->SetInAt(2, Location::RequiresRegister());
6383 }
6384 if (needs_write_barrier) {
6385 // Temporary registers for the write barrier.
6386 locations->AddTemp(Location::RequiresRegister()); // Possibly used for ref. poisoning too.
6387 locations->AddTemp(Location::RequiresRegister());
6388 }
6389 }
6390
VisitArraySet(HArraySet * instruction)6391 void InstructionCodeGeneratorARMVIXL::VisitArraySet(HArraySet* instruction) {
6392 LocationSummary* locations = instruction->GetLocations();
6393 vixl32::Register array = InputRegisterAt(instruction, 0);
6394 Location index = locations->InAt(1);
6395 DataType::Type value_type = instruction->GetComponentType();
6396 bool needs_type_check = instruction->NeedsTypeCheck();
6397 bool needs_write_barrier =
6398 CodeGenerator::StoreNeedsWriteBarrier(value_type, instruction->GetValue());
6399 uint32_t data_offset =
6400 mirror::Array::DataOffset(DataType::Size(value_type)).Uint32Value();
6401 Location value_loc = locations->InAt(2);
6402 HInstruction* array_instr = instruction->GetArray();
6403 bool has_intermediate_address = array_instr->IsIntermediateAddress();
6404
6405 switch (value_type) {
6406 case DataType::Type::kBool:
6407 case DataType::Type::kUint8:
6408 case DataType::Type::kInt8:
6409 case DataType::Type::kUint16:
6410 case DataType::Type::kInt16:
6411 case DataType::Type::kInt32: {
6412 if (index.IsConstant()) {
6413 int32_t const_index = Int32ConstantFrom(index);
6414 uint32_t full_offset =
6415 data_offset + (const_index << DataType::SizeShift(value_type));
6416 StoreOperandType store_type = GetStoreOperandType(value_type);
6417 // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
6418 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
6419 GetAssembler()->StoreToOffset(store_type, RegisterFrom(value_loc), array, full_offset);
6420 codegen_->MaybeRecordImplicitNullCheck(instruction);
6421 } else {
6422 UseScratchRegisterScope temps(GetVIXLAssembler());
6423 vixl32::Register temp = temps.Acquire();
6424
6425 if (has_intermediate_address) {
6426 // We do not need to compute the intermediate address from the array: the
6427 // input instruction has done it already. See the comment in
6428 // `TryExtractArrayAccessAddress()`.
6429 if (kIsDebugBuild) {
6430 HIntermediateAddress* tmp = array_instr->AsIntermediateAddress();
6431 DCHECK_EQ(Uint64ConstantFrom(tmp->GetOffset()), data_offset);
6432 }
6433 temp = array;
6434 } else {
6435 __ Add(temp, array, data_offset);
6436 }
6437 // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
6438 EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
6439 codegen_->StoreToShiftedRegOffset(value_type, value_loc, temp, RegisterFrom(index));
6440 codegen_->MaybeRecordImplicitNullCheck(instruction);
6441 }
6442 break;
6443 }
6444
6445 case DataType::Type::kReference: {
6446 vixl32::Register value = RegisterFrom(value_loc);
6447 // TryExtractArrayAccessAddress optimization is never applied for non-primitive ArraySet.
6448 // See the comment in instruction_simplifier_shared.cc.
6449 DCHECK(!has_intermediate_address);
6450
6451 if (instruction->InputAt(2)->IsNullConstant()) {
6452 // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
6453 // As two macro instructions can be emitted the max size is doubled.
6454 EmissionCheckScope guard(GetVIXLAssembler(), 2 * kMaxMacroInstructionSizeInBytes);
6455 // Just setting null.
6456 if (index.IsConstant()) {
6457 size_t offset = (Int32ConstantFrom(index) << TIMES_4) + data_offset;
6458 GetAssembler()->StoreToOffset(kStoreWord, value, array, offset);
6459 } else {
6460 DCHECK(index.IsRegister()) << index;
6461 UseScratchRegisterScope temps(GetVIXLAssembler());
6462 vixl32::Register temp = temps.Acquire();
6463 __ Add(temp, array, data_offset);
6464 codegen_->StoreToShiftedRegOffset(value_type, value_loc, temp, RegisterFrom(index));
6465 }
6466 codegen_->MaybeRecordImplicitNullCheck(instruction);
6467 DCHECK(!needs_write_barrier);
6468 DCHECK(!needs_type_check);
6469 break;
6470 }
6471
6472 DCHECK(needs_write_barrier);
6473 Location temp1_loc = locations->GetTemp(0);
6474 vixl32::Register temp1 = RegisterFrom(temp1_loc);
6475 Location temp2_loc = locations->GetTemp(1);
6476 vixl32::Register temp2 = RegisterFrom(temp2_loc);
6477
6478 bool can_value_be_null = instruction->GetValueCanBeNull();
6479 vixl32::Label do_store;
6480 if (can_value_be_null) {
6481 __ CompareAndBranchIfZero(value, &do_store, /* is_far_target= */ false);
6482 }
6483
6484 SlowPathCodeARMVIXL* slow_path = nullptr;
6485 if (needs_type_check) {
6486 slow_path = new (codegen_->GetScopedAllocator()) ArraySetSlowPathARMVIXL(instruction);
6487 codegen_->AddSlowPath(slow_path);
6488
6489 const uint32_t class_offset = mirror::Object::ClassOffset().Int32Value();
6490 const uint32_t super_offset = mirror::Class::SuperClassOffset().Int32Value();
6491 const uint32_t component_offset = mirror::Class::ComponentTypeOffset().Int32Value();
6492
6493 // Note that when read barriers are enabled, the type checks
6494 // are performed without read barriers. This is fine, even in
6495 // the case where a class object is in the from-space after
6496 // the flip, as a comparison involving such a type would not
6497 // produce a false positive; it may of course produce a false
6498 // negative, in which case we would take the ArraySet slow
6499 // path.
6500
6501 {
6502 // Ensure we record the pc position immediately after the `ldr` instruction.
6503 ExactAssemblyScope aas(GetVIXLAssembler(),
6504 vixl32::kMaxInstructionSizeInBytes,
6505 CodeBufferCheckScope::kMaximumSize);
6506 // /* HeapReference<Class> */ temp1 = array->klass_
6507 __ ldr(temp1, MemOperand(array, class_offset));
6508 codegen_->MaybeRecordImplicitNullCheck(instruction);
6509 }
6510 GetAssembler()->MaybeUnpoisonHeapReference(temp1);
6511
6512 // /* HeapReference<Class> */ temp1 = temp1->component_type_
6513 GetAssembler()->LoadFromOffset(kLoadWord, temp1, temp1, component_offset);
6514 // /* HeapReference<Class> */ temp2 = value->klass_
6515 GetAssembler()->LoadFromOffset(kLoadWord, temp2, value, class_offset);
6516 // If heap poisoning is enabled, no need to unpoison `temp1`
6517 // nor `temp2`, as we are comparing two poisoned references.
6518 __ Cmp(temp1, temp2);
6519
6520 if (instruction->StaticTypeOfArrayIsObjectArray()) {
6521 vixl32::Label do_put;
6522 __ B(eq, &do_put, /* is_far_target= */ false);
6523 // If heap poisoning is enabled, the `temp1` reference has
6524 // not been unpoisoned yet; unpoison it now.
6525 GetAssembler()->MaybeUnpoisonHeapReference(temp1);
6526
6527 // /* HeapReference<Class> */ temp1 = temp1->super_class_
6528 GetAssembler()->LoadFromOffset(kLoadWord, temp1, temp1, super_offset);
6529 // If heap poisoning is enabled, no need to unpoison
6530 // `temp1`, as we are comparing against null below.
6531 __ CompareAndBranchIfNonZero(temp1, slow_path->GetEntryLabel());
6532 __ Bind(&do_put);
6533 } else {
6534 __ B(ne, slow_path->GetEntryLabel());
6535 }
6536 }
6537
6538 codegen_->MarkGCCard(temp1, temp2, array, value, /* can_be_null= */ false);
6539
6540 if (can_value_be_null) {
6541 DCHECK(do_store.IsReferenced());
6542 __ Bind(&do_store);
6543 }
6544
6545 vixl32::Register source = value;
6546 if (kPoisonHeapReferences) {
6547 // Note that in the case where `value` is a null reference,
6548 // we do not enter this block, as a null reference does not
6549 // need poisoning.
6550 DCHECK_EQ(value_type, DataType::Type::kReference);
6551 __ Mov(temp1, value);
6552 GetAssembler()->PoisonHeapReference(temp1);
6553 source = temp1;
6554 }
6555
6556 {
6557 // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
6558 // As two macro instructions can be emitted the max size is doubled.
6559 EmissionCheckScope guard(GetVIXLAssembler(), 2 * kMaxMacroInstructionSizeInBytes);
6560 if (index.IsConstant()) {
6561 size_t offset = (Int32ConstantFrom(index) << TIMES_4) + data_offset;
6562 GetAssembler()->StoreToOffset(kStoreWord, source, array, offset);
6563 } else {
6564 DCHECK(index.IsRegister()) << index;
6565
6566 UseScratchRegisterScope temps(GetVIXLAssembler());
6567 vixl32::Register temp = temps.Acquire();
6568 __ Add(temp, array, data_offset);
6569 codegen_->StoreToShiftedRegOffset(value_type,
6570 LocationFrom(source),
6571 temp,
6572 RegisterFrom(index));
6573 }
6574
6575 if (can_value_be_null || !needs_type_check) {
6576 codegen_->MaybeRecordImplicitNullCheck(instruction);
6577 }
6578 }
6579
6580 if (slow_path != nullptr) {
6581 __ Bind(slow_path->GetExitLabel());
6582 }
6583
6584 break;
6585 }
6586
6587 case DataType::Type::kInt64: {
6588 // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
6589 // As two macro instructions can be emitted the max size is doubled.
6590 EmissionCheckScope guard(GetVIXLAssembler(), 2 * kMaxMacroInstructionSizeInBytes);
6591 Location value = locations->InAt(2);
6592 if (index.IsConstant()) {
6593 size_t offset =
6594 (Int32ConstantFrom(index) << TIMES_8) + data_offset;
6595 GetAssembler()->StoreToOffset(kStoreWordPair, LowRegisterFrom(value), array, offset);
6596 } else {
6597 UseScratchRegisterScope temps(GetVIXLAssembler());
6598 vixl32::Register temp = temps.Acquire();
6599 __ Add(temp, array, Operand(RegisterFrom(index), vixl32::LSL, TIMES_8));
6600 GetAssembler()->StoreToOffset(kStoreWordPair, LowRegisterFrom(value), temp, data_offset);
6601 }
6602 codegen_->MaybeRecordImplicitNullCheck(instruction);
6603 break;
6604 }
6605
6606 case DataType::Type::kFloat32: {
6607 // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
6608 // As two macro instructions can be emitted the max size is doubled.
6609 EmissionCheckScope guard(GetVIXLAssembler(), 2 * kMaxMacroInstructionSizeInBytes);
6610 Location value = locations->InAt(2);
6611 DCHECK(value.IsFpuRegister());
6612 if (index.IsConstant()) {
6613 size_t offset = (Int32ConstantFrom(index) << TIMES_4) + data_offset;
6614 GetAssembler()->StoreSToOffset(SRegisterFrom(value), array, offset);
6615 } else {
6616 UseScratchRegisterScope temps(GetVIXLAssembler());
6617 vixl32::Register temp = temps.Acquire();
6618 __ Add(temp, array, Operand(RegisterFrom(index), vixl32::LSL, TIMES_4));
6619 GetAssembler()->StoreSToOffset(SRegisterFrom(value), temp, data_offset);
6620 }
6621 codegen_->MaybeRecordImplicitNullCheck(instruction);
6622 break;
6623 }
6624
6625 case DataType::Type::kFloat64: {
6626 // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
6627 // As two macro instructions can be emitted the max size is doubled.
6628 EmissionCheckScope guard(GetVIXLAssembler(), 2 * kMaxMacroInstructionSizeInBytes);
6629 Location value = locations->InAt(2);
6630 DCHECK(value.IsFpuRegisterPair());
6631 if (index.IsConstant()) {
6632 size_t offset = (Int32ConstantFrom(index) << TIMES_8) + data_offset;
6633 GetAssembler()->StoreDToOffset(DRegisterFrom(value), array, offset);
6634 } else {
6635 UseScratchRegisterScope temps(GetVIXLAssembler());
6636 vixl32::Register temp = temps.Acquire();
6637 __ Add(temp, array, Operand(RegisterFrom(index), vixl32::LSL, TIMES_8));
6638 GetAssembler()->StoreDToOffset(DRegisterFrom(value), temp, data_offset);
6639 }
6640 codegen_->MaybeRecordImplicitNullCheck(instruction);
6641 break;
6642 }
6643
6644 case DataType::Type::kUint32:
6645 case DataType::Type::kUint64:
6646 case DataType::Type::kVoid:
6647 LOG(FATAL) << "Unreachable type " << value_type;
6648 UNREACHABLE();
6649 }
6650 }
6651
VisitArrayLength(HArrayLength * instruction)6652 void LocationsBuilderARMVIXL::VisitArrayLength(HArrayLength* instruction) {
6653 LocationSummary* locations =
6654 new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
6655 locations->SetInAt(0, Location::RequiresRegister());
6656 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
6657 }
6658
VisitArrayLength(HArrayLength * instruction)6659 void InstructionCodeGeneratorARMVIXL::VisitArrayLength(HArrayLength* instruction) {
6660 uint32_t offset = CodeGenerator::GetArrayLengthOffset(instruction);
6661 vixl32::Register obj = InputRegisterAt(instruction, 0);
6662 vixl32::Register out = OutputRegister(instruction);
6663 {
6664 ExactAssemblyScope aas(GetVIXLAssembler(),
6665 vixl32::kMaxInstructionSizeInBytes,
6666 CodeBufferCheckScope::kMaximumSize);
6667 __ ldr(out, MemOperand(obj, offset));
6668 codegen_->MaybeRecordImplicitNullCheck(instruction);
6669 }
6670 // Mask out compression flag from String's array length.
6671 if (mirror::kUseStringCompression && instruction->IsStringLength()) {
6672 __ Lsr(out, out, 1u);
6673 }
6674 }
6675
VisitIntermediateAddress(HIntermediateAddress * instruction)6676 void LocationsBuilderARMVIXL::VisitIntermediateAddress(HIntermediateAddress* instruction) {
6677 LocationSummary* locations =
6678 new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
6679
6680 locations->SetInAt(0, Location::RequiresRegister());
6681 locations->SetInAt(1, Location::RegisterOrConstant(instruction->GetOffset()));
6682 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
6683 }
6684
VisitIntermediateAddress(HIntermediateAddress * instruction)6685 void InstructionCodeGeneratorARMVIXL::VisitIntermediateAddress(HIntermediateAddress* instruction) {
6686 vixl32::Register out = OutputRegister(instruction);
6687 vixl32::Register first = InputRegisterAt(instruction, 0);
6688 Location second = instruction->GetLocations()->InAt(1);
6689
6690 if (second.IsRegister()) {
6691 __ Add(out, first, RegisterFrom(second));
6692 } else {
6693 __ Add(out, first, Int32ConstantFrom(second));
6694 }
6695 }
6696
VisitIntermediateAddressIndex(HIntermediateAddressIndex * instruction)6697 void LocationsBuilderARMVIXL::VisitIntermediateAddressIndex(
6698 HIntermediateAddressIndex* instruction) {
6699 LOG(FATAL) << "Unreachable " << instruction->GetId();
6700 }
6701
VisitIntermediateAddressIndex(HIntermediateAddressIndex * instruction)6702 void InstructionCodeGeneratorARMVIXL::VisitIntermediateAddressIndex(
6703 HIntermediateAddressIndex* instruction) {
6704 LOG(FATAL) << "Unreachable " << instruction->GetId();
6705 }
6706
VisitBoundsCheck(HBoundsCheck * instruction)6707 void LocationsBuilderARMVIXL::VisitBoundsCheck(HBoundsCheck* instruction) {
6708 RegisterSet caller_saves = RegisterSet::Empty();
6709 InvokeRuntimeCallingConventionARMVIXL calling_convention;
6710 caller_saves.Add(LocationFrom(calling_convention.GetRegisterAt(0)));
6711 caller_saves.Add(LocationFrom(calling_convention.GetRegisterAt(1)));
6712 LocationSummary* locations = codegen_->CreateThrowingSlowPathLocations(instruction, caller_saves);
6713
6714 HInstruction* index = instruction->InputAt(0);
6715 HInstruction* length = instruction->InputAt(1);
6716 // If both index and length are constants we can statically check the bounds. But if at least one
6717 // of them is not encodable ArmEncodableConstantOrRegister will create
6718 // Location::RequiresRegister() which is not desired to happen. Instead we create constant
6719 // locations.
6720 bool both_const = index->IsConstant() && length->IsConstant();
6721 locations->SetInAt(0, both_const
6722 ? Location::ConstantLocation(index->AsConstant())
6723 : ArmEncodableConstantOrRegister(index, CMP));
6724 locations->SetInAt(1, both_const
6725 ? Location::ConstantLocation(length->AsConstant())
6726 : ArmEncodableConstantOrRegister(length, CMP));
6727 }
6728
VisitBoundsCheck(HBoundsCheck * instruction)6729 void InstructionCodeGeneratorARMVIXL::VisitBoundsCheck(HBoundsCheck* instruction) {
6730 LocationSummary* locations = instruction->GetLocations();
6731 Location index_loc = locations->InAt(0);
6732 Location length_loc = locations->InAt(1);
6733
6734 if (length_loc.IsConstant()) {
6735 int32_t length = Int32ConstantFrom(length_loc);
6736 if (index_loc.IsConstant()) {
6737 // BCE will remove the bounds check if we are guaranteed to pass.
6738 int32_t index = Int32ConstantFrom(index_loc);
6739 if (index < 0 || index >= length) {
6740 SlowPathCodeARMVIXL* slow_path =
6741 new (codegen_->GetScopedAllocator()) BoundsCheckSlowPathARMVIXL(instruction);
6742 codegen_->AddSlowPath(slow_path);
6743 __ B(slow_path->GetEntryLabel());
6744 } else {
6745 // Some optimization after BCE may have generated this, and we should not
6746 // generate a bounds check if it is a valid range.
6747 }
6748 return;
6749 }
6750
6751 SlowPathCodeARMVIXL* slow_path =
6752 new (codegen_->GetScopedAllocator()) BoundsCheckSlowPathARMVIXL(instruction);
6753 __ Cmp(RegisterFrom(index_loc), length);
6754 codegen_->AddSlowPath(slow_path);
6755 __ B(hs, slow_path->GetEntryLabel());
6756 } else {
6757 SlowPathCodeARMVIXL* slow_path =
6758 new (codegen_->GetScopedAllocator()) BoundsCheckSlowPathARMVIXL(instruction);
6759 __ Cmp(RegisterFrom(length_loc), InputOperandAt(instruction, 0));
6760 codegen_->AddSlowPath(slow_path);
6761 __ B(ls, slow_path->GetEntryLabel());
6762 }
6763 }
6764
MarkGCCard(vixl32::Register temp,vixl32::Register card,vixl32::Register object,vixl32::Register value,bool can_be_null)6765 void CodeGeneratorARMVIXL::MarkGCCard(vixl32::Register temp,
6766 vixl32::Register card,
6767 vixl32::Register object,
6768 vixl32::Register value,
6769 bool can_be_null) {
6770 vixl32::Label is_null;
6771 if (can_be_null) {
6772 __ CompareAndBranchIfZero(value, &is_null);
6773 }
6774 // Load the address of the card table into `card`.
6775 GetAssembler()->LoadFromOffset(
6776 kLoadWord, card, tr, Thread::CardTableOffset<kArmPointerSize>().Int32Value());
6777 // Calculate the offset (in the card table) of the card corresponding to
6778 // `object`.
6779 __ Lsr(temp, object, Operand::From(gc::accounting::CardTable::kCardShift));
6780 // Write the `art::gc::accounting::CardTable::kCardDirty` value into the
6781 // `object`'s card.
6782 //
6783 // Register `card` contains the address of the card table. Note that the card
6784 // table's base is biased during its creation so that it always starts at an
6785 // address whose least-significant byte is equal to `kCardDirty` (see
6786 // art::gc::accounting::CardTable::Create). Therefore the STRB instruction
6787 // below writes the `kCardDirty` (byte) value into the `object`'s card
6788 // (located at `card + object >> kCardShift`).
6789 //
6790 // This dual use of the value in register `card` (1. to calculate the location
6791 // of the card to mark; and 2. to load the `kCardDirty` value) saves a load
6792 // (no need to explicitly load `kCardDirty` as an immediate value).
6793 __ Strb(card, MemOperand(card, temp));
6794 if (can_be_null) {
6795 __ Bind(&is_null);
6796 }
6797 }
6798
VisitParallelMove(HParallelMove * instruction ATTRIBUTE_UNUSED)6799 void LocationsBuilderARMVIXL::VisitParallelMove(HParallelMove* instruction ATTRIBUTE_UNUSED) {
6800 LOG(FATAL) << "Unreachable";
6801 }
6802
VisitParallelMove(HParallelMove * instruction)6803 void InstructionCodeGeneratorARMVIXL::VisitParallelMove(HParallelMove* instruction) {
6804 if (instruction->GetNext()->IsSuspendCheck() &&
6805 instruction->GetBlock()->GetLoopInformation() != nullptr) {
6806 HSuspendCheck* suspend_check = instruction->GetNext()->AsSuspendCheck();
6807 // The back edge will generate the suspend check.
6808 codegen_->ClearSpillSlotsFromLoopPhisInStackMap(suspend_check, instruction);
6809 }
6810
6811 codegen_->GetMoveResolver()->EmitNativeCode(instruction);
6812 }
6813
VisitSuspendCheck(HSuspendCheck * instruction)6814 void LocationsBuilderARMVIXL::VisitSuspendCheck(HSuspendCheck* instruction) {
6815 LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(
6816 instruction, LocationSummary::kCallOnSlowPath);
6817 locations->SetCustomSlowPathCallerSaves(RegisterSet::Empty()); // No caller-save registers.
6818 }
6819
VisitSuspendCheck(HSuspendCheck * instruction)6820 void InstructionCodeGeneratorARMVIXL::VisitSuspendCheck(HSuspendCheck* instruction) {
6821 HBasicBlock* block = instruction->GetBlock();
6822 if (block->GetLoopInformation() != nullptr) {
6823 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == instruction);
6824 // The back edge will generate the suspend check.
6825 return;
6826 }
6827 if (block->IsEntryBlock() && instruction->GetNext()->IsGoto()) {
6828 // The goto will generate the suspend check.
6829 return;
6830 }
6831 GenerateSuspendCheck(instruction, nullptr);
6832 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 13);
6833 }
6834
GenerateSuspendCheck(HSuspendCheck * instruction,HBasicBlock * successor)6835 void InstructionCodeGeneratorARMVIXL::GenerateSuspendCheck(HSuspendCheck* instruction,
6836 HBasicBlock* successor) {
6837 SuspendCheckSlowPathARMVIXL* slow_path =
6838 down_cast<SuspendCheckSlowPathARMVIXL*>(instruction->GetSlowPath());
6839 if (slow_path == nullptr) {
6840 slow_path =
6841 new (codegen_->GetScopedAllocator()) SuspendCheckSlowPathARMVIXL(instruction, successor);
6842 instruction->SetSlowPath(slow_path);
6843 codegen_->AddSlowPath(slow_path);
6844 if (successor != nullptr) {
6845 DCHECK(successor->IsLoopHeader());
6846 }
6847 } else {
6848 DCHECK_EQ(slow_path->GetSuccessor(), successor);
6849 }
6850
6851 UseScratchRegisterScope temps(GetVIXLAssembler());
6852 vixl32::Register temp = temps.Acquire();
6853 GetAssembler()->LoadFromOffset(
6854 kLoadUnsignedHalfword, temp, tr, Thread::ThreadFlagsOffset<kArmPointerSize>().Int32Value());
6855 if (successor == nullptr) {
6856 __ CompareAndBranchIfNonZero(temp, slow_path->GetEntryLabel());
6857 __ Bind(slow_path->GetReturnLabel());
6858 } else {
6859 __ CompareAndBranchIfZero(temp, codegen_->GetLabelOf(successor));
6860 __ B(slow_path->GetEntryLabel());
6861 }
6862 }
6863
GetAssembler() const6864 ArmVIXLAssembler* ParallelMoveResolverARMVIXL::GetAssembler() const {
6865 return codegen_->GetAssembler();
6866 }
6867
EmitMove(size_t index)6868 void ParallelMoveResolverARMVIXL::EmitMove(size_t index) {
6869 UseScratchRegisterScope temps(GetAssembler()->GetVIXLAssembler());
6870 MoveOperands* move = moves_[index];
6871 Location source = move->GetSource();
6872 Location destination = move->GetDestination();
6873
6874 if (source.IsRegister()) {
6875 if (destination.IsRegister()) {
6876 __ Mov(RegisterFrom(destination), RegisterFrom(source));
6877 } else if (destination.IsFpuRegister()) {
6878 __ Vmov(SRegisterFrom(destination), RegisterFrom(source));
6879 } else {
6880 DCHECK(destination.IsStackSlot());
6881 GetAssembler()->StoreToOffset(kStoreWord,
6882 RegisterFrom(source),
6883 sp,
6884 destination.GetStackIndex());
6885 }
6886 } else if (source.IsStackSlot()) {
6887 if (destination.IsRegister()) {
6888 GetAssembler()->LoadFromOffset(kLoadWord,
6889 RegisterFrom(destination),
6890 sp,
6891 source.GetStackIndex());
6892 } else if (destination.IsFpuRegister()) {
6893 GetAssembler()->LoadSFromOffset(SRegisterFrom(destination), sp, source.GetStackIndex());
6894 } else {
6895 DCHECK(destination.IsStackSlot());
6896 vixl32::Register temp = temps.Acquire();
6897 GetAssembler()->LoadFromOffset(kLoadWord, temp, sp, source.GetStackIndex());
6898 GetAssembler()->StoreToOffset(kStoreWord, temp, sp, destination.GetStackIndex());
6899 }
6900 } else if (source.IsFpuRegister()) {
6901 if (destination.IsRegister()) {
6902 __ Vmov(RegisterFrom(destination), SRegisterFrom(source));
6903 } else if (destination.IsFpuRegister()) {
6904 __ Vmov(SRegisterFrom(destination), SRegisterFrom(source));
6905 } else {
6906 DCHECK(destination.IsStackSlot());
6907 GetAssembler()->StoreSToOffset(SRegisterFrom(source), sp, destination.GetStackIndex());
6908 }
6909 } else if (source.IsDoubleStackSlot()) {
6910 if (destination.IsDoubleStackSlot()) {
6911 vixl32::DRegister temp = temps.AcquireD();
6912 GetAssembler()->LoadDFromOffset(temp, sp, source.GetStackIndex());
6913 GetAssembler()->StoreDToOffset(temp, sp, destination.GetStackIndex());
6914 } else if (destination.IsRegisterPair()) {
6915 DCHECK(ExpectedPairLayout(destination));
6916 GetAssembler()->LoadFromOffset(
6917 kLoadWordPair, LowRegisterFrom(destination), sp, source.GetStackIndex());
6918 } else {
6919 DCHECK(destination.IsFpuRegisterPair()) << destination;
6920 GetAssembler()->LoadDFromOffset(DRegisterFrom(destination), sp, source.GetStackIndex());
6921 }
6922 } else if (source.IsRegisterPair()) {
6923 if (destination.IsRegisterPair()) {
6924 __ Mov(LowRegisterFrom(destination), LowRegisterFrom(source));
6925 __ Mov(HighRegisterFrom(destination), HighRegisterFrom(source));
6926 } else if (destination.IsFpuRegisterPair()) {
6927 __ Vmov(DRegisterFrom(destination), LowRegisterFrom(source), HighRegisterFrom(source));
6928 } else {
6929 DCHECK(destination.IsDoubleStackSlot()) << destination;
6930 DCHECK(ExpectedPairLayout(source));
6931 GetAssembler()->StoreToOffset(kStoreWordPair,
6932 LowRegisterFrom(source),
6933 sp,
6934 destination.GetStackIndex());
6935 }
6936 } else if (source.IsFpuRegisterPair()) {
6937 if (destination.IsRegisterPair()) {
6938 __ Vmov(LowRegisterFrom(destination), HighRegisterFrom(destination), DRegisterFrom(source));
6939 } else if (destination.IsFpuRegisterPair()) {
6940 __ Vmov(DRegisterFrom(destination), DRegisterFrom(source));
6941 } else {
6942 DCHECK(destination.IsDoubleStackSlot()) << destination;
6943 GetAssembler()->StoreDToOffset(DRegisterFrom(source), sp, destination.GetStackIndex());
6944 }
6945 } else {
6946 DCHECK(source.IsConstant()) << source;
6947 HConstant* constant = source.GetConstant();
6948 if (constant->IsIntConstant() || constant->IsNullConstant()) {
6949 int32_t value = CodeGenerator::GetInt32ValueOf(constant);
6950 if (destination.IsRegister()) {
6951 __ Mov(RegisterFrom(destination), value);
6952 } else {
6953 DCHECK(destination.IsStackSlot());
6954 vixl32::Register temp = temps.Acquire();
6955 __ Mov(temp, value);
6956 GetAssembler()->StoreToOffset(kStoreWord, temp, sp, destination.GetStackIndex());
6957 }
6958 } else if (constant->IsLongConstant()) {
6959 int64_t value = Int64ConstantFrom(source);
6960 if (destination.IsRegisterPair()) {
6961 __ Mov(LowRegisterFrom(destination), Low32Bits(value));
6962 __ Mov(HighRegisterFrom(destination), High32Bits(value));
6963 } else {
6964 DCHECK(destination.IsDoubleStackSlot()) << destination;
6965 vixl32::Register temp = temps.Acquire();
6966 __ Mov(temp, Low32Bits(value));
6967 GetAssembler()->StoreToOffset(kStoreWord, temp, sp, destination.GetStackIndex());
6968 __ Mov(temp, High32Bits(value));
6969 GetAssembler()->StoreToOffset(kStoreWord,
6970 temp,
6971 sp,
6972 destination.GetHighStackIndex(kArmWordSize));
6973 }
6974 } else if (constant->IsDoubleConstant()) {
6975 double value = constant->AsDoubleConstant()->GetValue();
6976 if (destination.IsFpuRegisterPair()) {
6977 __ Vmov(DRegisterFrom(destination), value);
6978 } else {
6979 DCHECK(destination.IsDoubleStackSlot()) << destination;
6980 uint64_t int_value = bit_cast<uint64_t, double>(value);
6981 vixl32::Register temp = temps.Acquire();
6982 __ Mov(temp, Low32Bits(int_value));
6983 GetAssembler()->StoreToOffset(kStoreWord, temp, sp, destination.GetStackIndex());
6984 __ Mov(temp, High32Bits(int_value));
6985 GetAssembler()->StoreToOffset(kStoreWord,
6986 temp,
6987 sp,
6988 destination.GetHighStackIndex(kArmWordSize));
6989 }
6990 } else {
6991 DCHECK(constant->IsFloatConstant()) << constant->DebugName();
6992 float value = constant->AsFloatConstant()->GetValue();
6993 if (destination.IsFpuRegister()) {
6994 __ Vmov(SRegisterFrom(destination), value);
6995 } else {
6996 DCHECK(destination.IsStackSlot());
6997 vixl32::Register temp = temps.Acquire();
6998 __ Mov(temp, bit_cast<int32_t, float>(value));
6999 GetAssembler()->StoreToOffset(kStoreWord, temp, sp, destination.GetStackIndex());
7000 }
7001 }
7002 }
7003 }
7004
Exchange(vixl32::Register reg,int mem)7005 void ParallelMoveResolverARMVIXL::Exchange(vixl32::Register reg, int mem) {
7006 UseScratchRegisterScope temps(GetAssembler()->GetVIXLAssembler());
7007 vixl32::Register temp = temps.Acquire();
7008 __ Mov(temp, reg);
7009 GetAssembler()->LoadFromOffset(kLoadWord, reg, sp, mem);
7010 GetAssembler()->StoreToOffset(kStoreWord, temp, sp, mem);
7011 }
7012
Exchange(int mem1,int mem2)7013 void ParallelMoveResolverARMVIXL::Exchange(int mem1, int mem2) {
7014 // TODO(VIXL32): Double check the performance of this implementation.
7015 UseScratchRegisterScope temps(GetAssembler()->GetVIXLAssembler());
7016 vixl32::Register temp1 = temps.Acquire();
7017 ScratchRegisterScope ensure_scratch(
7018 this, temp1.GetCode(), r0.GetCode(), codegen_->GetNumberOfCoreRegisters());
7019 vixl32::Register temp2(ensure_scratch.GetRegister());
7020
7021 int stack_offset = ensure_scratch.IsSpilled() ? kArmWordSize : 0;
7022 GetAssembler()->LoadFromOffset(kLoadWord, temp1, sp, mem1 + stack_offset);
7023 GetAssembler()->LoadFromOffset(kLoadWord, temp2, sp, mem2 + stack_offset);
7024 GetAssembler()->StoreToOffset(kStoreWord, temp1, sp, mem2 + stack_offset);
7025 GetAssembler()->StoreToOffset(kStoreWord, temp2, sp, mem1 + stack_offset);
7026 }
7027
EmitSwap(size_t index)7028 void ParallelMoveResolverARMVIXL::EmitSwap(size_t index) {
7029 MoveOperands* move = moves_[index];
7030 Location source = move->GetSource();
7031 Location destination = move->GetDestination();
7032 UseScratchRegisterScope temps(GetAssembler()->GetVIXLAssembler());
7033
7034 if (source.IsRegister() && destination.IsRegister()) {
7035 vixl32::Register temp = temps.Acquire();
7036 DCHECK(!RegisterFrom(source).Is(temp));
7037 DCHECK(!RegisterFrom(destination).Is(temp));
7038 __ Mov(temp, RegisterFrom(destination));
7039 __ Mov(RegisterFrom(destination), RegisterFrom(source));
7040 __ Mov(RegisterFrom(source), temp);
7041 } else if (source.IsRegister() && destination.IsStackSlot()) {
7042 Exchange(RegisterFrom(source), destination.GetStackIndex());
7043 } else if (source.IsStackSlot() && destination.IsRegister()) {
7044 Exchange(RegisterFrom(destination), source.GetStackIndex());
7045 } else if (source.IsStackSlot() && destination.IsStackSlot()) {
7046 Exchange(source.GetStackIndex(), destination.GetStackIndex());
7047 } else if (source.IsFpuRegister() && destination.IsFpuRegister()) {
7048 vixl32::Register temp = temps.Acquire();
7049 __ Vmov(temp, SRegisterFrom(source));
7050 __ Vmov(SRegisterFrom(source), SRegisterFrom(destination));
7051 __ Vmov(SRegisterFrom(destination), temp);
7052 } else if (source.IsRegisterPair() && destination.IsRegisterPair()) {
7053 vixl32::DRegister temp = temps.AcquireD();
7054 __ Vmov(temp, LowRegisterFrom(source), HighRegisterFrom(source));
7055 __ Mov(LowRegisterFrom(source), LowRegisterFrom(destination));
7056 __ Mov(HighRegisterFrom(source), HighRegisterFrom(destination));
7057 __ Vmov(LowRegisterFrom(destination), HighRegisterFrom(destination), temp);
7058 } else if (source.IsRegisterPair() || destination.IsRegisterPair()) {
7059 vixl32::Register low_reg = LowRegisterFrom(source.IsRegisterPair() ? source : destination);
7060 int mem = source.IsRegisterPair() ? destination.GetStackIndex() : source.GetStackIndex();
7061 DCHECK(ExpectedPairLayout(source.IsRegisterPair() ? source : destination));
7062 vixl32::DRegister temp = temps.AcquireD();
7063 __ Vmov(temp, low_reg, vixl32::Register(low_reg.GetCode() + 1));
7064 GetAssembler()->LoadFromOffset(kLoadWordPair, low_reg, sp, mem);
7065 GetAssembler()->StoreDToOffset(temp, sp, mem);
7066 } else if (source.IsFpuRegisterPair() && destination.IsFpuRegisterPair()) {
7067 vixl32::DRegister first = DRegisterFrom(source);
7068 vixl32::DRegister second = DRegisterFrom(destination);
7069 vixl32::DRegister temp = temps.AcquireD();
7070 __ Vmov(temp, first);
7071 __ Vmov(first, second);
7072 __ Vmov(second, temp);
7073 } else if (source.IsFpuRegisterPair() || destination.IsFpuRegisterPair()) {
7074 vixl32::DRegister reg = source.IsFpuRegisterPair()
7075 ? DRegisterFrom(source)
7076 : DRegisterFrom(destination);
7077 int mem = source.IsFpuRegisterPair()
7078 ? destination.GetStackIndex()
7079 : source.GetStackIndex();
7080 vixl32::DRegister temp = temps.AcquireD();
7081 __ Vmov(temp, reg);
7082 GetAssembler()->LoadDFromOffset(reg, sp, mem);
7083 GetAssembler()->StoreDToOffset(temp, sp, mem);
7084 } else if (source.IsFpuRegister() || destination.IsFpuRegister()) {
7085 vixl32::SRegister reg = source.IsFpuRegister()
7086 ? SRegisterFrom(source)
7087 : SRegisterFrom(destination);
7088 int mem = source.IsFpuRegister()
7089 ? destination.GetStackIndex()
7090 : source.GetStackIndex();
7091 vixl32::Register temp = temps.Acquire();
7092 __ Vmov(temp, reg);
7093 GetAssembler()->LoadSFromOffset(reg, sp, mem);
7094 GetAssembler()->StoreToOffset(kStoreWord, temp, sp, mem);
7095 } else if (source.IsDoubleStackSlot() && destination.IsDoubleStackSlot()) {
7096 vixl32::DRegister temp1 = temps.AcquireD();
7097 vixl32::DRegister temp2 = temps.AcquireD();
7098 __ Vldr(temp1, MemOperand(sp, source.GetStackIndex()));
7099 __ Vldr(temp2, MemOperand(sp, destination.GetStackIndex()));
7100 __ Vstr(temp1, MemOperand(sp, destination.GetStackIndex()));
7101 __ Vstr(temp2, MemOperand(sp, source.GetStackIndex()));
7102 } else {
7103 LOG(FATAL) << "Unimplemented" << source << " <-> " << destination;
7104 }
7105 }
7106
SpillScratch(int reg)7107 void ParallelMoveResolverARMVIXL::SpillScratch(int reg) {
7108 __ Push(vixl32::Register(reg));
7109 }
7110
RestoreScratch(int reg)7111 void ParallelMoveResolverARMVIXL::RestoreScratch(int reg) {
7112 __ Pop(vixl32::Register(reg));
7113 }
7114
GetSupportedLoadClassKind(HLoadClass::LoadKind desired_class_load_kind)7115 HLoadClass::LoadKind CodeGeneratorARMVIXL::GetSupportedLoadClassKind(
7116 HLoadClass::LoadKind desired_class_load_kind) {
7117 switch (desired_class_load_kind) {
7118 case HLoadClass::LoadKind::kInvalid:
7119 LOG(FATAL) << "UNREACHABLE";
7120 UNREACHABLE();
7121 case HLoadClass::LoadKind::kReferrersClass:
7122 break;
7123 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
7124 case HLoadClass::LoadKind::kBootImageRelRo:
7125 case HLoadClass::LoadKind::kBssEntry:
7126 DCHECK(!Runtime::Current()->UseJitCompilation());
7127 break;
7128 case HLoadClass::LoadKind::kJitBootImageAddress:
7129 case HLoadClass::LoadKind::kJitTableAddress:
7130 DCHECK(Runtime::Current()->UseJitCompilation());
7131 break;
7132 case HLoadClass::LoadKind::kRuntimeCall:
7133 break;
7134 }
7135 return desired_class_load_kind;
7136 }
7137
VisitLoadClass(HLoadClass * cls)7138 void LocationsBuilderARMVIXL::VisitLoadClass(HLoadClass* cls) {
7139 HLoadClass::LoadKind load_kind = cls->GetLoadKind();
7140 if (load_kind == HLoadClass::LoadKind::kRuntimeCall) {
7141 InvokeRuntimeCallingConventionARMVIXL calling_convention;
7142 CodeGenerator::CreateLoadClassRuntimeCallLocationSummary(
7143 cls,
7144 LocationFrom(calling_convention.GetRegisterAt(0)),
7145 LocationFrom(r0));
7146 DCHECK(calling_convention.GetRegisterAt(0).Is(r0));
7147 return;
7148 }
7149 DCHECK(!cls->NeedsAccessCheck());
7150
7151 const bool requires_read_barrier = kEmitCompilerReadBarrier && !cls->IsInBootImage();
7152 LocationSummary::CallKind call_kind = (cls->NeedsEnvironment() || requires_read_barrier)
7153 ? LocationSummary::kCallOnSlowPath
7154 : LocationSummary::kNoCall;
7155 LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(cls, call_kind);
7156 if (kUseBakerReadBarrier && requires_read_barrier && !cls->NeedsEnvironment()) {
7157 locations->SetCustomSlowPathCallerSaves(RegisterSet::Empty()); // No caller-save registers.
7158 }
7159
7160 if (load_kind == HLoadClass::LoadKind::kReferrersClass) {
7161 locations->SetInAt(0, Location::RequiresRegister());
7162 }
7163 locations->SetOut(Location::RequiresRegister());
7164 if (load_kind == HLoadClass::LoadKind::kBssEntry) {
7165 if (!kUseReadBarrier || kUseBakerReadBarrier) {
7166 // Rely on the type resolution or initialization and marking to save everything we need.
7167 locations->SetCustomSlowPathCallerSaves(OneRegInReferenceOutSaveEverythingCallerSaves());
7168 } else {
7169 // For non-Baker read barrier we have a temp-clobbering call.
7170 }
7171 }
7172 }
7173
7174 // NO_THREAD_SAFETY_ANALYSIS as we manipulate handles whose internal object we know does not
7175 // move.
VisitLoadClass(HLoadClass * cls)7176 void InstructionCodeGeneratorARMVIXL::VisitLoadClass(HLoadClass* cls) NO_THREAD_SAFETY_ANALYSIS {
7177 HLoadClass::LoadKind load_kind = cls->GetLoadKind();
7178 if (load_kind == HLoadClass::LoadKind::kRuntimeCall) {
7179 codegen_->GenerateLoadClassRuntimeCall(cls);
7180 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 14);
7181 return;
7182 }
7183 DCHECK(!cls->NeedsAccessCheck());
7184
7185 LocationSummary* locations = cls->GetLocations();
7186 Location out_loc = locations->Out();
7187 vixl32::Register out = OutputRegister(cls);
7188
7189 const ReadBarrierOption read_barrier_option = cls->IsInBootImage()
7190 ? kWithoutReadBarrier
7191 : kCompilerReadBarrierOption;
7192 bool generate_null_check = false;
7193 switch (load_kind) {
7194 case HLoadClass::LoadKind::kReferrersClass: {
7195 DCHECK(!cls->CanCallRuntime());
7196 DCHECK(!cls->MustGenerateClinitCheck());
7197 // /* GcRoot<mirror::Class> */ out = current_method->declaring_class_
7198 vixl32::Register current_method = InputRegisterAt(cls, 0);
7199 codegen_->GenerateGcRootFieldLoad(cls,
7200 out_loc,
7201 current_method,
7202 ArtMethod::DeclaringClassOffset().Int32Value(),
7203 read_barrier_option);
7204 break;
7205 }
7206 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative: {
7207 DCHECK(codegen_->GetCompilerOptions().IsBootImage() ||
7208 codegen_->GetCompilerOptions().IsBootImageExtension());
7209 DCHECK_EQ(read_barrier_option, kWithoutReadBarrier);
7210 CodeGeneratorARMVIXL::PcRelativePatchInfo* labels =
7211 codegen_->NewBootImageTypePatch(cls->GetDexFile(), cls->GetTypeIndex());
7212 codegen_->EmitMovwMovtPlaceholder(labels, out);
7213 break;
7214 }
7215 case HLoadClass::LoadKind::kBootImageRelRo: {
7216 DCHECK(!codegen_->GetCompilerOptions().IsBootImage());
7217 CodeGeneratorARMVIXL::PcRelativePatchInfo* labels =
7218 codegen_->NewBootImageRelRoPatch(codegen_->GetBootImageOffset(cls));
7219 codegen_->EmitMovwMovtPlaceholder(labels, out);
7220 __ Ldr(out, MemOperand(out, /* offset= */ 0));
7221 break;
7222 }
7223 case HLoadClass::LoadKind::kBssEntry: {
7224 CodeGeneratorARMVIXL::PcRelativePatchInfo* labels =
7225 codegen_->NewTypeBssEntryPatch(cls->GetDexFile(), cls->GetTypeIndex());
7226 codegen_->EmitMovwMovtPlaceholder(labels, out);
7227 // All aligned loads are implicitly atomic consume operations on ARM.
7228 codegen_->GenerateGcRootFieldLoad(cls, out_loc, out, /* offset= */ 0, read_barrier_option);
7229 generate_null_check = true;
7230 break;
7231 }
7232 case HLoadClass::LoadKind::kJitBootImageAddress: {
7233 DCHECK_EQ(read_barrier_option, kWithoutReadBarrier);
7234 uint32_t address = reinterpret_cast32<uint32_t>(cls->GetClass().Get());
7235 DCHECK_NE(address, 0u);
7236 __ Ldr(out, codegen_->DeduplicateBootImageAddressLiteral(address));
7237 break;
7238 }
7239 case HLoadClass::LoadKind::kJitTableAddress: {
7240 __ Ldr(out, codegen_->DeduplicateJitClassLiteral(cls->GetDexFile(),
7241 cls->GetTypeIndex(),
7242 cls->GetClass()));
7243 // /* GcRoot<mirror::Class> */ out = *out
7244 codegen_->GenerateGcRootFieldLoad(cls, out_loc, out, /* offset= */ 0, read_barrier_option);
7245 break;
7246 }
7247 case HLoadClass::LoadKind::kRuntimeCall:
7248 case HLoadClass::LoadKind::kInvalid:
7249 LOG(FATAL) << "UNREACHABLE";
7250 UNREACHABLE();
7251 }
7252
7253 if (generate_null_check || cls->MustGenerateClinitCheck()) {
7254 DCHECK(cls->CanCallRuntime());
7255 LoadClassSlowPathARMVIXL* slow_path =
7256 new (codegen_->GetScopedAllocator()) LoadClassSlowPathARMVIXL(cls, cls);
7257 codegen_->AddSlowPath(slow_path);
7258 if (generate_null_check) {
7259 __ CompareAndBranchIfZero(out, slow_path->GetEntryLabel());
7260 }
7261 if (cls->MustGenerateClinitCheck()) {
7262 GenerateClassInitializationCheck(slow_path, out);
7263 } else {
7264 __ Bind(slow_path->GetExitLabel());
7265 }
7266 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 15);
7267 }
7268 }
7269
VisitLoadMethodHandle(HLoadMethodHandle * load)7270 void LocationsBuilderARMVIXL::VisitLoadMethodHandle(HLoadMethodHandle* load) {
7271 InvokeRuntimeCallingConventionARMVIXL calling_convention;
7272 Location location = LocationFrom(calling_convention.GetRegisterAt(0));
7273 CodeGenerator::CreateLoadMethodHandleRuntimeCallLocationSummary(load, location, location);
7274 }
7275
VisitLoadMethodHandle(HLoadMethodHandle * load)7276 void InstructionCodeGeneratorARMVIXL::VisitLoadMethodHandle(HLoadMethodHandle* load) {
7277 codegen_->GenerateLoadMethodHandleRuntimeCall(load);
7278 }
7279
VisitLoadMethodType(HLoadMethodType * load)7280 void LocationsBuilderARMVIXL::VisitLoadMethodType(HLoadMethodType* load) {
7281 InvokeRuntimeCallingConventionARMVIXL calling_convention;
7282 Location location = LocationFrom(calling_convention.GetRegisterAt(0));
7283 CodeGenerator::CreateLoadMethodTypeRuntimeCallLocationSummary(load, location, location);
7284 }
7285
VisitLoadMethodType(HLoadMethodType * load)7286 void InstructionCodeGeneratorARMVIXL::VisitLoadMethodType(HLoadMethodType* load) {
7287 codegen_->GenerateLoadMethodTypeRuntimeCall(load);
7288 }
7289
VisitClinitCheck(HClinitCheck * check)7290 void LocationsBuilderARMVIXL::VisitClinitCheck(HClinitCheck* check) {
7291 LocationSummary* locations =
7292 new (GetGraph()->GetAllocator()) LocationSummary(check, LocationSummary::kCallOnSlowPath);
7293 locations->SetInAt(0, Location::RequiresRegister());
7294 if (check->HasUses()) {
7295 locations->SetOut(Location::SameAsFirstInput());
7296 }
7297 // Rely on the type initialization to save everything we need.
7298 locations->SetCustomSlowPathCallerSaves(OneRegInReferenceOutSaveEverythingCallerSaves());
7299 }
7300
VisitClinitCheck(HClinitCheck * check)7301 void InstructionCodeGeneratorARMVIXL::VisitClinitCheck(HClinitCheck* check) {
7302 // We assume the class is not null.
7303 LoadClassSlowPathARMVIXL* slow_path =
7304 new (codegen_->GetScopedAllocator()) LoadClassSlowPathARMVIXL(check->GetLoadClass(), check);
7305 codegen_->AddSlowPath(slow_path);
7306 GenerateClassInitializationCheck(slow_path, InputRegisterAt(check, 0));
7307 }
7308
GenerateClassInitializationCheck(LoadClassSlowPathARMVIXL * slow_path,vixl32::Register class_reg)7309 void InstructionCodeGeneratorARMVIXL::GenerateClassInitializationCheck(
7310 LoadClassSlowPathARMVIXL* slow_path, vixl32::Register class_reg) {
7311 UseScratchRegisterScope temps(GetVIXLAssembler());
7312 vixl32::Register temp = temps.Acquire();
7313 constexpr size_t status_lsb_position = SubtypeCheckBits::BitStructSizeOf();
7314 constexpr uint32_t shifted_visibly_initialized_value =
7315 enum_cast<uint32_t>(ClassStatus::kVisiblyInitialized) << status_lsb_position;
7316
7317 const size_t status_offset = mirror::Class::StatusOffset().SizeValue();
7318 GetAssembler()->LoadFromOffset(kLoadWord, temp, class_reg, status_offset);
7319 __ Cmp(temp, shifted_visibly_initialized_value);
7320 __ B(lo, slow_path->GetEntryLabel());
7321 __ Bind(slow_path->GetExitLabel());
7322 }
7323
GenerateBitstringTypeCheckCompare(HTypeCheckInstruction * check,vixl32::Register temp,vixl32::FlagsUpdate flags_update)7324 void InstructionCodeGeneratorARMVIXL::GenerateBitstringTypeCheckCompare(
7325 HTypeCheckInstruction* check,
7326 vixl32::Register temp,
7327 vixl32::FlagsUpdate flags_update) {
7328 uint32_t path_to_root = check->GetBitstringPathToRoot();
7329 uint32_t mask = check->GetBitstringMask();
7330 DCHECK(IsPowerOfTwo(mask + 1));
7331 size_t mask_bits = WhichPowerOf2(mask + 1);
7332
7333 // Note that HInstanceOf shall check for zero value in `temp` but HCheckCast needs
7334 // the Z flag for BNE. This is indicated by the `flags_update` parameter.
7335 if (mask_bits == 16u) {
7336 // Load only the bitstring part of the status word.
7337 __ Ldrh(temp, MemOperand(temp, mirror::Class::StatusOffset().Int32Value()));
7338 // Check if the bitstring bits are equal to `path_to_root`.
7339 if (flags_update == SetFlags) {
7340 __ Cmp(temp, path_to_root);
7341 } else {
7342 __ Sub(temp, temp, path_to_root);
7343 }
7344 } else {
7345 // /* uint32_t */ temp = temp->status_
7346 __ Ldr(temp, MemOperand(temp, mirror::Class::StatusOffset().Int32Value()));
7347 if (GetAssembler()->ShifterOperandCanHold(SUB, path_to_root)) {
7348 // Compare the bitstring bits using SUB.
7349 __ Sub(temp, temp, path_to_root);
7350 // Shift out bits that do not contribute to the comparison.
7351 __ Lsl(flags_update, temp, temp, dchecked_integral_cast<uint32_t>(32u - mask_bits));
7352 } else if (IsUint<16>(path_to_root)) {
7353 if (temp.IsLow()) {
7354 // Note: Optimized for size but contains one more dependent instruction than necessary.
7355 // MOVW+SUB(register) would be 8 bytes unless we find a low-reg temporary but the
7356 // macro assembler would use the high reg IP for the constant by default.
7357 // Compare the bitstring bits using SUB.
7358 __ Sub(temp, temp, path_to_root & 0x00ffu); // 16-bit SUB (immediate) T2
7359 __ Sub(temp, temp, path_to_root & 0xff00u); // 32-bit SUB (immediate) T3
7360 // Shift out bits that do not contribute to the comparison.
7361 __ Lsl(flags_update, temp, temp, dchecked_integral_cast<uint32_t>(32u - mask_bits));
7362 } else {
7363 // Extract the bitstring bits.
7364 __ Ubfx(temp, temp, 0, mask_bits);
7365 // Check if the bitstring bits are equal to `path_to_root`.
7366 if (flags_update == SetFlags) {
7367 __ Cmp(temp, path_to_root);
7368 } else {
7369 __ Sub(temp, temp, path_to_root);
7370 }
7371 }
7372 } else {
7373 // Shift out bits that do not contribute to the comparison.
7374 __ Lsl(temp, temp, dchecked_integral_cast<uint32_t>(32u - mask_bits));
7375 // Check if the shifted bitstring bits are equal to `path_to_root << (32u - mask_bits)`.
7376 if (flags_update == SetFlags) {
7377 __ Cmp(temp, path_to_root << (32u - mask_bits));
7378 } else {
7379 __ Sub(temp, temp, path_to_root << (32u - mask_bits));
7380 }
7381 }
7382 }
7383 }
7384
GetSupportedLoadStringKind(HLoadString::LoadKind desired_string_load_kind)7385 HLoadString::LoadKind CodeGeneratorARMVIXL::GetSupportedLoadStringKind(
7386 HLoadString::LoadKind desired_string_load_kind) {
7387 switch (desired_string_load_kind) {
7388 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
7389 case HLoadString::LoadKind::kBootImageRelRo:
7390 case HLoadString::LoadKind::kBssEntry:
7391 DCHECK(!Runtime::Current()->UseJitCompilation());
7392 break;
7393 case HLoadString::LoadKind::kJitBootImageAddress:
7394 case HLoadString::LoadKind::kJitTableAddress:
7395 DCHECK(Runtime::Current()->UseJitCompilation());
7396 break;
7397 case HLoadString::LoadKind::kRuntimeCall:
7398 break;
7399 }
7400 return desired_string_load_kind;
7401 }
7402
VisitLoadString(HLoadString * load)7403 void LocationsBuilderARMVIXL::VisitLoadString(HLoadString* load) {
7404 LocationSummary::CallKind call_kind = CodeGenerator::GetLoadStringCallKind(load);
7405 LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(load, call_kind);
7406 HLoadString::LoadKind load_kind = load->GetLoadKind();
7407 if (load_kind == HLoadString::LoadKind::kRuntimeCall) {
7408 locations->SetOut(LocationFrom(r0));
7409 } else {
7410 locations->SetOut(Location::RequiresRegister());
7411 if (load_kind == HLoadString::LoadKind::kBssEntry) {
7412 if (!kUseReadBarrier || kUseBakerReadBarrier) {
7413 // Rely on the pResolveString and marking to save everything we need, including temps.
7414 locations->SetCustomSlowPathCallerSaves(OneRegInReferenceOutSaveEverythingCallerSaves());
7415 } else {
7416 // For non-Baker read barrier we have a temp-clobbering call.
7417 }
7418 }
7419 }
7420 }
7421
7422 // NO_THREAD_SAFETY_ANALYSIS as we manipulate handles whose internal object we know does not
7423 // move.
VisitLoadString(HLoadString * load)7424 void InstructionCodeGeneratorARMVIXL::VisitLoadString(HLoadString* load) NO_THREAD_SAFETY_ANALYSIS {
7425 LocationSummary* locations = load->GetLocations();
7426 Location out_loc = locations->Out();
7427 vixl32::Register out = OutputRegister(load);
7428 HLoadString::LoadKind load_kind = load->GetLoadKind();
7429
7430 switch (load_kind) {
7431 case HLoadString::LoadKind::kBootImageLinkTimePcRelative: {
7432 DCHECK(codegen_->GetCompilerOptions().IsBootImage() ||
7433 codegen_->GetCompilerOptions().IsBootImageExtension());
7434 CodeGeneratorARMVIXL::PcRelativePatchInfo* labels =
7435 codegen_->NewBootImageStringPatch(load->GetDexFile(), load->GetStringIndex());
7436 codegen_->EmitMovwMovtPlaceholder(labels, out);
7437 return;
7438 }
7439 case HLoadString::LoadKind::kBootImageRelRo: {
7440 DCHECK(!codegen_->GetCompilerOptions().IsBootImage());
7441 CodeGeneratorARMVIXL::PcRelativePatchInfo* labels =
7442 codegen_->NewBootImageRelRoPatch(codegen_->GetBootImageOffset(load));
7443 codegen_->EmitMovwMovtPlaceholder(labels, out);
7444 __ Ldr(out, MemOperand(out, /* offset= */ 0));
7445 return;
7446 }
7447 case HLoadString::LoadKind::kBssEntry: {
7448 CodeGeneratorARMVIXL::PcRelativePatchInfo* labels =
7449 codegen_->NewStringBssEntryPatch(load->GetDexFile(), load->GetStringIndex());
7450 codegen_->EmitMovwMovtPlaceholder(labels, out);
7451 // All aligned loads are implicitly atomic consume operations on ARM.
7452 codegen_->GenerateGcRootFieldLoad(
7453 load, out_loc, out, /* offset= */ 0, kCompilerReadBarrierOption);
7454 LoadStringSlowPathARMVIXL* slow_path =
7455 new (codegen_->GetScopedAllocator()) LoadStringSlowPathARMVIXL(load);
7456 codegen_->AddSlowPath(slow_path);
7457 __ CompareAndBranchIfZero(out, slow_path->GetEntryLabel());
7458 __ Bind(slow_path->GetExitLabel());
7459 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 16);
7460 return;
7461 }
7462 case HLoadString::LoadKind::kJitBootImageAddress: {
7463 uint32_t address = reinterpret_cast32<uint32_t>(load->GetString().Get());
7464 DCHECK_NE(address, 0u);
7465 __ Ldr(out, codegen_->DeduplicateBootImageAddressLiteral(address));
7466 return;
7467 }
7468 case HLoadString::LoadKind::kJitTableAddress: {
7469 __ Ldr(out, codegen_->DeduplicateJitStringLiteral(load->GetDexFile(),
7470 load->GetStringIndex(),
7471 load->GetString()));
7472 // /* GcRoot<mirror::String> */ out = *out
7473 codegen_->GenerateGcRootFieldLoad(
7474 load, out_loc, out, /* offset= */ 0, kCompilerReadBarrierOption);
7475 return;
7476 }
7477 default:
7478 break;
7479 }
7480
7481 // TODO: Re-add the compiler code to do string dex cache lookup again.
7482 DCHECK_EQ(load->GetLoadKind(), HLoadString::LoadKind::kRuntimeCall);
7483 InvokeRuntimeCallingConventionARMVIXL calling_convention;
7484 __ Mov(calling_convention.GetRegisterAt(0), load->GetStringIndex().index_);
7485 codegen_->InvokeRuntime(kQuickResolveString, load, load->GetDexPc());
7486 CheckEntrypointTypes<kQuickResolveString, void*, uint32_t>();
7487 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 17);
7488 }
7489
GetExceptionTlsOffset()7490 static int32_t GetExceptionTlsOffset() {
7491 return Thread::ExceptionOffset<kArmPointerSize>().Int32Value();
7492 }
7493
VisitLoadException(HLoadException * load)7494 void LocationsBuilderARMVIXL::VisitLoadException(HLoadException* load) {
7495 LocationSummary* locations =
7496 new (GetGraph()->GetAllocator()) LocationSummary(load, LocationSummary::kNoCall);
7497 locations->SetOut(Location::RequiresRegister());
7498 }
7499
VisitLoadException(HLoadException * load)7500 void InstructionCodeGeneratorARMVIXL::VisitLoadException(HLoadException* load) {
7501 vixl32::Register out = OutputRegister(load);
7502 GetAssembler()->LoadFromOffset(kLoadWord, out, tr, GetExceptionTlsOffset());
7503 }
7504
7505
VisitClearException(HClearException * clear)7506 void LocationsBuilderARMVIXL::VisitClearException(HClearException* clear) {
7507 new (GetGraph()->GetAllocator()) LocationSummary(clear, LocationSummary::kNoCall);
7508 }
7509
VisitClearException(HClearException * clear ATTRIBUTE_UNUSED)7510 void InstructionCodeGeneratorARMVIXL::VisitClearException(HClearException* clear ATTRIBUTE_UNUSED) {
7511 UseScratchRegisterScope temps(GetVIXLAssembler());
7512 vixl32::Register temp = temps.Acquire();
7513 __ Mov(temp, 0);
7514 GetAssembler()->StoreToOffset(kStoreWord, temp, tr, GetExceptionTlsOffset());
7515 }
7516
VisitThrow(HThrow * instruction)7517 void LocationsBuilderARMVIXL::VisitThrow(HThrow* instruction) {
7518 LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(
7519 instruction, LocationSummary::kCallOnMainOnly);
7520 InvokeRuntimeCallingConventionARMVIXL calling_convention;
7521 locations->SetInAt(0, LocationFrom(calling_convention.GetRegisterAt(0)));
7522 }
7523
VisitThrow(HThrow * instruction)7524 void InstructionCodeGeneratorARMVIXL::VisitThrow(HThrow* instruction) {
7525 codegen_->InvokeRuntime(kQuickDeliverException, instruction, instruction->GetDexPc());
7526 CheckEntrypointTypes<kQuickDeliverException, void, mirror::Object*>();
7527 }
7528
7529 // Temp is used for read barrier.
NumberOfInstanceOfTemps(TypeCheckKind type_check_kind)7530 static size_t NumberOfInstanceOfTemps(TypeCheckKind type_check_kind) {
7531 if (kEmitCompilerReadBarrier &&
7532 (kUseBakerReadBarrier ||
7533 type_check_kind == TypeCheckKind::kAbstractClassCheck ||
7534 type_check_kind == TypeCheckKind::kClassHierarchyCheck ||
7535 type_check_kind == TypeCheckKind::kArrayObjectCheck)) {
7536 return 1;
7537 }
7538 return 0;
7539 }
7540
7541 // Interface case has 3 temps, one for holding the number of interfaces, one for the current
7542 // interface pointer, one for loading the current interface.
7543 // The other checks have one temp for loading the object's class.
NumberOfCheckCastTemps(TypeCheckKind type_check_kind)7544 static size_t NumberOfCheckCastTemps(TypeCheckKind type_check_kind) {
7545 if (type_check_kind == TypeCheckKind::kInterfaceCheck) {
7546 return 3;
7547 }
7548 return 1 + NumberOfInstanceOfTemps(type_check_kind);
7549 }
7550
VisitInstanceOf(HInstanceOf * instruction)7551 void LocationsBuilderARMVIXL::VisitInstanceOf(HInstanceOf* instruction) {
7552 LocationSummary::CallKind call_kind = LocationSummary::kNoCall;
7553 TypeCheckKind type_check_kind = instruction->GetTypeCheckKind();
7554 bool baker_read_barrier_slow_path = false;
7555 switch (type_check_kind) {
7556 case TypeCheckKind::kExactCheck:
7557 case TypeCheckKind::kAbstractClassCheck:
7558 case TypeCheckKind::kClassHierarchyCheck:
7559 case TypeCheckKind::kArrayObjectCheck: {
7560 bool needs_read_barrier = CodeGenerator::InstanceOfNeedsReadBarrier(instruction);
7561 call_kind = needs_read_barrier ? LocationSummary::kCallOnSlowPath : LocationSummary::kNoCall;
7562 baker_read_barrier_slow_path = kUseBakerReadBarrier && needs_read_barrier;
7563 break;
7564 }
7565 case TypeCheckKind::kArrayCheck:
7566 case TypeCheckKind::kUnresolvedCheck:
7567 case TypeCheckKind::kInterfaceCheck:
7568 call_kind = LocationSummary::kCallOnSlowPath;
7569 break;
7570 case TypeCheckKind::kBitstringCheck:
7571 break;
7572 }
7573
7574 LocationSummary* locations =
7575 new (GetGraph()->GetAllocator()) LocationSummary(instruction, call_kind);
7576 if (baker_read_barrier_slow_path) {
7577 locations->SetCustomSlowPathCallerSaves(RegisterSet::Empty()); // No caller-save registers.
7578 }
7579 locations->SetInAt(0, Location::RequiresRegister());
7580 if (type_check_kind == TypeCheckKind::kBitstringCheck) {
7581 locations->SetInAt(1, Location::ConstantLocation(instruction->InputAt(1)->AsConstant()));
7582 locations->SetInAt(2, Location::ConstantLocation(instruction->InputAt(2)->AsConstant()));
7583 locations->SetInAt(3, Location::ConstantLocation(instruction->InputAt(3)->AsConstant()));
7584 } else {
7585 locations->SetInAt(1, Location::RequiresRegister());
7586 }
7587 // The "out" register is used as a temporary, so it overlaps with the inputs.
7588 // Note that TypeCheckSlowPathARM uses this register too.
7589 locations->SetOut(Location::RequiresRegister(), Location::kOutputOverlap);
7590 locations->AddRegisterTemps(NumberOfInstanceOfTemps(type_check_kind));
7591 }
7592
VisitInstanceOf(HInstanceOf * instruction)7593 void InstructionCodeGeneratorARMVIXL::VisitInstanceOf(HInstanceOf* instruction) {
7594 TypeCheckKind type_check_kind = instruction->GetTypeCheckKind();
7595 LocationSummary* locations = instruction->GetLocations();
7596 Location obj_loc = locations->InAt(0);
7597 vixl32::Register obj = InputRegisterAt(instruction, 0);
7598 vixl32::Register cls = (type_check_kind == TypeCheckKind::kBitstringCheck)
7599 ? vixl32::Register()
7600 : InputRegisterAt(instruction, 1);
7601 Location out_loc = locations->Out();
7602 vixl32::Register out = OutputRegister(instruction);
7603 const size_t num_temps = NumberOfInstanceOfTemps(type_check_kind);
7604 DCHECK_LE(num_temps, 1u);
7605 Location maybe_temp_loc = (num_temps >= 1) ? locations->GetTemp(0) : Location::NoLocation();
7606 uint32_t class_offset = mirror::Object::ClassOffset().Int32Value();
7607 uint32_t super_offset = mirror::Class::SuperClassOffset().Int32Value();
7608 uint32_t component_offset = mirror::Class::ComponentTypeOffset().Int32Value();
7609 uint32_t primitive_offset = mirror::Class::PrimitiveTypeOffset().Int32Value();
7610 vixl32::Label done;
7611 vixl32::Label* const final_label = codegen_->GetFinalLabel(instruction, &done);
7612 SlowPathCodeARMVIXL* slow_path = nullptr;
7613
7614 // Return 0 if `obj` is null.
7615 // avoid null check if we know obj is not null.
7616 if (instruction->MustDoNullCheck()) {
7617 DCHECK(!out.Is(obj));
7618 __ Mov(out, 0);
7619 __ CompareAndBranchIfZero(obj, final_label, /* is_far_target= */ false);
7620 }
7621
7622 switch (type_check_kind) {
7623 case TypeCheckKind::kExactCheck: {
7624 ReadBarrierOption read_barrier_option =
7625 CodeGenerator::ReadBarrierOptionForInstanceOf(instruction);
7626 // /* HeapReference<Class> */ out = obj->klass_
7627 GenerateReferenceLoadTwoRegisters(instruction,
7628 out_loc,
7629 obj_loc,
7630 class_offset,
7631 maybe_temp_loc,
7632 read_barrier_option);
7633 // Classes must be equal for the instanceof to succeed.
7634 __ Cmp(out, cls);
7635 // We speculatively set the result to false without changing the condition
7636 // flags, which allows us to avoid some branching later.
7637 __ Mov(LeaveFlags, out, 0);
7638
7639 // Since IT blocks longer than a 16-bit instruction are deprecated by ARMv8,
7640 // we check that the output is in a low register, so that a 16-bit MOV
7641 // encoding can be used.
7642 if (out.IsLow()) {
7643 // We use the scope because of the IT block that follows.
7644 ExactAssemblyScope guard(GetVIXLAssembler(),
7645 2 * vixl32::k16BitT32InstructionSizeInBytes,
7646 CodeBufferCheckScope::kExactSize);
7647
7648 __ it(eq);
7649 __ mov(eq, out, 1);
7650 } else {
7651 __ B(ne, final_label, /* is_far_target= */ false);
7652 __ Mov(out, 1);
7653 }
7654
7655 break;
7656 }
7657
7658 case TypeCheckKind::kAbstractClassCheck: {
7659 ReadBarrierOption read_barrier_option =
7660 CodeGenerator::ReadBarrierOptionForInstanceOf(instruction);
7661 // /* HeapReference<Class> */ out = obj->klass_
7662 GenerateReferenceLoadTwoRegisters(instruction,
7663 out_loc,
7664 obj_loc,
7665 class_offset,
7666 maybe_temp_loc,
7667 read_barrier_option);
7668 // If the class is abstract, we eagerly fetch the super class of the
7669 // object to avoid doing a comparison we know will fail.
7670 vixl32::Label loop;
7671 __ Bind(&loop);
7672 // /* HeapReference<Class> */ out = out->super_class_
7673 GenerateReferenceLoadOneRegister(instruction,
7674 out_loc,
7675 super_offset,
7676 maybe_temp_loc,
7677 read_barrier_option);
7678 // If `out` is null, we use it for the result, and jump to the final label.
7679 __ CompareAndBranchIfZero(out, final_label, /* is_far_target= */ false);
7680 __ Cmp(out, cls);
7681 __ B(ne, &loop, /* is_far_target= */ false);
7682 __ Mov(out, 1);
7683 break;
7684 }
7685
7686 case TypeCheckKind::kClassHierarchyCheck: {
7687 ReadBarrierOption read_barrier_option =
7688 CodeGenerator::ReadBarrierOptionForInstanceOf(instruction);
7689 // /* HeapReference<Class> */ out = obj->klass_
7690 GenerateReferenceLoadTwoRegisters(instruction,
7691 out_loc,
7692 obj_loc,
7693 class_offset,
7694 maybe_temp_loc,
7695 read_barrier_option);
7696 // Walk over the class hierarchy to find a match.
7697 vixl32::Label loop, success;
7698 __ Bind(&loop);
7699 __ Cmp(out, cls);
7700 __ B(eq, &success, /* is_far_target= */ false);
7701 // /* HeapReference<Class> */ out = out->super_class_
7702 GenerateReferenceLoadOneRegister(instruction,
7703 out_loc,
7704 super_offset,
7705 maybe_temp_loc,
7706 read_barrier_option);
7707 // This is essentially a null check, but it sets the condition flags to the
7708 // proper value for the code that follows the loop, i.e. not `eq`.
7709 __ Cmp(out, 1);
7710 __ B(hs, &loop, /* is_far_target= */ false);
7711
7712 // Since IT blocks longer than a 16-bit instruction are deprecated by ARMv8,
7713 // we check that the output is in a low register, so that a 16-bit MOV
7714 // encoding can be used.
7715 if (out.IsLow()) {
7716 // If `out` is null, we use it for the result, and the condition flags
7717 // have already been set to `ne`, so the IT block that comes afterwards
7718 // (and which handles the successful case) turns into a NOP (instead of
7719 // overwriting `out`).
7720 __ Bind(&success);
7721
7722 // We use the scope because of the IT block that follows.
7723 ExactAssemblyScope guard(GetVIXLAssembler(),
7724 2 * vixl32::k16BitT32InstructionSizeInBytes,
7725 CodeBufferCheckScope::kExactSize);
7726
7727 // There is only one branch to the `success` label (which is bound to this
7728 // IT block), and it has the same condition, `eq`, so in that case the MOV
7729 // is executed.
7730 __ it(eq);
7731 __ mov(eq, out, 1);
7732 } else {
7733 // If `out` is null, we use it for the result, and jump to the final label.
7734 __ B(final_label);
7735 __ Bind(&success);
7736 __ Mov(out, 1);
7737 }
7738
7739 break;
7740 }
7741
7742 case TypeCheckKind::kArrayObjectCheck: {
7743 ReadBarrierOption read_barrier_option =
7744 CodeGenerator::ReadBarrierOptionForInstanceOf(instruction);
7745 // /* HeapReference<Class> */ out = obj->klass_
7746 GenerateReferenceLoadTwoRegisters(instruction,
7747 out_loc,
7748 obj_loc,
7749 class_offset,
7750 maybe_temp_loc,
7751 read_barrier_option);
7752 // Do an exact check.
7753 vixl32::Label exact_check;
7754 __ Cmp(out, cls);
7755 __ B(eq, &exact_check, /* is_far_target= */ false);
7756 // Otherwise, we need to check that the object's class is a non-primitive array.
7757 // /* HeapReference<Class> */ out = out->component_type_
7758 GenerateReferenceLoadOneRegister(instruction,
7759 out_loc,
7760 component_offset,
7761 maybe_temp_loc,
7762 read_barrier_option);
7763 // If `out` is null, we use it for the result, and jump to the final label.
7764 __ CompareAndBranchIfZero(out, final_label, /* is_far_target= */ false);
7765 GetAssembler()->LoadFromOffset(kLoadUnsignedHalfword, out, out, primitive_offset);
7766 static_assert(Primitive::kPrimNot == 0, "Expected 0 for kPrimNot");
7767 __ Cmp(out, 0);
7768 // We speculatively set the result to false without changing the condition
7769 // flags, which allows us to avoid some branching later.
7770 __ Mov(LeaveFlags, out, 0);
7771
7772 // Since IT blocks longer than a 16-bit instruction are deprecated by ARMv8,
7773 // we check that the output is in a low register, so that a 16-bit MOV
7774 // encoding can be used.
7775 if (out.IsLow()) {
7776 __ Bind(&exact_check);
7777
7778 // We use the scope because of the IT block that follows.
7779 ExactAssemblyScope guard(GetVIXLAssembler(),
7780 2 * vixl32::k16BitT32InstructionSizeInBytes,
7781 CodeBufferCheckScope::kExactSize);
7782
7783 __ it(eq);
7784 __ mov(eq, out, 1);
7785 } else {
7786 __ B(ne, final_label, /* is_far_target= */ false);
7787 __ Bind(&exact_check);
7788 __ Mov(out, 1);
7789 }
7790
7791 break;
7792 }
7793
7794 case TypeCheckKind::kArrayCheck: {
7795 // No read barrier since the slow path will retry upon failure.
7796 // /* HeapReference<Class> */ out = obj->klass_
7797 GenerateReferenceLoadTwoRegisters(instruction,
7798 out_loc,
7799 obj_loc,
7800 class_offset,
7801 maybe_temp_loc,
7802 kWithoutReadBarrier);
7803 __ Cmp(out, cls);
7804 DCHECK(locations->OnlyCallsOnSlowPath());
7805 slow_path = new (codegen_->GetScopedAllocator()) TypeCheckSlowPathARMVIXL(
7806 instruction, /* is_fatal= */ false);
7807 codegen_->AddSlowPath(slow_path);
7808 __ B(ne, slow_path->GetEntryLabel());
7809 __ Mov(out, 1);
7810 break;
7811 }
7812
7813 case TypeCheckKind::kUnresolvedCheck:
7814 case TypeCheckKind::kInterfaceCheck: {
7815 // Note that we indeed only call on slow path, but we always go
7816 // into the slow path for the unresolved and interface check
7817 // cases.
7818 //
7819 // We cannot directly call the InstanceofNonTrivial runtime
7820 // entry point without resorting to a type checking slow path
7821 // here (i.e. by calling InvokeRuntime directly), as it would
7822 // require to assign fixed registers for the inputs of this
7823 // HInstanceOf instruction (following the runtime calling
7824 // convention), which might be cluttered by the potential first
7825 // read barrier emission at the beginning of this method.
7826 //
7827 // TODO: Introduce a new runtime entry point taking the object
7828 // to test (instead of its class) as argument, and let it deal
7829 // with the read barrier issues. This will let us refactor this
7830 // case of the `switch` code as it was previously (with a direct
7831 // call to the runtime not using a type checking slow path).
7832 // This should also be beneficial for the other cases above.
7833 DCHECK(locations->OnlyCallsOnSlowPath());
7834 slow_path = new (codegen_->GetScopedAllocator()) TypeCheckSlowPathARMVIXL(
7835 instruction, /* is_fatal= */ false);
7836 codegen_->AddSlowPath(slow_path);
7837 __ B(slow_path->GetEntryLabel());
7838 break;
7839 }
7840
7841 case TypeCheckKind::kBitstringCheck: {
7842 // /* HeapReference<Class> */ temp = obj->klass_
7843 GenerateReferenceLoadTwoRegisters(instruction,
7844 out_loc,
7845 obj_loc,
7846 class_offset,
7847 maybe_temp_loc,
7848 kWithoutReadBarrier);
7849
7850 GenerateBitstringTypeCheckCompare(instruction, out, DontCare);
7851 // If `out` is a low reg and we would have another low reg temp, we could
7852 // optimize this as RSBS+ADC, see GenerateConditionWithZero().
7853 //
7854 // Also, in some cases when `out` is a low reg and we're loading a constant to IP
7855 // it would make sense to use CMP+MOV+IT+MOV instead of SUB+CLZ+LSR as the code size
7856 // would be the same and we would have fewer direct data dependencies.
7857 codegen_->GenerateConditionWithZero(kCondEQ, out, out); // CLZ+LSR
7858 break;
7859 }
7860 }
7861
7862 if (done.IsReferenced()) {
7863 __ Bind(&done);
7864 }
7865
7866 if (slow_path != nullptr) {
7867 __ Bind(slow_path->GetExitLabel());
7868 }
7869 }
7870
VisitCheckCast(HCheckCast * instruction)7871 void LocationsBuilderARMVIXL::VisitCheckCast(HCheckCast* instruction) {
7872 TypeCheckKind type_check_kind = instruction->GetTypeCheckKind();
7873 LocationSummary::CallKind call_kind = CodeGenerator::GetCheckCastCallKind(instruction);
7874 LocationSummary* locations =
7875 new (GetGraph()->GetAllocator()) LocationSummary(instruction, call_kind);
7876 locations->SetInAt(0, Location::RequiresRegister());
7877 if (type_check_kind == TypeCheckKind::kBitstringCheck) {
7878 locations->SetInAt(1, Location::ConstantLocation(instruction->InputAt(1)->AsConstant()));
7879 locations->SetInAt(2, Location::ConstantLocation(instruction->InputAt(2)->AsConstant()));
7880 locations->SetInAt(3, Location::ConstantLocation(instruction->InputAt(3)->AsConstant()));
7881 } else {
7882 locations->SetInAt(1, Location::RequiresRegister());
7883 }
7884 locations->AddRegisterTemps(NumberOfCheckCastTemps(type_check_kind));
7885 }
7886
VisitCheckCast(HCheckCast * instruction)7887 void InstructionCodeGeneratorARMVIXL::VisitCheckCast(HCheckCast* instruction) {
7888 TypeCheckKind type_check_kind = instruction->GetTypeCheckKind();
7889 LocationSummary* locations = instruction->GetLocations();
7890 Location obj_loc = locations->InAt(0);
7891 vixl32::Register obj = InputRegisterAt(instruction, 0);
7892 vixl32::Register cls = (type_check_kind == TypeCheckKind::kBitstringCheck)
7893 ? vixl32::Register()
7894 : InputRegisterAt(instruction, 1);
7895 Location temp_loc = locations->GetTemp(0);
7896 vixl32::Register temp = RegisterFrom(temp_loc);
7897 const size_t num_temps = NumberOfCheckCastTemps(type_check_kind);
7898 DCHECK_LE(num_temps, 3u);
7899 Location maybe_temp2_loc = (num_temps >= 2) ? locations->GetTemp(1) : Location::NoLocation();
7900 Location maybe_temp3_loc = (num_temps >= 3) ? locations->GetTemp(2) : Location::NoLocation();
7901 const uint32_t class_offset = mirror::Object::ClassOffset().Int32Value();
7902 const uint32_t super_offset = mirror::Class::SuperClassOffset().Int32Value();
7903 const uint32_t component_offset = mirror::Class::ComponentTypeOffset().Int32Value();
7904 const uint32_t primitive_offset = mirror::Class::PrimitiveTypeOffset().Int32Value();
7905 const uint32_t iftable_offset = mirror::Class::IfTableOffset().Uint32Value();
7906 const uint32_t array_length_offset = mirror::Array::LengthOffset().Uint32Value();
7907 const uint32_t object_array_data_offset =
7908 mirror::Array::DataOffset(kHeapReferenceSize).Uint32Value();
7909
7910 bool is_type_check_slow_path_fatal = CodeGenerator::IsTypeCheckSlowPathFatal(instruction);
7911 SlowPathCodeARMVIXL* type_check_slow_path =
7912 new (codegen_->GetScopedAllocator()) TypeCheckSlowPathARMVIXL(
7913 instruction, is_type_check_slow_path_fatal);
7914 codegen_->AddSlowPath(type_check_slow_path);
7915
7916 vixl32::Label done;
7917 vixl32::Label* final_label = codegen_->GetFinalLabel(instruction, &done);
7918 // Avoid null check if we know obj is not null.
7919 if (instruction->MustDoNullCheck()) {
7920 __ CompareAndBranchIfZero(obj, final_label, /* is_far_target= */ false);
7921 }
7922
7923 switch (type_check_kind) {
7924 case TypeCheckKind::kExactCheck:
7925 case TypeCheckKind::kArrayCheck: {
7926 // /* HeapReference<Class> */ temp = obj->klass_
7927 GenerateReferenceLoadTwoRegisters(instruction,
7928 temp_loc,
7929 obj_loc,
7930 class_offset,
7931 maybe_temp2_loc,
7932 kWithoutReadBarrier);
7933
7934 __ Cmp(temp, cls);
7935 // Jump to slow path for throwing the exception or doing a
7936 // more involved array check.
7937 __ B(ne, type_check_slow_path->GetEntryLabel());
7938 break;
7939 }
7940
7941 case TypeCheckKind::kAbstractClassCheck: {
7942 // /* HeapReference<Class> */ temp = obj->klass_
7943 GenerateReferenceLoadTwoRegisters(instruction,
7944 temp_loc,
7945 obj_loc,
7946 class_offset,
7947 maybe_temp2_loc,
7948 kWithoutReadBarrier);
7949
7950 // If the class is abstract, we eagerly fetch the super class of the
7951 // object to avoid doing a comparison we know will fail.
7952 vixl32::Label loop;
7953 __ Bind(&loop);
7954 // /* HeapReference<Class> */ temp = temp->super_class_
7955 GenerateReferenceLoadOneRegister(instruction,
7956 temp_loc,
7957 super_offset,
7958 maybe_temp2_loc,
7959 kWithoutReadBarrier);
7960
7961 // If the class reference currently in `temp` is null, jump to the slow path to throw the
7962 // exception.
7963 __ CompareAndBranchIfZero(temp, type_check_slow_path->GetEntryLabel());
7964
7965 // Otherwise, compare the classes.
7966 __ Cmp(temp, cls);
7967 __ B(ne, &loop, /* is_far_target= */ false);
7968 break;
7969 }
7970
7971 case TypeCheckKind::kClassHierarchyCheck: {
7972 // /* HeapReference<Class> */ temp = obj->klass_
7973 GenerateReferenceLoadTwoRegisters(instruction,
7974 temp_loc,
7975 obj_loc,
7976 class_offset,
7977 maybe_temp2_loc,
7978 kWithoutReadBarrier);
7979
7980 // Walk over the class hierarchy to find a match.
7981 vixl32::Label loop;
7982 __ Bind(&loop);
7983 __ Cmp(temp, cls);
7984 __ B(eq, final_label, /* is_far_target= */ false);
7985
7986 // /* HeapReference<Class> */ temp = temp->super_class_
7987 GenerateReferenceLoadOneRegister(instruction,
7988 temp_loc,
7989 super_offset,
7990 maybe_temp2_loc,
7991 kWithoutReadBarrier);
7992
7993 // If the class reference currently in `temp` is null, jump to the slow path to throw the
7994 // exception.
7995 __ CompareAndBranchIfZero(temp, type_check_slow_path->GetEntryLabel());
7996 // Otherwise, jump to the beginning of the loop.
7997 __ B(&loop);
7998 break;
7999 }
8000
8001 case TypeCheckKind::kArrayObjectCheck: {
8002 // /* HeapReference<Class> */ temp = obj->klass_
8003 GenerateReferenceLoadTwoRegisters(instruction,
8004 temp_loc,
8005 obj_loc,
8006 class_offset,
8007 maybe_temp2_loc,
8008 kWithoutReadBarrier);
8009
8010 // Do an exact check.
8011 __ Cmp(temp, cls);
8012 __ B(eq, final_label, /* is_far_target= */ false);
8013
8014 // Otherwise, we need to check that the object's class is a non-primitive array.
8015 // /* HeapReference<Class> */ temp = temp->component_type_
8016 GenerateReferenceLoadOneRegister(instruction,
8017 temp_loc,
8018 component_offset,
8019 maybe_temp2_loc,
8020 kWithoutReadBarrier);
8021 // If the component type is null, jump to the slow path to throw the exception.
8022 __ CompareAndBranchIfZero(temp, type_check_slow_path->GetEntryLabel());
8023 // Otherwise,the object is indeed an array, jump to label `check_non_primitive_component_type`
8024 // to further check that this component type is not a primitive type.
8025 GetAssembler()->LoadFromOffset(kLoadUnsignedHalfword, temp, temp, primitive_offset);
8026 static_assert(Primitive::kPrimNot == 0, "Expected 0 for kPrimNot");
8027 __ CompareAndBranchIfNonZero(temp, type_check_slow_path->GetEntryLabel());
8028 break;
8029 }
8030
8031 case TypeCheckKind::kUnresolvedCheck:
8032 // We always go into the type check slow path for the unresolved check case.
8033 // We cannot directly call the CheckCast runtime entry point
8034 // without resorting to a type checking slow path here (i.e. by
8035 // calling InvokeRuntime directly), as it would require to
8036 // assign fixed registers for the inputs of this HInstanceOf
8037 // instruction (following the runtime calling convention), which
8038 // might be cluttered by the potential first read barrier
8039 // emission at the beginning of this method.
8040
8041 __ B(type_check_slow_path->GetEntryLabel());
8042 break;
8043
8044 case TypeCheckKind::kInterfaceCheck: {
8045 // Avoid read barriers to improve performance of the fast path. We can not get false
8046 // positives by doing this.
8047 // /* HeapReference<Class> */ temp = obj->klass_
8048 GenerateReferenceLoadTwoRegisters(instruction,
8049 temp_loc,
8050 obj_loc,
8051 class_offset,
8052 maybe_temp2_loc,
8053 kWithoutReadBarrier);
8054
8055 // /* HeapReference<Class> */ temp = temp->iftable_
8056 GenerateReferenceLoadTwoRegisters(instruction,
8057 temp_loc,
8058 temp_loc,
8059 iftable_offset,
8060 maybe_temp2_loc,
8061 kWithoutReadBarrier);
8062 // Iftable is never null.
8063 __ Ldr(RegisterFrom(maybe_temp2_loc), MemOperand(temp, array_length_offset));
8064 // Loop through the iftable and check if any class matches.
8065 vixl32::Label start_loop;
8066 __ Bind(&start_loop);
8067 __ CompareAndBranchIfZero(RegisterFrom(maybe_temp2_loc),
8068 type_check_slow_path->GetEntryLabel());
8069 __ Ldr(RegisterFrom(maybe_temp3_loc), MemOperand(temp, object_array_data_offset));
8070 GetAssembler()->MaybeUnpoisonHeapReference(RegisterFrom(maybe_temp3_loc));
8071 // Go to next interface.
8072 __ Add(temp, temp, Operand::From(2 * kHeapReferenceSize));
8073 __ Sub(RegisterFrom(maybe_temp2_loc), RegisterFrom(maybe_temp2_loc), 2);
8074 // Compare the classes and continue the loop if they do not match.
8075 __ Cmp(cls, RegisterFrom(maybe_temp3_loc));
8076 __ B(ne, &start_loop, /* is_far_target= */ false);
8077 break;
8078 }
8079
8080 case TypeCheckKind::kBitstringCheck: {
8081 // /* HeapReference<Class> */ temp = obj->klass_
8082 GenerateReferenceLoadTwoRegisters(instruction,
8083 temp_loc,
8084 obj_loc,
8085 class_offset,
8086 maybe_temp2_loc,
8087 kWithoutReadBarrier);
8088
8089 GenerateBitstringTypeCheckCompare(instruction, temp, SetFlags);
8090 __ B(ne, type_check_slow_path->GetEntryLabel());
8091 break;
8092 }
8093 }
8094 if (done.IsReferenced()) {
8095 __ Bind(&done);
8096 }
8097
8098 __ Bind(type_check_slow_path->GetExitLabel());
8099 }
8100
VisitMonitorOperation(HMonitorOperation * instruction)8101 void LocationsBuilderARMVIXL::VisitMonitorOperation(HMonitorOperation* instruction) {
8102 LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(
8103 instruction, LocationSummary::kCallOnMainOnly);
8104 InvokeRuntimeCallingConventionARMVIXL calling_convention;
8105 locations->SetInAt(0, LocationFrom(calling_convention.GetRegisterAt(0)));
8106 }
8107
VisitMonitorOperation(HMonitorOperation * instruction)8108 void InstructionCodeGeneratorARMVIXL::VisitMonitorOperation(HMonitorOperation* instruction) {
8109 codegen_->InvokeRuntime(instruction->IsEnter() ? kQuickLockObject : kQuickUnlockObject,
8110 instruction,
8111 instruction->GetDexPc());
8112 if (instruction->IsEnter()) {
8113 CheckEntrypointTypes<kQuickLockObject, void, mirror::Object*>();
8114 } else {
8115 CheckEntrypointTypes<kQuickUnlockObject, void, mirror::Object*>();
8116 }
8117 codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ 18);
8118 }
8119
VisitAnd(HAnd * instruction)8120 void LocationsBuilderARMVIXL::VisitAnd(HAnd* instruction) {
8121 HandleBitwiseOperation(instruction, AND);
8122 }
8123
VisitOr(HOr * instruction)8124 void LocationsBuilderARMVIXL::VisitOr(HOr* instruction) {
8125 HandleBitwiseOperation(instruction, ORR);
8126 }
8127
VisitXor(HXor * instruction)8128 void LocationsBuilderARMVIXL::VisitXor(HXor* instruction) {
8129 HandleBitwiseOperation(instruction, EOR);
8130 }
8131
HandleBitwiseOperation(HBinaryOperation * instruction,Opcode opcode)8132 void LocationsBuilderARMVIXL::HandleBitwiseOperation(HBinaryOperation* instruction, Opcode opcode) {
8133 LocationSummary* locations =
8134 new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
8135 DCHECK(instruction->GetResultType() == DataType::Type::kInt32
8136 || instruction->GetResultType() == DataType::Type::kInt64);
8137 // Note: GVN reorders commutative operations to have the constant on the right hand side.
8138 locations->SetInAt(0, Location::RequiresRegister());
8139 locations->SetInAt(1, ArmEncodableConstantOrRegister(instruction->InputAt(1), opcode));
8140 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
8141 }
8142
VisitAnd(HAnd * instruction)8143 void InstructionCodeGeneratorARMVIXL::VisitAnd(HAnd* instruction) {
8144 HandleBitwiseOperation(instruction);
8145 }
8146
VisitOr(HOr * instruction)8147 void InstructionCodeGeneratorARMVIXL::VisitOr(HOr* instruction) {
8148 HandleBitwiseOperation(instruction);
8149 }
8150
VisitXor(HXor * instruction)8151 void InstructionCodeGeneratorARMVIXL::VisitXor(HXor* instruction) {
8152 HandleBitwiseOperation(instruction);
8153 }
8154
VisitBitwiseNegatedRight(HBitwiseNegatedRight * instruction)8155 void LocationsBuilderARMVIXL::VisitBitwiseNegatedRight(HBitwiseNegatedRight* instruction) {
8156 LocationSummary* locations =
8157 new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
8158 DCHECK(instruction->GetResultType() == DataType::Type::kInt32
8159 || instruction->GetResultType() == DataType::Type::kInt64);
8160
8161 locations->SetInAt(0, Location::RequiresRegister());
8162 locations->SetInAt(1, Location::RequiresRegister());
8163 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
8164 }
8165
VisitBitwiseNegatedRight(HBitwiseNegatedRight * instruction)8166 void InstructionCodeGeneratorARMVIXL::VisitBitwiseNegatedRight(HBitwiseNegatedRight* instruction) {
8167 LocationSummary* locations = instruction->GetLocations();
8168 Location first = locations->InAt(0);
8169 Location second = locations->InAt(1);
8170 Location out = locations->Out();
8171
8172 if (instruction->GetResultType() == DataType::Type::kInt32) {
8173 vixl32::Register first_reg = RegisterFrom(first);
8174 vixl32::Register second_reg = RegisterFrom(second);
8175 vixl32::Register out_reg = RegisterFrom(out);
8176
8177 switch (instruction->GetOpKind()) {
8178 case HInstruction::kAnd:
8179 __ Bic(out_reg, first_reg, second_reg);
8180 break;
8181 case HInstruction::kOr:
8182 __ Orn(out_reg, first_reg, second_reg);
8183 break;
8184 // There is no EON on arm.
8185 case HInstruction::kXor:
8186 default:
8187 LOG(FATAL) << "Unexpected instruction " << instruction->DebugName();
8188 UNREACHABLE();
8189 }
8190 return;
8191
8192 } else {
8193 DCHECK_EQ(instruction->GetResultType(), DataType::Type::kInt64);
8194 vixl32::Register first_low = LowRegisterFrom(first);
8195 vixl32::Register first_high = HighRegisterFrom(first);
8196 vixl32::Register second_low = LowRegisterFrom(second);
8197 vixl32::Register second_high = HighRegisterFrom(second);
8198 vixl32::Register out_low = LowRegisterFrom(out);
8199 vixl32::Register out_high = HighRegisterFrom(out);
8200
8201 switch (instruction->GetOpKind()) {
8202 case HInstruction::kAnd:
8203 __ Bic(out_low, first_low, second_low);
8204 __ Bic(out_high, first_high, second_high);
8205 break;
8206 case HInstruction::kOr:
8207 __ Orn(out_low, first_low, second_low);
8208 __ Orn(out_high, first_high, second_high);
8209 break;
8210 // There is no EON on arm.
8211 case HInstruction::kXor:
8212 default:
8213 LOG(FATAL) << "Unexpected instruction " << instruction->DebugName();
8214 UNREACHABLE();
8215 }
8216 }
8217 }
8218
VisitDataProcWithShifterOp(HDataProcWithShifterOp * instruction)8219 void LocationsBuilderARMVIXL::VisitDataProcWithShifterOp(
8220 HDataProcWithShifterOp* instruction) {
8221 DCHECK(instruction->GetType() == DataType::Type::kInt32 ||
8222 instruction->GetType() == DataType::Type::kInt64);
8223 LocationSummary* locations =
8224 new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
8225 const bool overlap = instruction->GetType() == DataType::Type::kInt64 &&
8226 HDataProcWithShifterOp::IsExtensionOp(instruction->GetOpKind());
8227
8228 locations->SetInAt(0, Location::RequiresRegister());
8229 locations->SetInAt(1, Location::RequiresRegister());
8230 locations->SetOut(Location::RequiresRegister(),
8231 overlap ? Location::kOutputOverlap : Location::kNoOutputOverlap);
8232 }
8233
VisitDataProcWithShifterOp(HDataProcWithShifterOp * instruction)8234 void InstructionCodeGeneratorARMVIXL::VisitDataProcWithShifterOp(
8235 HDataProcWithShifterOp* instruction) {
8236 const LocationSummary* const locations = instruction->GetLocations();
8237 const HInstruction::InstructionKind kind = instruction->GetInstrKind();
8238 const HDataProcWithShifterOp::OpKind op_kind = instruction->GetOpKind();
8239
8240 if (instruction->GetType() == DataType::Type::kInt32) {
8241 const vixl32::Register first = InputRegisterAt(instruction, 0);
8242 const vixl32::Register output = OutputRegister(instruction);
8243 const vixl32::Register second = instruction->InputAt(1)->GetType() == DataType::Type::kInt64
8244 ? LowRegisterFrom(locations->InAt(1))
8245 : InputRegisterAt(instruction, 1);
8246
8247 if (HDataProcWithShifterOp::IsExtensionOp(op_kind)) {
8248 DCHECK_EQ(kind, HInstruction::kAdd);
8249
8250 switch (op_kind) {
8251 case HDataProcWithShifterOp::kUXTB:
8252 __ Uxtab(output, first, second);
8253 break;
8254 case HDataProcWithShifterOp::kUXTH:
8255 __ Uxtah(output, first, second);
8256 break;
8257 case HDataProcWithShifterOp::kSXTB:
8258 __ Sxtab(output, first, second);
8259 break;
8260 case HDataProcWithShifterOp::kSXTH:
8261 __ Sxtah(output, first, second);
8262 break;
8263 default:
8264 LOG(FATAL) << "Unexpected operation kind: " << op_kind;
8265 UNREACHABLE();
8266 }
8267 } else {
8268 GenerateDataProcInstruction(kind,
8269 output,
8270 first,
8271 Operand(second,
8272 ShiftFromOpKind(op_kind),
8273 instruction->GetShiftAmount()),
8274 codegen_);
8275 }
8276 } else {
8277 DCHECK_EQ(instruction->GetType(), DataType::Type::kInt64);
8278
8279 if (HDataProcWithShifterOp::IsExtensionOp(op_kind)) {
8280 const vixl32::Register second = InputRegisterAt(instruction, 1);
8281
8282 DCHECK(!LowRegisterFrom(locations->Out()).Is(second));
8283 GenerateDataProc(kind,
8284 locations->Out(),
8285 locations->InAt(0),
8286 second,
8287 Operand(second, ShiftType::ASR, 31),
8288 codegen_);
8289 } else {
8290 GenerateLongDataProc(instruction, codegen_);
8291 }
8292 }
8293 }
8294
8295 // TODO(VIXL): Remove optimizations in the helper when they are implemented in vixl.
GenerateAndConst(vixl32::Register out,vixl32::Register first,uint32_t value)8296 void InstructionCodeGeneratorARMVIXL::GenerateAndConst(vixl32::Register out,
8297 vixl32::Register first,
8298 uint32_t value) {
8299 // Optimize special cases for individual halfs of `and-long` (`and` is simplified earlier).
8300 if (value == 0xffffffffu) {
8301 if (!out.Is(first)) {
8302 __ Mov(out, first);
8303 }
8304 return;
8305 }
8306 if (value == 0u) {
8307 __ Mov(out, 0);
8308 return;
8309 }
8310 if (GetAssembler()->ShifterOperandCanHold(AND, value)) {
8311 __ And(out, first, value);
8312 } else if (GetAssembler()->ShifterOperandCanHold(BIC, ~value)) {
8313 __ Bic(out, first, ~value);
8314 } else {
8315 DCHECK(IsPowerOfTwo(value + 1));
8316 __ Ubfx(out, first, 0, WhichPowerOf2(value + 1));
8317 }
8318 }
8319
8320 // TODO(VIXL): Remove optimizations in the helper when they are implemented in vixl.
GenerateOrrConst(vixl32::Register out,vixl32::Register first,uint32_t value)8321 void InstructionCodeGeneratorARMVIXL::GenerateOrrConst(vixl32::Register out,
8322 vixl32::Register first,
8323 uint32_t value) {
8324 // Optimize special cases for individual halfs of `or-long` (`or` is simplified earlier).
8325 if (value == 0u) {
8326 if (!out.Is(first)) {
8327 __ Mov(out, first);
8328 }
8329 return;
8330 }
8331 if (value == 0xffffffffu) {
8332 __ Mvn(out, 0);
8333 return;
8334 }
8335 if (GetAssembler()->ShifterOperandCanHold(ORR, value)) {
8336 __ Orr(out, first, value);
8337 } else {
8338 DCHECK(GetAssembler()->ShifterOperandCanHold(ORN, ~value));
8339 __ Orn(out, first, ~value);
8340 }
8341 }
8342
8343 // TODO(VIXL): Remove optimizations in the helper when they are implemented in vixl.
GenerateEorConst(vixl32::Register out,vixl32::Register first,uint32_t value)8344 void InstructionCodeGeneratorARMVIXL::GenerateEorConst(vixl32::Register out,
8345 vixl32::Register first,
8346 uint32_t value) {
8347 // Optimize special case for individual halfs of `xor-long` (`xor` is simplified earlier).
8348 if (value == 0u) {
8349 if (!out.Is(first)) {
8350 __ Mov(out, first);
8351 }
8352 return;
8353 }
8354 __ Eor(out, first, value);
8355 }
8356
GenerateAddLongConst(Location out,Location first,uint64_t value)8357 void InstructionCodeGeneratorARMVIXL::GenerateAddLongConst(Location out,
8358 Location first,
8359 uint64_t value) {
8360 vixl32::Register out_low = LowRegisterFrom(out);
8361 vixl32::Register out_high = HighRegisterFrom(out);
8362 vixl32::Register first_low = LowRegisterFrom(first);
8363 vixl32::Register first_high = HighRegisterFrom(first);
8364 uint32_t value_low = Low32Bits(value);
8365 uint32_t value_high = High32Bits(value);
8366 if (value_low == 0u) {
8367 if (!out_low.Is(first_low)) {
8368 __ Mov(out_low, first_low);
8369 }
8370 __ Add(out_high, first_high, value_high);
8371 return;
8372 }
8373 __ Adds(out_low, first_low, value_low);
8374 if (GetAssembler()->ShifterOperandCanHold(ADC, value_high)) {
8375 __ Adc(out_high, first_high, value_high);
8376 } else {
8377 DCHECK(GetAssembler()->ShifterOperandCanHold(SBC, ~value_high));
8378 __ Sbc(out_high, first_high, ~value_high);
8379 }
8380 }
8381
HandleBitwiseOperation(HBinaryOperation * instruction)8382 void InstructionCodeGeneratorARMVIXL::HandleBitwiseOperation(HBinaryOperation* instruction) {
8383 LocationSummary* locations = instruction->GetLocations();
8384 Location first = locations->InAt(0);
8385 Location second = locations->InAt(1);
8386 Location out = locations->Out();
8387
8388 if (second.IsConstant()) {
8389 uint64_t value = static_cast<uint64_t>(Int64FromConstant(second.GetConstant()));
8390 uint32_t value_low = Low32Bits(value);
8391 if (instruction->GetResultType() == DataType::Type::kInt32) {
8392 vixl32::Register first_reg = InputRegisterAt(instruction, 0);
8393 vixl32::Register out_reg = OutputRegister(instruction);
8394 if (instruction->IsAnd()) {
8395 GenerateAndConst(out_reg, first_reg, value_low);
8396 } else if (instruction->IsOr()) {
8397 GenerateOrrConst(out_reg, first_reg, value_low);
8398 } else {
8399 DCHECK(instruction->IsXor());
8400 GenerateEorConst(out_reg, first_reg, value_low);
8401 }
8402 } else {
8403 DCHECK_EQ(instruction->GetResultType(), DataType::Type::kInt64);
8404 uint32_t value_high = High32Bits(value);
8405 vixl32::Register first_low = LowRegisterFrom(first);
8406 vixl32::Register first_high = HighRegisterFrom(first);
8407 vixl32::Register out_low = LowRegisterFrom(out);
8408 vixl32::Register out_high = HighRegisterFrom(out);
8409 if (instruction->IsAnd()) {
8410 GenerateAndConst(out_low, first_low, value_low);
8411 GenerateAndConst(out_high, first_high, value_high);
8412 } else if (instruction->IsOr()) {
8413 GenerateOrrConst(out_low, first_low, value_low);
8414 GenerateOrrConst(out_high, first_high, value_high);
8415 } else {
8416 DCHECK(instruction->IsXor());
8417 GenerateEorConst(out_low, first_low, value_low);
8418 GenerateEorConst(out_high, first_high, value_high);
8419 }
8420 }
8421 return;
8422 }
8423
8424 if (instruction->GetResultType() == DataType::Type::kInt32) {
8425 vixl32::Register first_reg = InputRegisterAt(instruction, 0);
8426 vixl32::Register second_reg = InputRegisterAt(instruction, 1);
8427 vixl32::Register out_reg = OutputRegister(instruction);
8428 if (instruction->IsAnd()) {
8429 __ And(out_reg, first_reg, second_reg);
8430 } else if (instruction->IsOr()) {
8431 __ Orr(out_reg, first_reg, second_reg);
8432 } else {
8433 DCHECK(instruction->IsXor());
8434 __ Eor(out_reg, first_reg, second_reg);
8435 }
8436 } else {
8437 DCHECK_EQ(instruction->GetResultType(), DataType::Type::kInt64);
8438 vixl32::Register first_low = LowRegisterFrom(first);
8439 vixl32::Register first_high = HighRegisterFrom(first);
8440 vixl32::Register second_low = LowRegisterFrom(second);
8441 vixl32::Register second_high = HighRegisterFrom(second);
8442 vixl32::Register out_low = LowRegisterFrom(out);
8443 vixl32::Register out_high = HighRegisterFrom(out);
8444 if (instruction->IsAnd()) {
8445 __ And(out_low, first_low, second_low);
8446 __ And(out_high, first_high, second_high);
8447 } else if (instruction->IsOr()) {
8448 __ Orr(out_low, first_low, second_low);
8449 __ Orr(out_high, first_high, second_high);
8450 } else {
8451 DCHECK(instruction->IsXor());
8452 __ Eor(out_low, first_low, second_low);
8453 __ Eor(out_high, first_high, second_high);
8454 }
8455 }
8456 }
8457
GenerateReferenceLoadOneRegister(HInstruction * instruction,Location out,uint32_t offset,Location maybe_temp,ReadBarrierOption read_barrier_option)8458 void InstructionCodeGeneratorARMVIXL::GenerateReferenceLoadOneRegister(
8459 HInstruction* instruction,
8460 Location out,
8461 uint32_t offset,
8462 Location maybe_temp,
8463 ReadBarrierOption read_barrier_option) {
8464 vixl32::Register out_reg = RegisterFrom(out);
8465 if (read_barrier_option == kWithReadBarrier) {
8466 CHECK(kEmitCompilerReadBarrier);
8467 DCHECK(maybe_temp.IsRegister()) << maybe_temp;
8468 if (kUseBakerReadBarrier) {
8469 // Load with fast path based Baker's read barrier.
8470 // /* HeapReference<Object> */ out = *(out + offset)
8471 codegen_->GenerateFieldLoadWithBakerReadBarrier(
8472 instruction, out, out_reg, offset, maybe_temp, /* needs_null_check= */ false);
8473 } else {
8474 // Load with slow path based read barrier.
8475 // Save the value of `out` into `maybe_temp` before overwriting it
8476 // in the following move operation, as we will need it for the
8477 // read barrier below.
8478 __ Mov(RegisterFrom(maybe_temp), out_reg);
8479 // /* HeapReference<Object> */ out = *(out + offset)
8480 GetAssembler()->LoadFromOffset(kLoadWord, out_reg, out_reg, offset);
8481 codegen_->GenerateReadBarrierSlow(instruction, out, out, maybe_temp, offset);
8482 }
8483 } else {
8484 // Plain load with no read barrier.
8485 // /* HeapReference<Object> */ out = *(out + offset)
8486 GetAssembler()->LoadFromOffset(kLoadWord, out_reg, out_reg, offset);
8487 GetAssembler()->MaybeUnpoisonHeapReference(out_reg);
8488 }
8489 }
8490
GenerateReferenceLoadTwoRegisters(HInstruction * instruction,Location out,Location obj,uint32_t offset,Location maybe_temp,ReadBarrierOption read_barrier_option)8491 void InstructionCodeGeneratorARMVIXL::GenerateReferenceLoadTwoRegisters(
8492 HInstruction* instruction,
8493 Location out,
8494 Location obj,
8495 uint32_t offset,
8496 Location maybe_temp,
8497 ReadBarrierOption read_barrier_option) {
8498 vixl32::Register out_reg = RegisterFrom(out);
8499 vixl32::Register obj_reg = RegisterFrom(obj);
8500 if (read_barrier_option == kWithReadBarrier) {
8501 CHECK(kEmitCompilerReadBarrier);
8502 if (kUseBakerReadBarrier) {
8503 DCHECK(maybe_temp.IsRegister()) << maybe_temp;
8504 // Load with fast path based Baker's read barrier.
8505 // /* HeapReference<Object> */ out = *(obj + offset)
8506 codegen_->GenerateFieldLoadWithBakerReadBarrier(
8507 instruction, out, obj_reg, offset, maybe_temp, /* needs_null_check= */ false);
8508 } else {
8509 // Load with slow path based read barrier.
8510 // /* HeapReference<Object> */ out = *(obj + offset)
8511 GetAssembler()->LoadFromOffset(kLoadWord, out_reg, obj_reg, offset);
8512 codegen_->GenerateReadBarrierSlow(instruction, out, out, obj, offset);
8513 }
8514 } else {
8515 // Plain load with no read barrier.
8516 // /* HeapReference<Object> */ out = *(obj + offset)
8517 GetAssembler()->LoadFromOffset(kLoadWord, out_reg, obj_reg, offset);
8518 GetAssembler()->MaybeUnpoisonHeapReference(out_reg);
8519 }
8520 }
8521
GenerateGcRootFieldLoad(HInstruction * instruction,Location root,vixl32::Register obj,uint32_t offset,ReadBarrierOption read_barrier_option)8522 void CodeGeneratorARMVIXL::GenerateGcRootFieldLoad(
8523 HInstruction* instruction,
8524 Location root,
8525 vixl32::Register obj,
8526 uint32_t offset,
8527 ReadBarrierOption read_barrier_option) {
8528 vixl32::Register root_reg = RegisterFrom(root);
8529 if (read_barrier_option == kWithReadBarrier) {
8530 DCHECK(kEmitCompilerReadBarrier);
8531 if (kUseBakerReadBarrier) {
8532 // Fast path implementation of art::ReadBarrier::BarrierForRoot when
8533 // Baker's read barrier are used.
8534
8535 // Query `art::Thread::Current()->GetIsGcMarking()` (stored in
8536 // the Marking Register) to decide whether we need to enter
8537 // the slow path to mark the GC root.
8538 //
8539 // We use shared thunks for the slow path; shared within the method
8540 // for JIT, across methods for AOT. That thunk checks the reference
8541 // and jumps to the entrypoint if needed.
8542 //
8543 // lr = &return_address;
8544 // GcRoot<mirror::Object> root = *(obj+offset); // Original reference load.
8545 // if (mr) { // Thread::Current()->GetIsGcMarking()
8546 // goto gc_root_thunk<root_reg>(lr)
8547 // }
8548 // return_address:
8549
8550 UseScratchRegisterScope temps(GetVIXLAssembler());
8551 temps.Exclude(ip);
8552 bool narrow = CanEmitNarrowLdr(root_reg, obj, offset);
8553 uint32_t custom_data = EncodeBakerReadBarrierGcRootData(root_reg.GetCode(), narrow);
8554
8555 size_t narrow_instructions = /* CMP */ (mr.IsLow() ? 1u : 0u) + /* LDR */ (narrow ? 1u : 0u);
8556 size_t wide_instructions = /* ADR+CMP+LDR+BNE */ 4u - narrow_instructions;
8557 size_t exact_size = wide_instructions * vixl32::k32BitT32InstructionSizeInBytes +
8558 narrow_instructions * vixl32::k16BitT32InstructionSizeInBytes;
8559 ExactAssemblyScope guard(GetVIXLAssembler(), exact_size);
8560 vixl32::Label return_address;
8561 EmitAdrCode adr(GetVIXLAssembler(), lr, &return_address);
8562 __ cmp(mr, Operand(0));
8563 // Currently the offset is always within range. If that changes,
8564 // we shall have to split the load the same way as for fields.
8565 DCHECK_LT(offset, kReferenceLoadMinFarOffset);
8566 ptrdiff_t old_offset = GetVIXLAssembler()->GetBuffer()->GetCursorOffset();
8567 __ ldr(EncodingSize(narrow ? Narrow : Wide), root_reg, MemOperand(obj, offset));
8568 EmitBakerReadBarrierBne(custom_data);
8569 __ bind(&return_address);
8570 DCHECK_EQ(old_offset - GetVIXLAssembler()->GetBuffer()->GetCursorOffset(),
8571 narrow ? BAKER_MARK_INTROSPECTION_GC_ROOT_LDR_NARROW_OFFSET
8572 : BAKER_MARK_INTROSPECTION_GC_ROOT_LDR_WIDE_OFFSET);
8573 } else {
8574 // GC root loaded through a slow path for read barriers other
8575 // than Baker's.
8576 // /* GcRoot<mirror::Object>* */ root = obj + offset
8577 __ Add(root_reg, obj, offset);
8578 // /* mirror::Object* */ root = root->Read()
8579 GenerateReadBarrierForRootSlow(instruction, root, root);
8580 }
8581 } else {
8582 // Plain GC root load with no read barrier.
8583 // /* GcRoot<mirror::Object> */ root = *(obj + offset)
8584 GetAssembler()->LoadFromOffset(kLoadWord, root_reg, obj, offset);
8585 // Note that GC roots are not affected by heap poisoning, thus we
8586 // do not have to unpoison `root_reg` here.
8587 }
8588 MaybeGenerateMarkingRegisterCheck(/* code= */ 19);
8589 }
8590
GenerateUnsafeCasOldValueAddWithBakerReadBarrier(vixl::aarch32::Register old_value,vixl::aarch32::Register adjusted_old_value,vixl::aarch32::Register expected)8591 void CodeGeneratorARMVIXL::GenerateUnsafeCasOldValueAddWithBakerReadBarrier(
8592 vixl::aarch32::Register old_value,
8593 vixl::aarch32::Register adjusted_old_value,
8594 vixl::aarch32::Register expected) {
8595 DCHECK(kEmitCompilerReadBarrier);
8596 DCHECK(kUseBakerReadBarrier);
8597
8598 // Similar to the Baker RB path in GenerateGcRootFieldLoad(), with an ADD instead of LDR.
8599 uint32_t custom_data = EncodeBakerReadBarrierUnsafeCasData(old_value.GetCode());
8600
8601 size_t narrow_instructions = /* CMP */ (mr.IsLow() ? 1u : 0u);
8602 size_t wide_instructions = /* ADR+CMP+ADD+BNE */ 4u - narrow_instructions;
8603 size_t exact_size = wide_instructions * vixl32::k32BitT32InstructionSizeInBytes +
8604 narrow_instructions * vixl32::k16BitT32InstructionSizeInBytes;
8605 ExactAssemblyScope guard(GetVIXLAssembler(), exact_size);
8606 vixl32::Label return_address;
8607 EmitAdrCode adr(GetVIXLAssembler(), lr, &return_address);
8608 __ cmp(mr, Operand(0));
8609 ptrdiff_t old_offset = GetVIXLAssembler()->GetBuffer()->GetCursorOffset();
8610 __ add(EncodingSize(Wide), old_value, adjusted_old_value, Operand(expected)); // Preserves flags.
8611 EmitBakerReadBarrierBne(custom_data);
8612 __ bind(&return_address);
8613 DCHECK_EQ(old_offset - GetVIXLAssembler()->GetBuffer()->GetCursorOffset(),
8614 BAKER_MARK_INTROSPECTION_UNSAFE_CAS_ADD_OFFSET);
8615 }
8616
GenerateFieldLoadWithBakerReadBarrier(HInstruction * instruction,Location ref,vixl32::Register obj,const vixl32::MemOperand & src,bool needs_null_check)8617 void CodeGeneratorARMVIXL::GenerateFieldLoadWithBakerReadBarrier(HInstruction* instruction,
8618 Location ref,
8619 vixl32::Register obj,
8620 const vixl32::MemOperand& src,
8621 bool needs_null_check) {
8622 DCHECK(kEmitCompilerReadBarrier);
8623 DCHECK(kUseBakerReadBarrier);
8624
8625 // Query `art::Thread::Current()->GetIsGcMarking()` (stored in the
8626 // Marking Register) to decide whether we need to enter the slow
8627 // path to mark the reference. Then, in the slow path, check the
8628 // gray bit in the lock word of the reference's holder (`obj`) to
8629 // decide whether to mark `ref` or not.
8630 //
8631 // We use shared thunks for the slow path; shared within the method
8632 // for JIT, across methods for AOT. That thunk checks the holder
8633 // and jumps to the entrypoint if needed. If the holder is not gray,
8634 // it creates a fake dependency and returns to the LDR instruction.
8635 //
8636 // lr = &gray_return_address;
8637 // if (mr) { // Thread::Current()->GetIsGcMarking()
8638 // goto field_thunk<holder_reg, base_reg>(lr)
8639 // }
8640 // not_gray_return_address:
8641 // // Original reference load. If the offset is too large to fit
8642 // // into LDR, we use an adjusted base register here.
8643 // HeapReference<mirror::Object> reference = *(obj+offset);
8644 // gray_return_address:
8645
8646 DCHECK(src.GetAddrMode() == vixl32::Offset);
8647 DCHECK_ALIGNED(src.GetOffsetImmediate(), sizeof(mirror::HeapReference<mirror::Object>));
8648 vixl32::Register ref_reg = RegisterFrom(ref, DataType::Type::kReference);
8649 bool narrow = CanEmitNarrowLdr(ref_reg, src.GetBaseRegister(), src.GetOffsetImmediate());
8650
8651 UseScratchRegisterScope temps(GetVIXLAssembler());
8652 temps.Exclude(ip);
8653 uint32_t custom_data =
8654 EncodeBakerReadBarrierFieldData(src.GetBaseRegister().GetCode(), obj.GetCode(), narrow);
8655
8656 {
8657 size_t narrow_instructions =
8658 /* CMP */ (mr.IsLow() ? 1u : 0u) +
8659 /* LDR+unpoison? */ (narrow ? (kPoisonHeapReferences ? 2u : 1u) : 0u);
8660 size_t wide_instructions =
8661 /* ADR+CMP+LDR+BNE+unpoison? */ (kPoisonHeapReferences ? 5u : 4u) - narrow_instructions;
8662 size_t exact_size = wide_instructions * vixl32::k32BitT32InstructionSizeInBytes +
8663 narrow_instructions * vixl32::k16BitT32InstructionSizeInBytes;
8664 ExactAssemblyScope guard(GetVIXLAssembler(), exact_size);
8665 vixl32::Label return_address;
8666 EmitAdrCode adr(GetVIXLAssembler(), lr, &return_address);
8667 __ cmp(mr, Operand(0));
8668 EmitBakerReadBarrierBne(custom_data);
8669 ptrdiff_t old_offset = GetVIXLAssembler()->GetBuffer()->GetCursorOffset();
8670 __ ldr(EncodingSize(narrow ? Narrow : Wide), ref_reg, src);
8671 if (needs_null_check) {
8672 MaybeRecordImplicitNullCheck(instruction);
8673 }
8674 // Note: We need a specific width for the unpoisoning NEG.
8675 if (kPoisonHeapReferences) {
8676 if (narrow) {
8677 // The only 16-bit encoding is T1 which sets flags outside IT block (i.e. RSBS, not RSB).
8678 __ rsbs(EncodingSize(Narrow), ref_reg, ref_reg, Operand(0));
8679 } else {
8680 __ rsb(EncodingSize(Wide), ref_reg, ref_reg, Operand(0));
8681 }
8682 }
8683 __ bind(&return_address);
8684 DCHECK_EQ(old_offset - GetVIXLAssembler()->GetBuffer()->GetCursorOffset(),
8685 narrow ? BAKER_MARK_INTROSPECTION_FIELD_LDR_NARROW_OFFSET
8686 : BAKER_MARK_INTROSPECTION_FIELD_LDR_WIDE_OFFSET);
8687 }
8688 MaybeGenerateMarkingRegisterCheck(/* code= */ 20, /* temp_loc= */ LocationFrom(ip));
8689 }
8690
GenerateFieldLoadWithBakerReadBarrier(HInstruction * instruction,Location ref,vixl32::Register obj,uint32_t offset,Location temp,bool needs_null_check)8691 void CodeGeneratorARMVIXL::GenerateFieldLoadWithBakerReadBarrier(HInstruction* instruction,
8692 Location ref,
8693 vixl32::Register obj,
8694 uint32_t offset,
8695 Location temp,
8696 bool needs_null_check) {
8697 DCHECK_ALIGNED(offset, sizeof(mirror::HeapReference<mirror::Object>));
8698 vixl32::Register base = obj;
8699 if (offset >= kReferenceLoadMinFarOffset) {
8700 base = RegisterFrom(temp);
8701 static_assert(IsPowerOfTwo(kReferenceLoadMinFarOffset), "Expecting a power of 2.");
8702 __ Add(base, obj, Operand(offset & ~(kReferenceLoadMinFarOffset - 1u)));
8703 offset &= (kReferenceLoadMinFarOffset - 1u);
8704 }
8705 GenerateFieldLoadWithBakerReadBarrier(
8706 instruction, ref, obj, MemOperand(base, offset), needs_null_check);
8707 }
8708
GenerateArrayLoadWithBakerReadBarrier(Location ref,vixl32::Register obj,uint32_t data_offset,Location index,Location temp,bool needs_null_check)8709 void CodeGeneratorARMVIXL::GenerateArrayLoadWithBakerReadBarrier(Location ref,
8710 vixl32::Register obj,
8711 uint32_t data_offset,
8712 Location index,
8713 Location temp,
8714 bool needs_null_check) {
8715 DCHECK(kEmitCompilerReadBarrier);
8716 DCHECK(kUseBakerReadBarrier);
8717
8718 static_assert(
8719 sizeof(mirror::HeapReference<mirror::Object>) == sizeof(int32_t),
8720 "art::mirror::HeapReference<art::mirror::Object> and int32_t have different sizes.");
8721 ScaleFactor scale_factor = TIMES_4;
8722
8723 // Query `art::Thread::Current()->GetIsGcMarking()` (stored in the
8724 // Marking Register) to decide whether we need to enter the slow
8725 // path to mark the reference. Then, in the slow path, check the
8726 // gray bit in the lock word of the reference's holder (`obj`) to
8727 // decide whether to mark `ref` or not.
8728 //
8729 // We use shared thunks for the slow path; shared within the method
8730 // for JIT, across methods for AOT. That thunk checks the holder
8731 // and jumps to the entrypoint if needed. If the holder is not gray,
8732 // it creates a fake dependency and returns to the LDR instruction.
8733 //
8734 // lr = &gray_return_address;
8735 // if (mr) { // Thread::Current()->GetIsGcMarking()
8736 // goto array_thunk<base_reg>(lr)
8737 // }
8738 // not_gray_return_address:
8739 // // Original reference load. If the offset is too large to fit
8740 // // into LDR, we use an adjusted base register here.
8741 // HeapReference<mirror::Object> reference = data[index];
8742 // gray_return_address:
8743
8744 DCHECK(index.IsValid());
8745 vixl32::Register index_reg = RegisterFrom(index, DataType::Type::kInt32);
8746 vixl32::Register ref_reg = RegisterFrom(ref, DataType::Type::kReference);
8747 vixl32::Register data_reg = RegisterFrom(temp, DataType::Type::kInt32); // Raw pointer.
8748
8749 UseScratchRegisterScope temps(GetVIXLAssembler());
8750 temps.Exclude(ip);
8751 uint32_t custom_data = EncodeBakerReadBarrierArrayData(data_reg.GetCode());
8752
8753 __ Add(data_reg, obj, Operand(data_offset));
8754 {
8755 size_t narrow_instructions = /* CMP */ (mr.IsLow() ? 1u : 0u);
8756 size_t wide_instructions =
8757 /* ADR+CMP+BNE+LDR+unpoison? */ (kPoisonHeapReferences ? 5u : 4u) - narrow_instructions;
8758 size_t exact_size = wide_instructions * vixl32::k32BitT32InstructionSizeInBytes +
8759 narrow_instructions * vixl32::k16BitT32InstructionSizeInBytes;
8760 ExactAssemblyScope guard(GetVIXLAssembler(), exact_size);
8761 vixl32::Label return_address;
8762 EmitAdrCode adr(GetVIXLAssembler(), lr, &return_address);
8763 __ cmp(mr, Operand(0));
8764 EmitBakerReadBarrierBne(custom_data);
8765 ptrdiff_t old_offset = GetVIXLAssembler()->GetBuffer()->GetCursorOffset();
8766 __ ldr(ref_reg, MemOperand(data_reg, index_reg, vixl32::LSL, scale_factor));
8767 DCHECK(!needs_null_check); // The thunk cannot handle the null check.
8768 // Note: We need a Wide NEG for the unpoisoning.
8769 if (kPoisonHeapReferences) {
8770 __ rsb(EncodingSize(Wide), ref_reg, ref_reg, Operand(0));
8771 }
8772 __ bind(&return_address);
8773 DCHECK_EQ(old_offset - GetVIXLAssembler()->GetBuffer()->GetCursorOffset(),
8774 BAKER_MARK_INTROSPECTION_ARRAY_LDR_OFFSET);
8775 }
8776 MaybeGenerateMarkingRegisterCheck(/* code= */ 21, /* temp_loc= */ LocationFrom(ip));
8777 }
8778
MaybeGenerateMarkingRegisterCheck(int code,Location temp_loc)8779 void CodeGeneratorARMVIXL::MaybeGenerateMarkingRegisterCheck(int code, Location temp_loc) {
8780 // The following condition is a compile-time one, so it does not have a run-time cost.
8781 if (kEmitCompilerReadBarrier && kUseBakerReadBarrier && kIsDebugBuild) {
8782 // The following condition is a run-time one; it is executed after the
8783 // previous compile-time test, to avoid penalizing non-debug builds.
8784 if (GetCompilerOptions().EmitRunTimeChecksInDebugMode()) {
8785 UseScratchRegisterScope temps(GetVIXLAssembler());
8786 vixl32::Register temp = temp_loc.IsValid() ? RegisterFrom(temp_loc) : temps.Acquire();
8787 GetAssembler()->GenerateMarkingRegisterCheck(temp,
8788 kMarkingRegisterCheckBreakCodeBaseCode + code);
8789 }
8790 }
8791 }
8792
GenerateReadBarrierSlow(HInstruction * instruction,Location out,Location ref,Location obj,uint32_t offset,Location index)8793 void CodeGeneratorARMVIXL::GenerateReadBarrierSlow(HInstruction* instruction,
8794 Location out,
8795 Location ref,
8796 Location obj,
8797 uint32_t offset,
8798 Location index) {
8799 DCHECK(kEmitCompilerReadBarrier);
8800
8801 // Insert a slow path based read barrier *after* the reference load.
8802 //
8803 // If heap poisoning is enabled, the unpoisoning of the loaded
8804 // reference will be carried out by the runtime within the slow
8805 // path.
8806 //
8807 // Note that `ref` currently does not get unpoisoned (when heap
8808 // poisoning is enabled), which is alright as the `ref` argument is
8809 // not used by the artReadBarrierSlow entry point.
8810 //
8811 // TODO: Unpoison `ref` when it is used by artReadBarrierSlow.
8812 SlowPathCodeARMVIXL* slow_path = new (GetScopedAllocator())
8813 ReadBarrierForHeapReferenceSlowPathARMVIXL(instruction, out, ref, obj, offset, index);
8814 AddSlowPath(slow_path);
8815
8816 __ B(slow_path->GetEntryLabel());
8817 __ Bind(slow_path->GetExitLabel());
8818 }
8819
MaybeGenerateReadBarrierSlow(HInstruction * instruction,Location out,Location ref,Location obj,uint32_t offset,Location index)8820 void CodeGeneratorARMVIXL::MaybeGenerateReadBarrierSlow(HInstruction* instruction,
8821 Location out,
8822 Location ref,
8823 Location obj,
8824 uint32_t offset,
8825 Location index) {
8826 if (kEmitCompilerReadBarrier) {
8827 // Baker's read barriers shall be handled by the fast path
8828 // (CodeGeneratorARMVIXL::GenerateReferenceLoadWithBakerReadBarrier).
8829 DCHECK(!kUseBakerReadBarrier);
8830 // If heap poisoning is enabled, unpoisoning will be taken care of
8831 // by the runtime within the slow path.
8832 GenerateReadBarrierSlow(instruction, out, ref, obj, offset, index);
8833 } else if (kPoisonHeapReferences) {
8834 GetAssembler()->UnpoisonHeapReference(RegisterFrom(out));
8835 }
8836 }
8837
GenerateReadBarrierForRootSlow(HInstruction * instruction,Location out,Location root)8838 void CodeGeneratorARMVIXL::GenerateReadBarrierForRootSlow(HInstruction* instruction,
8839 Location out,
8840 Location root) {
8841 DCHECK(kEmitCompilerReadBarrier);
8842
8843 // Insert a slow path based read barrier *after* the GC root load.
8844 //
8845 // Note that GC roots are not affected by heap poisoning, so we do
8846 // not need to do anything special for this here.
8847 SlowPathCodeARMVIXL* slow_path =
8848 new (GetScopedAllocator()) ReadBarrierForRootSlowPathARMVIXL(instruction, out, root);
8849 AddSlowPath(slow_path);
8850
8851 __ B(slow_path->GetEntryLabel());
8852 __ Bind(slow_path->GetExitLabel());
8853 }
8854
8855 // Check if the desired_dispatch_info is supported. If it is, return it,
8856 // otherwise return a fall-back info that should be used instead.
GetSupportedInvokeStaticOrDirectDispatch(const HInvokeStaticOrDirect::DispatchInfo & desired_dispatch_info,ArtMethod * method ATTRIBUTE_UNUSED)8857 HInvokeStaticOrDirect::DispatchInfo CodeGeneratorARMVIXL::GetSupportedInvokeStaticOrDirectDispatch(
8858 const HInvokeStaticOrDirect::DispatchInfo& desired_dispatch_info,
8859 ArtMethod* method ATTRIBUTE_UNUSED) {
8860 return desired_dispatch_info;
8861 }
8862
GetInvokeStaticOrDirectExtraParameter(HInvokeStaticOrDirect * invoke,vixl32::Register temp)8863 vixl32::Register CodeGeneratorARMVIXL::GetInvokeStaticOrDirectExtraParameter(
8864 HInvokeStaticOrDirect* invoke, vixl32::Register temp) {
8865 DCHECK_EQ(invoke->InputCount(), invoke->GetNumberOfArguments() + 1u);
8866 Location location = invoke->GetLocations()->InAt(invoke->GetSpecialInputIndex());
8867 if (!invoke->GetLocations()->Intrinsified()) {
8868 return RegisterFrom(location);
8869 }
8870 // For intrinsics we allow any location, so it may be on the stack.
8871 if (!location.IsRegister()) {
8872 GetAssembler()->LoadFromOffset(kLoadWord, temp, sp, location.GetStackIndex());
8873 return temp;
8874 }
8875 // For register locations, check if the register was saved. If so, get it from the stack.
8876 // Note: There is a chance that the register was saved but not overwritten, so we could
8877 // save one load. However, since this is just an intrinsic slow path we prefer this
8878 // simple and more robust approach rather that trying to determine if that's the case.
8879 SlowPathCode* slow_path = GetCurrentSlowPath();
8880 if (slow_path != nullptr && slow_path->IsCoreRegisterSaved(RegisterFrom(location).GetCode())) {
8881 int stack_offset = slow_path->GetStackOffsetOfCoreRegister(RegisterFrom(location).GetCode());
8882 GetAssembler()->LoadFromOffset(kLoadWord, temp, sp, stack_offset);
8883 return temp;
8884 }
8885 return RegisterFrom(location);
8886 }
8887
GenerateStaticOrDirectCall(HInvokeStaticOrDirect * invoke,Location temp,SlowPathCode * slow_path)8888 void CodeGeneratorARMVIXL::GenerateStaticOrDirectCall(
8889 HInvokeStaticOrDirect* invoke, Location temp, SlowPathCode* slow_path) {
8890 Location callee_method = temp; // For all kinds except kRecursive, callee will be in temp.
8891 switch (invoke->GetMethodLoadKind()) {
8892 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit: {
8893 uint32_t offset =
8894 GetThreadOffset<kArmPointerSize>(invoke->GetStringInitEntryPoint()).Int32Value();
8895 // temp = thread->string_init_entrypoint
8896 GetAssembler()->LoadFromOffset(kLoadWord, RegisterFrom(temp), tr, offset);
8897 break;
8898 }
8899 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
8900 callee_method = invoke->GetLocations()->InAt(invoke->GetSpecialInputIndex());
8901 break;
8902 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative: {
8903 DCHECK(GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension());
8904 PcRelativePatchInfo* labels = NewBootImageMethodPatch(invoke->GetTargetMethod());
8905 vixl32::Register temp_reg = RegisterFrom(temp);
8906 EmitMovwMovtPlaceholder(labels, temp_reg);
8907 break;
8908 }
8909 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageRelRo: {
8910 uint32_t boot_image_offset = GetBootImageOffset(invoke);
8911 PcRelativePatchInfo* labels = NewBootImageRelRoPatch(boot_image_offset);
8912 vixl32::Register temp_reg = RegisterFrom(temp);
8913 EmitMovwMovtPlaceholder(labels, temp_reg);
8914 GetAssembler()->LoadFromOffset(kLoadWord, temp_reg, temp_reg, /* offset*/ 0);
8915 break;
8916 }
8917 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry: {
8918 PcRelativePatchInfo* labels = NewMethodBssEntryPatch(
8919 MethodReference(&GetGraph()->GetDexFile(), invoke->GetDexMethodIndex()));
8920 vixl32::Register temp_reg = RegisterFrom(temp);
8921 EmitMovwMovtPlaceholder(labels, temp_reg);
8922 // All aligned loads are implicitly atomic consume operations on ARM.
8923 GetAssembler()->LoadFromOffset(kLoadWord, temp_reg, temp_reg, /* offset*/ 0);
8924 break;
8925 }
8926 case HInvokeStaticOrDirect::MethodLoadKind::kJitDirectAddress:
8927 __ Mov(RegisterFrom(temp), Operand::From(invoke->GetMethodAddress()));
8928 break;
8929 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall: {
8930 GenerateInvokeStaticOrDirectRuntimeCall(invoke, temp, slow_path);
8931 return; // No code pointer retrieval; the runtime performs the call directly.
8932 }
8933 }
8934
8935 switch (invoke->GetCodePtrLocation()) {
8936 case HInvokeStaticOrDirect::CodePtrLocation::kCallSelf:
8937 {
8938 // Use a scope to help guarantee that `RecordPcInfo()` records the correct pc.
8939 ExactAssemblyScope aas(GetVIXLAssembler(),
8940 vixl32::k32BitT32InstructionSizeInBytes,
8941 CodeBufferCheckScope::kMaximumSize);
8942 __ bl(GetFrameEntryLabel());
8943 RecordPcInfo(invoke, invoke->GetDexPc(), slow_path);
8944 }
8945 break;
8946 case HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod:
8947 // LR = callee_method->entry_point_from_quick_compiled_code_
8948 GetAssembler()->LoadFromOffset(
8949 kLoadWord,
8950 lr,
8951 RegisterFrom(callee_method),
8952 ArtMethod::EntryPointFromQuickCompiledCodeOffset(kArmPointerSize).Int32Value());
8953 {
8954 // Use a scope to help guarantee that `RecordPcInfo()` records the correct pc.
8955 // blx in T32 has only 16bit encoding that's why a stricter check for the scope is used.
8956 ExactAssemblyScope aas(GetVIXLAssembler(),
8957 vixl32::k16BitT32InstructionSizeInBytes,
8958 CodeBufferCheckScope::kExactSize);
8959 // LR()
8960 __ blx(lr);
8961 RecordPcInfo(invoke, invoke->GetDexPc(), slow_path);
8962 }
8963 break;
8964 }
8965
8966 DCHECK(!IsLeafMethod());
8967 }
8968
GenerateVirtualCall(HInvokeVirtual * invoke,Location temp_location,SlowPathCode * slow_path)8969 void CodeGeneratorARMVIXL::GenerateVirtualCall(
8970 HInvokeVirtual* invoke, Location temp_location, SlowPathCode* slow_path) {
8971 vixl32::Register temp = RegisterFrom(temp_location);
8972 uint32_t method_offset = mirror::Class::EmbeddedVTableEntryOffset(
8973 invoke->GetVTableIndex(), kArmPointerSize).Uint32Value();
8974
8975 // Use the calling convention instead of the location of the receiver, as
8976 // intrinsics may have put the receiver in a different register. In the intrinsics
8977 // slow path, the arguments have been moved to the right place, so here we are
8978 // guaranteed that the receiver is the first register of the calling convention.
8979 InvokeDexCallingConventionARMVIXL calling_convention;
8980 vixl32::Register receiver = calling_convention.GetRegisterAt(0);
8981 uint32_t class_offset = mirror::Object::ClassOffset().Int32Value();
8982 {
8983 // Make sure the pc is recorded immediately after the `ldr` instruction.
8984 ExactAssemblyScope aas(GetVIXLAssembler(),
8985 vixl32::kMaxInstructionSizeInBytes,
8986 CodeBufferCheckScope::kMaximumSize);
8987 // /* HeapReference<Class> */ temp = receiver->klass_
8988 __ ldr(temp, MemOperand(receiver, class_offset));
8989 MaybeRecordImplicitNullCheck(invoke);
8990 }
8991 // Instead of simply (possibly) unpoisoning `temp` here, we should
8992 // emit a read barrier for the previous class reference load.
8993 // However this is not required in practice, as this is an
8994 // intermediate/temporary reference and because the current
8995 // concurrent copying collector keeps the from-space memory
8996 // intact/accessible until the end of the marking phase (the
8997 // concurrent copying collector may not in the future).
8998 GetAssembler()->MaybeUnpoisonHeapReference(temp);
8999
9000 // If we're compiling baseline, update the inline cache.
9001 MaybeGenerateInlineCacheCheck(invoke, temp);
9002
9003 // temp = temp->GetMethodAt(method_offset);
9004 uint32_t entry_point = ArtMethod::EntryPointFromQuickCompiledCodeOffset(
9005 kArmPointerSize).Int32Value();
9006 GetAssembler()->LoadFromOffset(kLoadWord, temp, temp, method_offset);
9007 // LR = temp->GetEntryPoint();
9008 GetAssembler()->LoadFromOffset(kLoadWord, lr, temp, entry_point);
9009 {
9010 // Use a scope to help guarantee that `RecordPcInfo()` records the correct pc.
9011 // blx in T32 has only 16bit encoding that's why a stricter check for the scope is used.
9012 ExactAssemblyScope aas(GetVIXLAssembler(),
9013 vixl32::k16BitT32InstructionSizeInBytes,
9014 CodeBufferCheckScope::kExactSize);
9015 // LR();
9016 __ blx(lr);
9017 RecordPcInfo(invoke, invoke->GetDexPc(), slow_path);
9018 }
9019 }
9020
NewBootImageIntrinsicPatch(uint32_t intrinsic_data)9021 CodeGeneratorARMVIXL::PcRelativePatchInfo* CodeGeneratorARMVIXL::NewBootImageIntrinsicPatch(
9022 uint32_t intrinsic_data) {
9023 return NewPcRelativePatch(/* dex_file= */ nullptr, intrinsic_data, &boot_image_other_patches_);
9024 }
9025
NewBootImageRelRoPatch(uint32_t boot_image_offset)9026 CodeGeneratorARMVIXL::PcRelativePatchInfo* CodeGeneratorARMVIXL::NewBootImageRelRoPatch(
9027 uint32_t boot_image_offset) {
9028 return NewPcRelativePatch(/* dex_file= */ nullptr,
9029 boot_image_offset,
9030 &boot_image_other_patches_);
9031 }
9032
NewBootImageMethodPatch(MethodReference target_method)9033 CodeGeneratorARMVIXL::PcRelativePatchInfo* CodeGeneratorARMVIXL::NewBootImageMethodPatch(
9034 MethodReference target_method) {
9035 return NewPcRelativePatch(
9036 target_method.dex_file, target_method.index, &boot_image_method_patches_);
9037 }
9038
NewMethodBssEntryPatch(MethodReference target_method)9039 CodeGeneratorARMVIXL::PcRelativePatchInfo* CodeGeneratorARMVIXL::NewMethodBssEntryPatch(
9040 MethodReference target_method) {
9041 return NewPcRelativePatch(
9042 target_method.dex_file, target_method.index, &method_bss_entry_patches_);
9043 }
9044
NewBootImageTypePatch(const DexFile & dex_file,dex::TypeIndex type_index)9045 CodeGeneratorARMVIXL::PcRelativePatchInfo* CodeGeneratorARMVIXL::NewBootImageTypePatch(
9046 const DexFile& dex_file, dex::TypeIndex type_index) {
9047 return NewPcRelativePatch(&dex_file, type_index.index_, &boot_image_type_patches_);
9048 }
9049
NewTypeBssEntryPatch(const DexFile & dex_file,dex::TypeIndex type_index)9050 CodeGeneratorARMVIXL::PcRelativePatchInfo* CodeGeneratorARMVIXL::NewTypeBssEntryPatch(
9051 const DexFile& dex_file, dex::TypeIndex type_index) {
9052 return NewPcRelativePatch(&dex_file, type_index.index_, &type_bss_entry_patches_);
9053 }
9054
NewBootImageStringPatch(const DexFile & dex_file,dex::StringIndex string_index)9055 CodeGeneratorARMVIXL::PcRelativePatchInfo* CodeGeneratorARMVIXL::NewBootImageStringPatch(
9056 const DexFile& dex_file, dex::StringIndex string_index) {
9057 return NewPcRelativePatch(&dex_file, string_index.index_, &boot_image_string_patches_);
9058 }
9059
NewStringBssEntryPatch(const DexFile & dex_file,dex::StringIndex string_index)9060 CodeGeneratorARMVIXL::PcRelativePatchInfo* CodeGeneratorARMVIXL::NewStringBssEntryPatch(
9061 const DexFile& dex_file, dex::StringIndex string_index) {
9062 return NewPcRelativePatch(&dex_file, string_index.index_, &string_bss_entry_patches_);
9063 }
9064
NewPcRelativePatch(const DexFile * dex_file,uint32_t offset_or_index,ArenaDeque<PcRelativePatchInfo> * patches)9065 CodeGeneratorARMVIXL::PcRelativePatchInfo* CodeGeneratorARMVIXL::NewPcRelativePatch(
9066 const DexFile* dex_file, uint32_t offset_or_index, ArenaDeque<PcRelativePatchInfo>* patches) {
9067 patches->emplace_back(dex_file, offset_or_index);
9068 return &patches->back();
9069 }
9070
EmitEntrypointThunkCall(ThreadOffset32 entrypoint_offset)9071 void CodeGeneratorARMVIXL::EmitEntrypointThunkCall(ThreadOffset32 entrypoint_offset) {
9072 DCHECK(!__ AllowMacroInstructions()); // In ExactAssemblyScope.
9073 DCHECK(!Runtime::Current()->UseJitCompilation());
9074 call_entrypoint_patches_.emplace_back(/*dex_file*/ nullptr, entrypoint_offset.Uint32Value());
9075 vixl::aarch32::Label* bl_label = &call_entrypoint_patches_.back().label;
9076 __ bind(bl_label);
9077 vixl32::Label placeholder_label;
9078 __ bl(&placeholder_label); // Placeholder, patched at link-time.
9079 __ bind(&placeholder_label);
9080 }
9081
EmitBakerReadBarrierBne(uint32_t custom_data)9082 void CodeGeneratorARMVIXL::EmitBakerReadBarrierBne(uint32_t custom_data) {
9083 DCHECK(!__ AllowMacroInstructions()); // In ExactAssemblyScope.
9084 if (Runtime::Current()->UseJitCompilation()) {
9085 auto it = jit_baker_read_barrier_slow_paths_.FindOrAdd(custom_data);
9086 vixl::aarch32::Label* slow_path_entry = &it->second.label;
9087 __ b(ne, EncodingSize(Wide), slow_path_entry);
9088 } else {
9089 baker_read_barrier_patches_.emplace_back(custom_data);
9090 vixl::aarch32::Label* patch_label = &baker_read_barrier_patches_.back().label;
9091 __ bind(patch_label);
9092 vixl32::Label placeholder_label;
9093 __ b(ne, EncodingSize(Wide), &placeholder_label); // Placeholder, patched at link-time.
9094 __ bind(&placeholder_label);
9095 }
9096 }
9097
DeduplicateBootImageAddressLiteral(uint32_t address)9098 VIXLUInt32Literal* CodeGeneratorARMVIXL::DeduplicateBootImageAddressLiteral(uint32_t address) {
9099 return DeduplicateUint32Literal(address, &uint32_literals_);
9100 }
9101
DeduplicateJitStringLiteral(const DexFile & dex_file,dex::StringIndex string_index,Handle<mirror::String> handle)9102 VIXLUInt32Literal* CodeGeneratorARMVIXL::DeduplicateJitStringLiteral(
9103 const DexFile& dex_file,
9104 dex::StringIndex string_index,
9105 Handle<mirror::String> handle) {
9106 ReserveJitStringRoot(StringReference(&dex_file, string_index), handle);
9107 return jit_string_patches_.GetOrCreate(
9108 StringReference(&dex_file, string_index),
9109 [this]() {
9110 return GetAssembler()->CreateLiteralDestroyedWithPool<uint32_t>(/* value= */ 0u);
9111 });
9112 }
9113
DeduplicateJitClassLiteral(const DexFile & dex_file,dex::TypeIndex type_index,Handle<mirror::Class> handle)9114 VIXLUInt32Literal* CodeGeneratorARMVIXL::DeduplicateJitClassLiteral(const DexFile& dex_file,
9115 dex::TypeIndex type_index,
9116 Handle<mirror::Class> handle) {
9117 ReserveJitClassRoot(TypeReference(&dex_file, type_index), handle);
9118 return jit_class_patches_.GetOrCreate(
9119 TypeReference(&dex_file, type_index),
9120 [this]() {
9121 return GetAssembler()->CreateLiteralDestroyedWithPool<uint32_t>(/* value= */ 0u);
9122 });
9123 }
9124
LoadBootImageAddress(vixl32::Register reg,uint32_t boot_image_reference)9125 void CodeGeneratorARMVIXL::LoadBootImageAddress(vixl32::Register reg,
9126 uint32_t boot_image_reference) {
9127 if (GetCompilerOptions().IsBootImage()) {
9128 CodeGeneratorARMVIXL::PcRelativePatchInfo* labels =
9129 NewBootImageIntrinsicPatch(boot_image_reference);
9130 EmitMovwMovtPlaceholder(labels, reg);
9131 } else if (GetCompilerOptions().GetCompilePic()) {
9132 CodeGeneratorARMVIXL::PcRelativePatchInfo* labels =
9133 NewBootImageRelRoPatch(boot_image_reference);
9134 EmitMovwMovtPlaceholder(labels, reg);
9135 __ Ldr(reg, MemOperand(reg, /* offset= */ 0));
9136 } else {
9137 DCHECK(Runtime::Current()->UseJitCompilation());
9138 gc::Heap* heap = Runtime::Current()->GetHeap();
9139 DCHECK(!heap->GetBootImageSpaces().empty());
9140 uintptr_t address =
9141 reinterpret_cast<uintptr_t>(heap->GetBootImageSpaces()[0]->Begin() + boot_image_reference);
9142 __ Ldr(reg, DeduplicateBootImageAddressLiteral(dchecked_integral_cast<uint32_t>(address)));
9143 }
9144 }
9145
AllocateInstanceForIntrinsic(HInvokeStaticOrDirect * invoke,uint32_t boot_image_offset)9146 void CodeGeneratorARMVIXL::AllocateInstanceForIntrinsic(HInvokeStaticOrDirect* invoke,
9147 uint32_t boot_image_offset) {
9148 DCHECK(invoke->IsStatic());
9149 InvokeRuntimeCallingConventionARMVIXL calling_convention;
9150 vixl32::Register argument = calling_convention.GetRegisterAt(0);
9151 if (GetCompilerOptions().IsBootImage()) {
9152 DCHECK_EQ(boot_image_offset, IntrinsicVisitor::IntegerValueOfInfo::kInvalidReference);
9153 // Load the class the same way as for HLoadClass::LoadKind::kBootImageLinkTimePcRelative.
9154 MethodReference target_method = invoke->GetTargetMethod();
9155 dex::TypeIndex type_idx = target_method.dex_file->GetMethodId(target_method.index).class_idx_;
9156 PcRelativePatchInfo* labels = NewBootImageTypePatch(*target_method.dex_file, type_idx);
9157 EmitMovwMovtPlaceholder(labels, argument);
9158 } else {
9159 LoadBootImageAddress(argument, boot_image_offset);
9160 }
9161 InvokeRuntime(kQuickAllocObjectInitialized, invoke, invoke->GetDexPc());
9162 CheckEntrypointTypes<kQuickAllocObjectWithChecks, void*, mirror::Class*>();
9163 }
9164
9165 template <linker::LinkerPatch (*Factory)(size_t, const DexFile*, uint32_t, uint32_t)>
EmitPcRelativeLinkerPatches(const ArenaDeque<PcRelativePatchInfo> & infos,ArenaVector<linker::LinkerPatch> * linker_patches)9166 inline void CodeGeneratorARMVIXL::EmitPcRelativeLinkerPatches(
9167 const ArenaDeque<PcRelativePatchInfo>& infos,
9168 ArenaVector<linker::LinkerPatch>* linker_patches) {
9169 for (const PcRelativePatchInfo& info : infos) {
9170 const DexFile* dex_file = info.target_dex_file;
9171 size_t offset_or_index = info.offset_or_index;
9172 DCHECK(info.add_pc_label.IsBound());
9173 uint32_t add_pc_offset = dchecked_integral_cast<uint32_t>(info.add_pc_label.GetLocation());
9174 // Add MOVW patch.
9175 DCHECK(info.movw_label.IsBound());
9176 uint32_t movw_offset = dchecked_integral_cast<uint32_t>(info.movw_label.GetLocation());
9177 linker_patches->push_back(Factory(movw_offset, dex_file, add_pc_offset, offset_or_index));
9178 // Add MOVT patch.
9179 DCHECK(info.movt_label.IsBound());
9180 uint32_t movt_offset = dchecked_integral_cast<uint32_t>(info.movt_label.GetLocation());
9181 linker_patches->push_back(Factory(movt_offset, dex_file, add_pc_offset, offset_or_index));
9182 }
9183 }
9184
9185 template <linker::LinkerPatch (*Factory)(size_t, uint32_t, uint32_t)>
NoDexFileAdapter(size_t literal_offset,const DexFile * target_dex_file,uint32_t pc_insn_offset,uint32_t boot_image_offset)9186 linker::LinkerPatch NoDexFileAdapter(size_t literal_offset,
9187 const DexFile* target_dex_file,
9188 uint32_t pc_insn_offset,
9189 uint32_t boot_image_offset) {
9190 DCHECK(target_dex_file == nullptr); // Unused for these patches, should be null.
9191 return Factory(literal_offset, pc_insn_offset, boot_image_offset);
9192 }
9193
EmitLinkerPatches(ArenaVector<linker::LinkerPatch> * linker_patches)9194 void CodeGeneratorARMVIXL::EmitLinkerPatches(ArenaVector<linker::LinkerPatch>* linker_patches) {
9195 DCHECK(linker_patches->empty());
9196 size_t size =
9197 /* MOVW+MOVT for each entry */ 2u * boot_image_method_patches_.size() +
9198 /* MOVW+MOVT for each entry */ 2u * method_bss_entry_patches_.size() +
9199 /* MOVW+MOVT for each entry */ 2u * boot_image_type_patches_.size() +
9200 /* MOVW+MOVT for each entry */ 2u * type_bss_entry_patches_.size() +
9201 /* MOVW+MOVT for each entry */ 2u * boot_image_string_patches_.size() +
9202 /* MOVW+MOVT for each entry */ 2u * string_bss_entry_patches_.size() +
9203 /* MOVW+MOVT for each entry */ 2u * boot_image_other_patches_.size() +
9204 call_entrypoint_patches_.size() +
9205 baker_read_barrier_patches_.size();
9206 linker_patches->reserve(size);
9207 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension()) {
9208 EmitPcRelativeLinkerPatches<linker::LinkerPatch::RelativeMethodPatch>(
9209 boot_image_method_patches_, linker_patches);
9210 EmitPcRelativeLinkerPatches<linker::LinkerPatch::RelativeTypePatch>(
9211 boot_image_type_patches_, linker_patches);
9212 EmitPcRelativeLinkerPatches<linker::LinkerPatch::RelativeStringPatch>(
9213 boot_image_string_patches_, linker_patches);
9214 } else {
9215 DCHECK(boot_image_method_patches_.empty());
9216 DCHECK(boot_image_type_patches_.empty());
9217 DCHECK(boot_image_string_patches_.empty());
9218 }
9219 if (GetCompilerOptions().IsBootImage()) {
9220 EmitPcRelativeLinkerPatches<NoDexFileAdapter<linker::LinkerPatch::IntrinsicReferencePatch>>(
9221 boot_image_other_patches_, linker_patches);
9222 } else {
9223 EmitPcRelativeLinkerPatches<NoDexFileAdapter<linker::LinkerPatch::DataBimgRelRoPatch>>(
9224 boot_image_other_patches_, linker_patches);
9225 }
9226 EmitPcRelativeLinkerPatches<linker::LinkerPatch::MethodBssEntryPatch>(
9227 method_bss_entry_patches_, linker_patches);
9228 EmitPcRelativeLinkerPatches<linker::LinkerPatch::TypeBssEntryPatch>(
9229 type_bss_entry_patches_, linker_patches);
9230 EmitPcRelativeLinkerPatches<linker::LinkerPatch::StringBssEntryPatch>(
9231 string_bss_entry_patches_, linker_patches);
9232 for (const PatchInfo<vixl32::Label>& info : call_entrypoint_patches_) {
9233 DCHECK(info.target_dex_file == nullptr);
9234 linker_patches->push_back(linker::LinkerPatch::CallEntrypointPatch(
9235 info.label.GetLocation(), info.offset_or_index));
9236 }
9237 for (const BakerReadBarrierPatchInfo& info : baker_read_barrier_patches_) {
9238 linker_patches->push_back(linker::LinkerPatch::BakerReadBarrierBranchPatch(
9239 info.label.GetLocation(), info.custom_data));
9240 }
9241 DCHECK_EQ(size, linker_patches->size());
9242 }
9243
NeedsThunkCode(const linker::LinkerPatch & patch) const9244 bool CodeGeneratorARMVIXL::NeedsThunkCode(const linker::LinkerPatch& patch) const {
9245 return patch.GetType() == linker::LinkerPatch::Type::kCallEntrypoint ||
9246 patch.GetType() == linker::LinkerPatch::Type::kBakerReadBarrierBranch ||
9247 patch.GetType() == linker::LinkerPatch::Type::kCallRelative;
9248 }
9249
EmitThunkCode(const linker::LinkerPatch & patch,ArenaVector<uint8_t> * code,std::string * debug_name)9250 void CodeGeneratorARMVIXL::EmitThunkCode(const linker::LinkerPatch& patch,
9251 /*out*/ ArenaVector<uint8_t>* code,
9252 /*out*/ std::string* debug_name) {
9253 arm::ArmVIXLAssembler assembler(GetGraph()->GetAllocator());
9254 switch (patch.GetType()) {
9255 case linker::LinkerPatch::Type::kCallRelative: {
9256 // The thunk just uses the entry point in the ArtMethod. This works even for calls
9257 // to the generic JNI and interpreter trampolines.
9258 MemberOffset offset = ArtMethod::EntryPointFromQuickCompiledCodeOffset(kArmPointerSize);
9259 assembler.LoadFromOffset(arm::kLoadWord, vixl32::pc, vixl32::r0, offset.Int32Value());
9260 assembler.GetVIXLAssembler()->Bkpt(0);
9261 if (GetCompilerOptions().GenerateAnyDebugInfo()) {
9262 *debug_name = "MethodCallThunk";
9263 }
9264 break;
9265 }
9266 case linker::LinkerPatch::Type::kCallEntrypoint: {
9267 assembler.LoadFromOffset(arm::kLoadWord, vixl32::pc, tr, patch.EntrypointOffset());
9268 assembler.GetVIXLAssembler()->Bkpt(0);
9269 if (GetCompilerOptions().GenerateAnyDebugInfo()) {
9270 *debug_name = "EntrypointCallThunk_" + std::to_string(patch.EntrypointOffset());
9271 }
9272 break;
9273 }
9274 case linker::LinkerPatch::Type::kBakerReadBarrierBranch: {
9275 DCHECK_EQ(patch.GetBakerCustomValue2(), 0u);
9276 CompileBakerReadBarrierThunk(assembler, patch.GetBakerCustomValue1(), debug_name);
9277 break;
9278 }
9279 default:
9280 LOG(FATAL) << "Unexpected patch type " << patch.GetType();
9281 UNREACHABLE();
9282 }
9283
9284 // Ensure we emit the literal pool if any.
9285 assembler.FinalizeCode();
9286 code->resize(assembler.CodeSize());
9287 MemoryRegion code_region(code->data(), code->size());
9288 assembler.FinalizeInstructions(code_region);
9289 }
9290
DeduplicateUint32Literal(uint32_t value,Uint32ToLiteralMap * map)9291 VIXLUInt32Literal* CodeGeneratorARMVIXL::DeduplicateUint32Literal(
9292 uint32_t value,
9293 Uint32ToLiteralMap* map) {
9294 return map->GetOrCreate(
9295 value,
9296 [this, value]() {
9297 return GetAssembler()->CreateLiteralDestroyedWithPool<uint32_t>(/* value= */ value);
9298 });
9299 }
9300
VisitMultiplyAccumulate(HMultiplyAccumulate * instr)9301 void LocationsBuilderARMVIXL::VisitMultiplyAccumulate(HMultiplyAccumulate* instr) {
9302 LocationSummary* locations =
9303 new (GetGraph()->GetAllocator()) LocationSummary(instr, LocationSummary::kNoCall);
9304 locations->SetInAt(HMultiplyAccumulate::kInputAccumulatorIndex,
9305 Location::RequiresRegister());
9306 locations->SetInAt(HMultiplyAccumulate::kInputMulLeftIndex, Location::RequiresRegister());
9307 locations->SetInAt(HMultiplyAccumulate::kInputMulRightIndex, Location::RequiresRegister());
9308 locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
9309 }
9310
VisitMultiplyAccumulate(HMultiplyAccumulate * instr)9311 void InstructionCodeGeneratorARMVIXL::VisitMultiplyAccumulate(HMultiplyAccumulate* instr) {
9312 vixl32::Register res = OutputRegister(instr);
9313 vixl32::Register accumulator =
9314 InputRegisterAt(instr, HMultiplyAccumulate::kInputAccumulatorIndex);
9315 vixl32::Register mul_left =
9316 InputRegisterAt(instr, HMultiplyAccumulate::kInputMulLeftIndex);
9317 vixl32::Register mul_right =
9318 InputRegisterAt(instr, HMultiplyAccumulate::kInputMulRightIndex);
9319
9320 if (instr->GetOpKind() == HInstruction::kAdd) {
9321 __ Mla(res, mul_left, mul_right, accumulator);
9322 } else {
9323 __ Mls(res, mul_left, mul_right, accumulator);
9324 }
9325 }
9326
VisitBoundType(HBoundType * instruction ATTRIBUTE_UNUSED)9327 void LocationsBuilderARMVIXL::VisitBoundType(HBoundType* instruction ATTRIBUTE_UNUSED) {
9328 // Nothing to do, this should be removed during prepare for register allocator.
9329 LOG(FATAL) << "Unreachable";
9330 }
9331
VisitBoundType(HBoundType * instruction ATTRIBUTE_UNUSED)9332 void InstructionCodeGeneratorARMVIXL::VisitBoundType(HBoundType* instruction ATTRIBUTE_UNUSED) {
9333 // Nothing to do, this should be removed during prepare for register allocator.
9334 LOG(FATAL) << "Unreachable";
9335 }
9336
9337 // Simple implementation of packed switch - generate cascaded compare/jumps.
VisitPackedSwitch(HPackedSwitch * switch_instr)9338 void LocationsBuilderARMVIXL::VisitPackedSwitch(HPackedSwitch* switch_instr) {
9339 LocationSummary* locations =
9340 new (GetGraph()->GetAllocator()) LocationSummary(switch_instr, LocationSummary::kNoCall);
9341 locations->SetInAt(0, Location::RequiresRegister());
9342 if (switch_instr->GetNumEntries() > kPackedSwitchCompareJumpThreshold &&
9343 codegen_->GetAssembler()->GetVIXLAssembler()->IsUsingT32()) {
9344 locations->AddTemp(Location::RequiresRegister()); // We need a temp for the table base.
9345 if (switch_instr->GetStartValue() != 0) {
9346 locations->AddTemp(Location::RequiresRegister()); // We need a temp for the bias.
9347 }
9348 }
9349 }
9350
9351 // TODO(VIXL): Investigate and reach the parity with old arm codegen.
VisitPackedSwitch(HPackedSwitch * switch_instr)9352 void InstructionCodeGeneratorARMVIXL::VisitPackedSwitch(HPackedSwitch* switch_instr) {
9353 int32_t lower_bound = switch_instr->GetStartValue();
9354 uint32_t num_entries = switch_instr->GetNumEntries();
9355 LocationSummary* locations = switch_instr->GetLocations();
9356 vixl32::Register value_reg = InputRegisterAt(switch_instr, 0);
9357 HBasicBlock* default_block = switch_instr->GetDefaultBlock();
9358
9359 if (num_entries <= kPackedSwitchCompareJumpThreshold ||
9360 !codegen_->GetAssembler()->GetVIXLAssembler()->IsUsingT32()) {
9361 // Create a series of compare/jumps.
9362 UseScratchRegisterScope temps(GetVIXLAssembler());
9363 vixl32::Register temp_reg = temps.Acquire();
9364 // Note: It is fine for the below AddConstantSetFlags() using IP register to temporarily store
9365 // the immediate, because IP is used as the destination register. For the other
9366 // AddConstantSetFlags() and GenerateCompareWithImmediate(), the immediate values are constant,
9367 // and they can be encoded in the instruction without making use of IP register.
9368 __ Adds(temp_reg, value_reg, -lower_bound);
9369
9370 const ArenaVector<HBasicBlock*>& successors = switch_instr->GetBlock()->GetSuccessors();
9371 // Jump to successors[0] if value == lower_bound.
9372 __ B(eq, codegen_->GetLabelOf(successors[0]));
9373 int32_t last_index = 0;
9374 for (; num_entries - last_index > 2; last_index += 2) {
9375 __ Adds(temp_reg, temp_reg, -2);
9376 // Jump to successors[last_index + 1] if value < case_value[last_index + 2].
9377 __ B(lo, codegen_->GetLabelOf(successors[last_index + 1]));
9378 // Jump to successors[last_index + 2] if value == case_value[last_index + 2].
9379 __ B(eq, codegen_->GetLabelOf(successors[last_index + 2]));
9380 }
9381 if (num_entries - last_index == 2) {
9382 // The last missing case_value.
9383 __ Cmp(temp_reg, 1);
9384 __ B(eq, codegen_->GetLabelOf(successors[last_index + 1]));
9385 }
9386
9387 // And the default for any other value.
9388 if (!codegen_->GoesToNextBlock(switch_instr->GetBlock(), default_block)) {
9389 __ B(codegen_->GetLabelOf(default_block));
9390 }
9391 } else {
9392 // Create a table lookup.
9393 vixl32::Register table_base = RegisterFrom(locations->GetTemp(0));
9394
9395 JumpTableARMVIXL* jump_table = codegen_->CreateJumpTable(switch_instr);
9396
9397 // Remove the bias.
9398 vixl32::Register key_reg;
9399 if (lower_bound != 0) {
9400 key_reg = RegisterFrom(locations->GetTemp(1));
9401 __ Sub(key_reg, value_reg, lower_bound);
9402 } else {
9403 key_reg = value_reg;
9404 }
9405
9406 // Check whether the value is in the table, jump to default block if not.
9407 __ Cmp(key_reg, num_entries - 1);
9408 __ B(hi, codegen_->GetLabelOf(default_block));
9409
9410 UseScratchRegisterScope temps(GetVIXLAssembler());
9411 vixl32::Register jump_offset = temps.Acquire();
9412
9413 // Load jump offset from the table.
9414 {
9415 const size_t jump_size = switch_instr->GetNumEntries() * sizeof(int32_t);
9416 ExactAssemblyScope aas(GetVIXLAssembler(),
9417 (vixl32::kMaxInstructionSizeInBytes * 4) + jump_size,
9418 CodeBufferCheckScope::kMaximumSize);
9419 __ adr(table_base, jump_table->GetTableStartLabel());
9420 __ ldr(jump_offset, MemOperand(table_base, key_reg, vixl32::LSL, 2));
9421
9422 // Jump to target block by branching to table_base(pc related) + offset.
9423 vixl32::Register target_address = table_base;
9424 __ add(target_address, table_base, jump_offset);
9425 __ bx(target_address);
9426
9427 jump_table->EmitTable(codegen_);
9428 }
9429 }
9430 }
9431
9432 // Copy the result of a call into the given target.
MoveFromReturnRegister(Location trg,DataType::Type type)9433 void CodeGeneratorARMVIXL::MoveFromReturnRegister(Location trg, DataType::Type type) {
9434 if (!trg.IsValid()) {
9435 DCHECK_EQ(type, DataType::Type::kVoid);
9436 return;
9437 }
9438
9439 DCHECK_NE(type, DataType::Type::kVoid);
9440
9441 Location return_loc = InvokeDexCallingConventionVisitorARMVIXL().GetReturnLocation(type);
9442 if (return_loc.Equals(trg)) {
9443 return;
9444 }
9445
9446 // TODO: Consider pairs in the parallel move resolver, then this could be nicely merged
9447 // with the last branch.
9448 if (type == DataType::Type::kInt64) {
9449 TODO_VIXL32(FATAL);
9450 } else if (type == DataType::Type::kFloat64) {
9451 TODO_VIXL32(FATAL);
9452 } else {
9453 // Let the parallel move resolver take care of all of this.
9454 HParallelMove parallel_move(GetGraph()->GetAllocator());
9455 parallel_move.AddMove(return_loc, trg, type, nullptr);
9456 GetMoveResolver()->EmitNativeCode(¶llel_move);
9457 }
9458 }
9459
VisitClassTableGet(HClassTableGet * instruction)9460 void LocationsBuilderARMVIXL::VisitClassTableGet(HClassTableGet* instruction) {
9461 LocationSummary* locations =
9462 new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
9463 locations->SetInAt(0, Location::RequiresRegister());
9464 locations->SetOut(Location::RequiresRegister());
9465 }
9466
VisitClassTableGet(HClassTableGet * instruction)9467 void InstructionCodeGeneratorARMVIXL::VisitClassTableGet(HClassTableGet* instruction) {
9468 if (instruction->GetTableKind() == HClassTableGet::TableKind::kVTable) {
9469 uint32_t method_offset = mirror::Class::EmbeddedVTableEntryOffset(
9470 instruction->GetIndex(), kArmPointerSize).SizeValue();
9471 GetAssembler()->LoadFromOffset(kLoadWord,
9472 OutputRegister(instruction),
9473 InputRegisterAt(instruction, 0),
9474 method_offset);
9475 } else {
9476 uint32_t method_offset = static_cast<uint32_t>(ImTable::OffsetOfElement(
9477 instruction->GetIndex(), kArmPointerSize));
9478 GetAssembler()->LoadFromOffset(kLoadWord,
9479 OutputRegister(instruction),
9480 InputRegisterAt(instruction, 0),
9481 mirror::Class::ImtPtrOffset(kArmPointerSize).Uint32Value());
9482 GetAssembler()->LoadFromOffset(kLoadWord,
9483 OutputRegister(instruction),
9484 OutputRegister(instruction),
9485 method_offset);
9486 }
9487 }
9488
PatchJitRootUse(uint8_t * code,const uint8_t * roots_data,VIXLUInt32Literal * literal,uint64_t index_in_table)9489 static void PatchJitRootUse(uint8_t* code,
9490 const uint8_t* roots_data,
9491 VIXLUInt32Literal* literal,
9492 uint64_t index_in_table) {
9493 DCHECK(literal->IsBound());
9494 uint32_t literal_offset = literal->GetLocation();
9495 uintptr_t address =
9496 reinterpret_cast<uintptr_t>(roots_data) + index_in_table * sizeof(GcRoot<mirror::Object>);
9497 uint8_t* data = code + literal_offset;
9498 reinterpret_cast<uint32_t*>(data)[0] = dchecked_integral_cast<uint32_t>(address);
9499 }
9500
EmitJitRootPatches(uint8_t * code,const uint8_t * roots_data)9501 void CodeGeneratorARMVIXL::EmitJitRootPatches(uint8_t* code, const uint8_t* roots_data) {
9502 for (const auto& entry : jit_string_patches_) {
9503 const StringReference& string_reference = entry.first;
9504 VIXLUInt32Literal* table_entry_literal = entry.second;
9505 uint64_t index_in_table = GetJitStringRootIndex(string_reference);
9506 PatchJitRootUse(code, roots_data, table_entry_literal, index_in_table);
9507 }
9508 for (const auto& entry : jit_class_patches_) {
9509 const TypeReference& type_reference = entry.first;
9510 VIXLUInt32Literal* table_entry_literal = entry.second;
9511 uint64_t index_in_table = GetJitClassRootIndex(type_reference);
9512 PatchJitRootUse(code, roots_data, table_entry_literal, index_in_table);
9513 }
9514 }
9515
EmitMovwMovtPlaceholder(CodeGeneratorARMVIXL::PcRelativePatchInfo * labels,vixl32::Register out)9516 void CodeGeneratorARMVIXL::EmitMovwMovtPlaceholder(
9517 CodeGeneratorARMVIXL::PcRelativePatchInfo* labels,
9518 vixl32::Register out) {
9519 ExactAssemblyScope aas(GetVIXLAssembler(),
9520 3 * vixl32::kMaxInstructionSizeInBytes,
9521 CodeBufferCheckScope::kMaximumSize);
9522 // TODO(VIXL): Think about using mov instead of movw.
9523 __ bind(&labels->movw_label);
9524 __ movw(out, /* operand= */ 0u);
9525 __ bind(&labels->movt_label);
9526 __ movt(out, /* operand= */ 0u);
9527 __ bind(&labels->add_pc_label);
9528 __ add(out, out, pc);
9529 }
9530
9531 #undef __
9532 #undef QUICK_ENTRY_POINT
9533 #undef TODO_VIXL32
9534
9535 #define __ assembler.GetVIXLAssembler()->
9536
EmitGrayCheckAndFastPath(ArmVIXLAssembler & assembler,vixl32::Register base_reg,vixl32::MemOperand & lock_word,vixl32::Label * slow_path,int32_t raw_ldr_offset,vixl32::Label * throw_npe=nullptr)9537 static void EmitGrayCheckAndFastPath(ArmVIXLAssembler& assembler,
9538 vixl32::Register base_reg,
9539 vixl32::MemOperand& lock_word,
9540 vixl32::Label* slow_path,
9541 int32_t raw_ldr_offset,
9542 vixl32::Label* throw_npe = nullptr) {
9543 // Load the lock word containing the rb_state.
9544 __ Ldr(ip, lock_word);
9545 // Given the numeric representation, it's enough to check the low bit of the rb_state.
9546 static_assert(ReadBarrier::NonGrayState() == 0, "Expecting non-gray to have value 0");
9547 static_assert(ReadBarrier::GrayState() == 1, "Expecting gray to have value 1");
9548 __ Tst(ip, Operand(LockWord::kReadBarrierStateMaskShifted));
9549 __ B(ne, slow_path, /* is_far_target= */ false);
9550 // To throw NPE, we return to the fast path; the artificial dependence below does not matter.
9551 if (throw_npe != nullptr) {
9552 __ Bind(throw_npe);
9553 }
9554 __ Add(lr, lr, raw_ldr_offset);
9555 // Introduce a dependency on the lock_word including rb_state,
9556 // to prevent load-load reordering, and without using
9557 // a memory barrier (which would be more expensive).
9558 __ Add(base_reg, base_reg, Operand(ip, LSR, 32));
9559 __ Bx(lr); // And return back to the function.
9560 // Note: The fake dependency is unnecessary for the slow path.
9561 }
9562
9563 // Load the read barrier introspection entrypoint in register `entrypoint`
LoadReadBarrierMarkIntrospectionEntrypoint(ArmVIXLAssembler & assembler)9564 static vixl32::Register LoadReadBarrierMarkIntrospectionEntrypoint(ArmVIXLAssembler& assembler) {
9565 // The register where the read barrier introspection entrypoint is loaded
9566 // is the marking register. We clobber it here and the entrypoint restores it to 1.
9567 vixl32::Register entrypoint = mr;
9568 // entrypoint = Thread::Current()->pReadBarrierMarkReg12, i.e. pReadBarrierMarkIntrospection.
9569 DCHECK_EQ(ip.GetCode(), 12u);
9570 const int32_t entry_point_offset =
9571 Thread::ReadBarrierMarkEntryPointsOffset<kArmPointerSize>(ip.GetCode());
9572 __ Ldr(entrypoint, MemOperand(tr, entry_point_offset));
9573 return entrypoint;
9574 }
9575
CompileBakerReadBarrierThunk(ArmVIXLAssembler & assembler,uint32_t encoded_data,std::string * debug_name)9576 void CodeGeneratorARMVIXL::CompileBakerReadBarrierThunk(ArmVIXLAssembler& assembler,
9577 uint32_t encoded_data,
9578 /*out*/ std::string* debug_name) {
9579 BakerReadBarrierKind kind = BakerReadBarrierKindField::Decode(encoded_data);
9580 switch (kind) {
9581 case BakerReadBarrierKind::kField: {
9582 vixl32::Register base_reg(BakerReadBarrierFirstRegField::Decode(encoded_data));
9583 CheckValidReg(base_reg.GetCode());
9584 vixl32::Register holder_reg(BakerReadBarrierSecondRegField::Decode(encoded_data));
9585 CheckValidReg(holder_reg.GetCode());
9586 BakerReadBarrierWidth width = BakerReadBarrierWidthField::Decode(encoded_data);
9587 UseScratchRegisterScope temps(assembler.GetVIXLAssembler());
9588 temps.Exclude(ip);
9589 // In the case of a field load, if `base_reg` differs from
9590 // `holder_reg`, the offset was too large and we must have emitted (during the construction
9591 // of the HIR graph, see `art::HInstructionBuilder::BuildInstanceFieldAccess`) and preserved
9592 // (see `art::PrepareForRegisterAllocation::VisitNullCheck`) an explicit null check before
9593 // the load. Otherwise, for implicit null checks, we need to null-check the holder as we do
9594 // not necessarily do that check before going to the thunk.
9595 vixl32::Label throw_npe_label;
9596 vixl32::Label* throw_npe = nullptr;
9597 if (GetCompilerOptions().GetImplicitNullChecks() && holder_reg.Is(base_reg)) {
9598 throw_npe = &throw_npe_label;
9599 __ CompareAndBranchIfZero(holder_reg, throw_npe, /* is_far_target= */ false);
9600 }
9601 // Check if the holder is gray and, if not, add fake dependency to the base register
9602 // and return to the LDR instruction to load the reference. Otherwise, use introspection
9603 // to load the reference and call the entrypoint that performs further checks on the
9604 // reference and marks it if needed.
9605 vixl32::Label slow_path;
9606 MemOperand lock_word(holder_reg, mirror::Object::MonitorOffset().Int32Value());
9607 const int32_t raw_ldr_offset = (width == BakerReadBarrierWidth::kWide)
9608 ? BAKER_MARK_INTROSPECTION_FIELD_LDR_WIDE_OFFSET
9609 : BAKER_MARK_INTROSPECTION_FIELD_LDR_NARROW_OFFSET;
9610 EmitGrayCheckAndFastPath(
9611 assembler, base_reg, lock_word, &slow_path, raw_ldr_offset, throw_npe);
9612 __ Bind(&slow_path);
9613 const int32_t ldr_offset = /* Thumb state adjustment (LR contains Thumb state). */ -1 +
9614 raw_ldr_offset;
9615 vixl32::Register ep_reg = LoadReadBarrierMarkIntrospectionEntrypoint(assembler);
9616 if (width == BakerReadBarrierWidth::kWide) {
9617 MemOperand ldr_half_address(lr, ldr_offset + 2);
9618 __ Ldrh(ip, ldr_half_address); // Load the LDR immediate half-word with "Rt | imm12".
9619 __ Ubfx(ip, ip, 0, 12); // Extract the offset imm12.
9620 __ Ldr(ip, MemOperand(base_reg, ip)); // Load the reference.
9621 } else {
9622 MemOperand ldr_address(lr, ldr_offset);
9623 __ Ldrh(ip, ldr_address); // Load the LDR immediate, encoding T1.
9624 __ Add(ep_reg, // Adjust the entrypoint address to the entrypoint
9625 ep_reg, // for narrow LDR.
9626 Operand(BAKER_MARK_INTROSPECTION_FIELD_LDR_NARROW_ENTRYPOINT_OFFSET));
9627 __ Ubfx(ip, ip, 6, 5); // Extract the imm5, i.e. offset / 4.
9628 __ Ldr(ip, MemOperand(base_reg, ip, LSL, 2)); // Load the reference.
9629 }
9630 // Do not unpoison. With heap poisoning enabled, the entrypoint expects a poisoned reference.
9631 __ Bx(ep_reg); // Jump to the entrypoint.
9632 break;
9633 }
9634 case BakerReadBarrierKind::kArray: {
9635 vixl32::Register base_reg(BakerReadBarrierFirstRegField::Decode(encoded_data));
9636 CheckValidReg(base_reg.GetCode());
9637 DCHECK_EQ(kBakerReadBarrierInvalidEncodedReg,
9638 BakerReadBarrierSecondRegField::Decode(encoded_data));
9639 DCHECK(BakerReadBarrierWidthField::Decode(encoded_data) == BakerReadBarrierWidth::kWide);
9640 UseScratchRegisterScope temps(assembler.GetVIXLAssembler());
9641 temps.Exclude(ip);
9642 vixl32::Label slow_path;
9643 int32_t data_offset =
9644 mirror::Array::DataOffset(Primitive::ComponentSize(Primitive::kPrimNot)).Int32Value();
9645 MemOperand lock_word(base_reg, mirror::Object::MonitorOffset().Int32Value() - data_offset);
9646 DCHECK_LT(lock_word.GetOffsetImmediate(), 0);
9647 const int32_t raw_ldr_offset = BAKER_MARK_INTROSPECTION_ARRAY_LDR_OFFSET;
9648 EmitGrayCheckAndFastPath(assembler, base_reg, lock_word, &slow_path, raw_ldr_offset);
9649 __ Bind(&slow_path);
9650 const int32_t ldr_offset = /* Thumb state adjustment (LR contains Thumb state). */ -1 +
9651 raw_ldr_offset;
9652 MemOperand ldr_address(lr, ldr_offset + 2);
9653 __ Ldrb(ip, ldr_address); // Load the LDR (register) byte with "00 | imm2 | Rm",
9654 // i.e. Rm+32 because the scale in imm2 is 2.
9655 vixl32::Register ep_reg = LoadReadBarrierMarkIntrospectionEntrypoint(assembler);
9656 __ Bfi(ep_reg, ip, 3, 6); // Insert ip to the entrypoint address to create
9657 // a switch case target based on the index register.
9658 __ Mov(ip, base_reg); // Move the base register to ip0.
9659 __ Bx(ep_reg); // Jump to the entrypoint's array switch case.
9660 break;
9661 }
9662 case BakerReadBarrierKind::kGcRoot:
9663 case BakerReadBarrierKind::kUnsafeCas: {
9664 // Check if the reference needs to be marked and if so (i.e. not null, not marked yet
9665 // and it does not have a forwarding address), call the correct introspection entrypoint;
9666 // otherwise return the reference (or the extracted forwarding address).
9667 // There is no gray bit check for GC roots.
9668 vixl32::Register root_reg(BakerReadBarrierFirstRegField::Decode(encoded_data));
9669 CheckValidReg(root_reg.GetCode());
9670 DCHECK_EQ(kBakerReadBarrierInvalidEncodedReg,
9671 BakerReadBarrierSecondRegField::Decode(encoded_data));
9672 BakerReadBarrierWidth width = BakerReadBarrierWidthField::Decode(encoded_data);
9673 UseScratchRegisterScope temps(assembler.GetVIXLAssembler());
9674 temps.Exclude(ip);
9675 vixl32::Label return_label, not_marked, forwarding_address;
9676 __ CompareAndBranchIfZero(root_reg, &return_label, /* is_far_target= */ false);
9677 MemOperand lock_word(root_reg, mirror::Object::MonitorOffset().Int32Value());
9678 __ Ldr(ip, lock_word);
9679 __ Tst(ip, LockWord::kMarkBitStateMaskShifted);
9680 __ B(eq, ¬_marked);
9681 __ Bind(&return_label);
9682 __ Bx(lr);
9683 __ Bind(¬_marked);
9684 static_assert(LockWord::kStateShift == 30 && LockWord::kStateForwardingAddress == 3,
9685 "To use 'CMP ip, #modified-immediate; BHS', we need the lock word state in "
9686 " the highest bits and the 'forwarding address' state to have all bits set");
9687 __ Cmp(ip, Operand(0xc0000000));
9688 __ B(hs, &forwarding_address);
9689 vixl32::Register ep_reg = LoadReadBarrierMarkIntrospectionEntrypoint(assembler);
9690 // Adjust the art_quick_read_barrier_mark_introspection address in kBakerCcEntrypointRegister
9691 // to one of art_quick_read_barrier_mark_introspection_{gc_roots_{wide,narrow},unsafe_cas}.
9692 DCHECK(kind != BakerReadBarrierKind::kUnsafeCas || width == BakerReadBarrierWidth::kWide);
9693 int32_t entrypoint_offset =
9694 (kind == BakerReadBarrierKind::kGcRoot)
9695 ? (width == BakerReadBarrierWidth::kWide)
9696 ? BAKER_MARK_INTROSPECTION_GC_ROOT_LDR_WIDE_ENTRYPOINT_OFFSET
9697 : BAKER_MARK_INTROSPECTION_GC_ROOT_LDR_NARROW_ENTRYPOINT_OFFSET
9698 : BAKER_MARK_INTROSPECTION_UNSAFE_CAS_ENTRYPOINT_OFFSET;
9699 __ Add(ep_reg, ep_reg, Operand(entrypoint_offset));
9700 __ Mov(ip, root_reg);
9701 __ Bx(ep_reg);
9702 __ Bind(&forwarding_address);
9703 __ Lsl(root_reg, ip, LockWord::kForwardingAddressShift);
9704 __ Bx(lr);
9705 break;
9706 }
9707 default:
9708 LOG(FATAL) << "Unexpected kind: " << static_cast<uint32_t>(kind);
9709 UNREACHABLE();
9710 }
9711
9712 // For JIT, the slow path is considered part of the compiled method,
9713 // so JIT should pass null as `debug_name`. Tests may not have a runtime.
9714 DCHECK(Runtime::Current() == nullptr ||
9715 !Runtime::Current()->UseJitCompilation() ||
9716 debug_name == nullptr);
9717 if (debug_name != nullptr && GetCompilerOptions().GenerateAnyDebugInfo()) {
9718 std::ostringstream oss;
9719 oss << "BakerReadBarrierThunk";
9720 switch (kind) {
9721 case BakerReadBarrierKind::kField:
9722 oss << "Field";
9723 if (BakerReadBarrierWidthField::Decode(encoded_data) == BakerReadBarrierWidth::kWide) {
9724 oss << "Wide";
9725 }
9726 oss << "_r" << BakerReadBarrierFirstRegField::Decode(encoded_data)
9727 << "_r" << BakerReadBarrierSecondRegField::Decode(encoded_data);
9728 break;
9729 case BakerReadBarrierKind::kArray:
9730 oss << "Array_r" << BakerReadBarrierFirstRegField::Decode(encoded_data);
9731 DCHECK_EQ(kBakerReadBarrierInvalidEncodedReg,
9732 BakerReadBarrierSecondRegField::Decode(encoded_data));
9733 DCHECK(BakerReadBarrierWidthField::Decode(encoded_data) == BakerReadBarrierWidth::kWide);
9734 break;
9735 case BakerReadBarrierKind::kGcRoot:
9736 oss << "GcRoot";
9737 if (BakerReadBarrierWidthField::Decode(encoded_data) == BakerReadBarrierWidth::kWide) {
9738 oss << "Wide";
9739 }
9740 oss << "_r" << BakerReadBarrierFirstRegField::Decode(encoded_data);
9741 DCHECK_EQ(kBakerReadBarrierInvalidEncodedReg,
9742 BakerReadBarrierSecondRegField::Decode(encoded_data));
9743 break;
9744 case BakerReadBarrierKind::kUnsafeCas:
9745 oss << "UnsafeCas_r" << BakerReadBarrierFirstRegField::Decode(encoded_data);
9746 DCHECK_EQ(kBakerReadBarrierInvalidEncodedReg,
9747 BakerReadBarrierSecondRegField::Decode(encoded_data));
9748 DCHECK(BakerReadBarrierWidthField::Decode(encoded_data) == BakerReadBarrierWidth::kWide);
9749 break;
9750 }
9751 *debug_name = oss.str();
9752 }
9753 }
9754
9755 #undef __
9756
9757 } // namespace arm
9758 } // namespace art
9759