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