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