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