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