1 //===-- ARMFastISel.cpp - ARM FastISel implementation ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ARM-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // ARMGenFastISel.inc, which is #included here.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "ARM.h"
17 #include "ARMBaseInstrInfo.h"
18 #include "ARMBaseRegisterInfo.h"
19 #include "ARMCallingConv.h"
20 #include "ARMConstantPoolValue.h"
21 #include "ARMISelLowering.h"
22 #include "ARMMachineFunctionInfo.h"
23 #include "ARMSubtarget.h"
24 #include "MCTargetDesc/ARMAddressingModes.h"
25 #include "MCTargetDesc/ARMBaseInfo.h"
26 #include "llvm/ADT/APFloat.h"
27 #include "llvm/ADT/APInt.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/CodeGen/CallingConvLower.h"
32 #include "llvm/CodeGen/FastISel.h"
33 #include "llvm/CodeGen/FunctionLoweringInfo.h"
34 #include "llvm/CodeGen/ISDOpcodes.h"
35 #include "llvm/CodeGen/MachineConstantPool.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineMemOperand.h"
40 #include "llvm/CodeGen/MachineOperand.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/MachineValueType.h"
43 #include "llvm/CodeGen/RuntimeLibcalls.h"
44 #include "llvm/CodeGen/ValueTypes.h"
45 #include "llvm/IR/Argument.h"
46 #include "llvm/IR/Attributes.h"
47 #include "llvm/IR/CallSite.h"
48 #include "llvm/IR/CallingConv.h"
49 #include "llvm/IR/Constant.h"
50 #include "llvm/IR/Constants.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GetElementPtrTypeIterator.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/GlobalVariable.h"
57 #include "llvm/IR/InstrTypes.h"
58 #include "llvm/IR/Instruction.h"
59 #include "llvm/IR/Instructions.h"
60 #include "llvm/IR/IntrinsicInst.h"
61 #include "llvm/IR/Module.h"
62 #include "llvm/IR/Operator.h"
63 #include "llvm/IR/Type.h"
64 #include "llvm/IR/User.h"
65 #include "llvm/IR/Value.h"
66 #include "llvm/MC/MCInstrDesc.h"
67 #include "llvm/MC/MCRegisterInfo.h"
68 #include "llvm/Support/Casting.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Target/TargetInstrInfo.h"
73 #include "llvm/Target/TargetLowering.h"
74 #include "llvm/Target/TargetMachine.h"
75 #include "llvm/Target/TargetOptions.h"
76 #include <cassert>
77 #include <cstdint>
78 #include <utility>
79 
80 using namespace llvm;
81 
82 namespace {
83 
84   // All possible address modes, plus some.
85   typedef struct Address {
86     enum {
87       RegBase,
88       FrameIndexBase
89     } BaseType = RegBase;
90 
91     union {
92       unsigned Reg;
93       int FI;
94     } Base;
95 
96     int Offset = 0;
97 
98     // Innocuous defaults for our address.
99     Address() {
100       Base.Reg = 0;
101     }
102   } Address;
103 
104 class ARMFastISel final : public FastISel {
105   /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
106   /// make the right decision when generating code for different targets.
107   const ARMSubtarget *Subtarget;
108   Module &M;
109   const TargetMachine &TM;
110   const TargetInstrInfo &TII;
111   const TargetLowering &TLI;
112   ARMFunctionInfo *AFI;
113 
114   // Convenience variables to avoid some queries.
115   bool isThumb2;
116   LLVMContext *Context;
117 
118   public:
119     explicit ARMFastISel(FunctionLoweringInfo &funcInfo,
120                          const TargetLibraryInfo *libInfo)
121         : FastISel(funcInfo, libInfo),
122           Subtarget(
123               &static_cast<const ARMSubtarget &>(funcInfo.MF->getSubtarget())),
124           M(const_cast<Module &>(*funcInfo.Fn->getParent())),
125           TM(funcInfo.MF->getTarget()), TII(*Subtarget->getInstrInfo()),
126           TLI(*Subtarget->getTargetLowering()) {
127       AFI = funcInfo.MF->getInfo<ARMFunctionInfo>();
128       isThumb2 = AFI->isThumbFunction();
129       Context = &funcInfo.Fn->getContext();
130     }
131 
132   private:
133     // Code from FastISel.cpp.
134 
135     unsigned fastEmitInst_r(unsigned MachineInstOpcode,
136                             const TargetRegisterClass *RC,
137                             unsigned Op0, bool Op0IsKill);
138     unsigned fastEmitInst_rr(unsigned MachineInstOpcode,
139                              const TargetRegisterClass *RC,
140                              unsigned Op0, bool Op0IsKill,
141                              unsigned Op1, bool Op1IsKill);
142     unsigned fastEmitInst_ri(unsigned MachineInstOpcode,
143                              const TargetRegisterClass *RC,
144                              unsigned Op0, bool Op0IsKill,
145                              uint64_t Imm);
146     unsigned fastEmitInst_i(unsigned MachineInstOpcode,
147                             const TargetRegisterClass *RC,
148                             uint64_t Imm);
149 
150     // Backend specific FastISel code.
151 
152     bool fastSelectInstruction(const Instruction *I) override;
153     unsigned fastMaterializeConstant(const Constant *C) override;
154     unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
155     bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
156                              const LoadInst *LI) override;
157     bool fastLowerArguments() override;
158 
159   #include "ARMGenFastISel.inc"
160 
161     // Instruction selection routines.
162 
163     bool SelectLoad(const Instruction *I);
164     bool SelectStore(const Instruction *I);
165     bool SelectBranch(const Instruction *I);
166     bool SelectIndirectBr(const Instruction *I);
167     bool SelectCmp(const Instruction *I);
168     bool SelectFPExt(const Instruction *I);
169     bool SelectFPTrunc(const Instruction *I);
170     bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
171     bool SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode);
172     bool SelectIToFP(const Instruction *I, bool isSigned);
173     bool SelectFPToI(const Instruction *I, bool isSigned);
174     bool SelectDiv(const Instruction *I, bool isSigned);
175     bool SelectRem(const Instruction *I, bool isSigned);
176     bool SelectCall(const Instruction *I, const char *IntrMemName);
177     bool SelectIntrinsicCall(const IntrinsicInst &I);
178     bool SelectSelect(const Instruction *I);
179     bool SelectRet(const Instruction *I);
180     bool SelectTrunc(const Instruction *I);
181     bool SelectIntExt(const Instruction *I);
182     bool SelectShift(const Instruction *I, ARM_AM::ShiftOpc ShiftTy);
183 
184     // Utility routines.
185 
186     bool isPositionIndependent() const;
187     bool isTypeLegal(Type *Ty, MVT &VT);
188     bool isLoadTypeLegal(Type *Ty, MVT &VT);
189     bool ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
190                     bool isZExt);
191     bool ARMEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
192                      unsigned Alignment = 0, bool isZExt = true,
193                      bool allocReg = true);
194     bool ARMEmitStore(MVT VT, unsigned SrcReg, Address &Addr,
195                       unsigned Alignment = 0);
196     bool ARMComputeAddress(const Value *Obj, Address &Addr);
197     void ARMSimplifyAddress(Address &Addr, MVT VT, bool useAM3);
198     bool ARMIsMemCpySmall(uint64_t Len);
199     bool ARMTryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
200                                unsigned Alignment);
201     unsigned ARMEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
202     unsigned ARMMaterializeFP(const ConstantFP *CFP, MVT VT);
203     unsigned ARMMaterializeInt(const Constant *C, MVT VT);
204     unsigned ARMMaterializeGV(const GlobalValue *GV, MVT VT);
205     unsigned ARMMoveToFPReg(MVT VT, unsigned SrcReg);
206     unsigned ARMMoveToIntReg(MVT VT, unsigned SrcReg);
207     unsigned ARMSelectCallOp(bool UseReg);
208     unsigned ARMLowerPICELF(const GlobalValue *GV, unsigned Align, MVT VT);
209 
210     const TargetLowering *getTargetLowering() { return &TLI; }
211 
212     // Call handling routines.
213 
214     CCAssignFn *CCAssignFnForCall(CallingConv::ID CC,
215                                   bool Return,
216                                   bool isVarArg);
217     bool ProcessCallArgs(SmallVectorImpl<Value*> &Args,
218                          SmallVectorImpl<unsigned> &ArgRegs,
219                          SmallVectorImpl<MVT> &ArgVTs,
220                          SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
221                          SmallVectorImpl<unsigned> &RegArgs,
222                          CallingConv::ID CC,
223                          unsigned &NumBytes,
224                          bool isVarArg);
225     unsigned getLibcallReg(const Twine &Name);
226     bool FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
227                     const Instruction *I, CallingConv::ID CC,
228                     unsigned &NumBytes, bool isVarArg);
229     bool ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call);
230 
231     // OptionalDef handling routines.
232 
233     bool isARMNEONPred(const MachineInstr *MI);
234     bool DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR);
235     const MachineInstrBuilder &AddOptionalDefs(const MachineInstrBuilder &MIB);
236     void AddLoadStoreOperands(MVT VT, Address &Addr,
237                               const MachineInstrBuilder &MIB,
238                               MachineMemOperand::Flags Flags, bool useAM3);
239 };
240 
241 } // end anonymous namespace
242 
243 #include "ARMGenCallingConv.inc"
244 
245 // DefinesOptionalPredicate - This is different from DefinesPredicate in that
246 // we don't care about implicit defs here, just places we'll need to add a
247 // default CCReg argument. Sets CPSR if we're setting CPSR instead of CCR.
248 bool ARMFastISel::DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR) {
249   if (!MI->hasOptionalDef())
250     return false;
251 
252   // Look to see if our OptionalDef is defining CPSR or CCR.
253   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
254     const MachineOperand &MO = MI->getOperand(i);
255     if (!MO.isReg() || !MO.isDef()) continue;
256     if (MO.getReg() == ARM::CPSR)
257       *CPSR = true;
258   }
259   return true;
260 }
261 
262 bool ARMFastISel::isARMNEONPred(const MachineInstr *MI) {
263   const MCInstrDesc &MCID = MI->getDesc();
264 
265   // If we're a thumb2 or not NEON function we'll be handled via isPredicable.
266   if ((MCID.TSFlags & ARMII::DomainMask) != ARMII::DomainNEON ||
267        AFI->isThumb2Function())
268     return MI->isPredicable();
269 
270   for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i)
271     if (MCID.OpInfo[i].isPredicate())
272       return true;
273 
274   return false;
275 }
276 
277 // If the machine is predicable go ahead and add the predicate operands, if
278 // it needs default CC operands add those.
279 // TODO: If we want to support thumb1 then we'll need to deal with optional
280 // CPSR defs that need to be added before the remaining operands. See s_cc_out
281 // for descriptions why.
282 const MachineInstrBuilder &
283 ARMFastISel::AddOptionalDefs(const MachineInstrBuilder &MIB) {
284   MachineInstr *MI = &*MIB;
285 
286   // Do we use a predicate? or...
287   // Are we NEON in ARM mode and have a predicate operand? If so, I know
288   // we're not predicable but add it anyways.
289   if (isARMNEONPred(MI))
290     MIB.add(predOps(ARMCC::AL));
291 
292   // Do we optionally set a predicate?  Preds is size > 0 iff the predicate
293   // defines CPSR. All other OptionalDefines in ARM are the CCR register.
294   bool CPSR = false;
295   if (DefinesOptionalPredicate(MI, &CPSR))
296     MIB.add(CPSR ? t1CondCodeOp() : condCodeOp());
297   return MIB;
298 }
299 
300 unsigned ARMFastISel::fastEmitInst_r(unsigned MachineInstOpcode,
301                                      const TargetRegisterClass *RC,
302                                      unsigned Op0, bool Op0IsKill) {
303   unsigned ResultReg = createResultReg(RC);
304   const MCInstrDesc &II = TII.get(MachineInstOpcode);
305 
306   // Make sure the input operand is sufficiently constrained to be legal
307   // for this instruction.
308   Op0 = constrainOperandRegClass(II, Op0, 1);
309   if (II.getNumDefs() >= 1) {
310     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II,
311                             ResultReg).addReg(Op0, Op0IsKill * RegState::Kill));
312   } else {
313     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
314                    .addReg(Op0, Op0IsKill * RegState::Kill));
315     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
316                    TII.get(TargetOpcode::COPY), ResultReg)
317                    .addReg(II.ImplicitDefs[0]));
318   }
319   return ResultReg;
320 }
321 
322 unsigned ARMFastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
323                                       const TargetRegisterClass *RC,
324                                       unsigned Op0, bool Op0IsKill,
325                                       unsigned Op1, bool Op1IsKill) {
326   unsigned ResultReg = createResultReg(RC);
327   const MCInstrDesc &II = TII.get(MachineInstOpcode);
328 
329   // Make sure the input operands are sufficiently constrained to be legal
330   // for this instruction.
331   Op0 = constrainOperandRegClass(II, Op0, 1);
332   Op1 = constrainOperandRegClass(II, Op1, 2);
333 
334   if (II.getNumDefs() >= 1) {
335     AddOptionalDefs(
336         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
337             .addReg(Op0, Op0IsKill * RegState::Kill)
338             .addReg(Op1, Op1IsKill * RegState::Kill));
339   } else {
340     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
341                    .addReg(Op0, Op0IsKill * RegState::Kill)
342                    .addReg(Op1, Op1IsKill * RegState::Kill));
343     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
344                            TII.get(TargetOpcode::COPY), ResultReg)
345                    .addReg(II.ImplicitDefs[0]));
346   }
347   return ResultReg;
348 }
349 
350 unsigned ARMFastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
351                                       const TargetRegisterClass *RC,
352                                       unsigned Op0, bool Op0IsKill,
353                                       uint64_t Imm) {
354   unsigned ResultReg = createResultReg(RC);
355   const MCInstrDesc &II = TII.get(MachineInstOpcode);
356 
357   // Make sure the input operand is sufficiently constrained to be legal
358   // for this instruction.
359   Op0 = constrainOperandRegClass(II, Op0, 1);
360   if (II.getNumDefs() >= 1) {
361     AddOptionalDefs(
362         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
363             .addReg(Op0, Op0IsKill * RegState::Kill)
364             .addImm(Imm));
365   } else {
366     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
367                    .addReg(Op0, Op0IsKill * RegState::Kill)
368                    .addImm(Imm));
369     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
370                            TII.get(TargetOpcode::COPY), ResultReg)
371                    .addReg(II.ImplicitDefs[0]));
372   }
373   return ResultReg;
374 }
375 
376 unsigned ARMFastISel::fastEmitInst_i(unsigned MachineInstOpcode,
377                                      const TargetRegisterClass *RC,
378                                      uint64_t Imm) {
379   unsigned ResultReg = createResultReg(RC);
380   const MCInstrDesc &II = TII.get(MachineInstOpcode);
381 
382   if (II.getNumDefs() >= 1) {
383     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II,
384                             ResultReg).addImm(Imm));
385   } else {
386     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
387                    .addImm(Imm));
388     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
389                            TII.get(TargetOpcode::COPY), ResultReg)
390                    .addReg(II.ImplicitDefs[0]));
391   }
392   return ResultReg;
393 }
394 
395 // TODO: Don't worry about 64-bit now, but when this is fixed remove the
396 // checks from the various callers.
397 unsigned ARMFastISel::ARMMoveToFPReg(MVT VT, unsigned SrcReg) {
398   if (VT == MVT::f64) return 0;
399 
400   unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
401   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
402                           TII.get(ARM::VMOVSR), MoveReg)
403                   .addReg(SrcReg));
404   return MoveReg;
405 }
406 
407 unsigned ARMFastISel::ARMMoveToIntReg(MVT VT, unsigned SrcReg) {
408   if (VT == MVT::i64) return 0;
409 
410   unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
411   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
412                           TII.get(ARM::VMOVRS), MoveReg)
413                   .addReg(SrcReg));
414   return MoveReg;
415 }
416 
417 // For double width floating point we need to materialize two constants
418 // (the high and the low) into integer registers then use a move to get
419 // the combined constant into an FP reg.
420 unsigned ARMFastISel::ARMMaterializeFP(const ConstantFP *CFP, MVT VT) {
421   const APFloat Val = CFP->getValueAPF();
422   bool is64bit = VT == MVT::f64;
423 
424   // This checks to see if we can use VFP3 instructions to materialize
425   // a constant, otherwise we have to go through the constant pool.
426   if (TLI.isFPImmLegal(Val, VT)) {
427     int Imm;
428     unsigned Opc;
429     if (is64bit) {
430       Imm = ARM_AM::getFP64Imm(Val);
431       Opc = ARM::FCONSTD;
432     } else {
433       Imm = ARM_AM::getFP32Imm(Val);
434       Opc = ARM::FCONSTS;
435     }
436     unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
437     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
438                             TII.get(Opc), DestReg).addImm(Imm));
439     return DestReg;
440   }
441 
442   // Require VFP2 for loading fp constants.
443   if (!Subtarget->hasVFP2()) return false;
444 
445   // MachineConstantPool wants an explicit alignment.
446   unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
447   if (Align == 0) {
448     // TODO: Figure out if this is correct.
449     Align = DL.getTypeAllocSize(CFP->getType());
450   }
451   unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
452   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
453   unsigned Opc = is64bit ? ARM::VLDRD : ARM::VLDRS;
454 
455   // The extra reg is for addrmode5.
456   AddOptionalDefs(
457       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
458           .addConstantPoolIndex(Idx)
459           .addReg(0));
460   return DestReg;
461 }
462 
463 unsigned ARMFastISel::ARMMaterializeInt(const Constant *C, MVT VT) {
464   if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8 && VT != MVT::i1)
465     return 0;
466 
467   // If we can do this in a single instruction without a constant pool entry
468   // do so now.
469   const ConstantInt *CI = cast<ConstantInt>(C);
470   if (Subtarget->hasV6T2Ops() && isUInt<16>(CI->getZExtValue())) {
471     unsigned Opc = isThumb2 ? ARM::t2MOVi16 : ARM::MOVi16;
472     const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass :
473       &ARM::GPRRegClass;
474     unsigned ImmReg = createResultReg(RC);
475     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
476                             TII.get(Opc), ImmReg)
477                     .addImm(CI->getZExtValue()));
478     return ImmReg;
479   }
480 
481   // Use MVN to emit negative constants.
482   if (VT == MVT::i32 && Subtarget->hasV6T2Ops() && CI->isNegative()) {
483     unsigned Imm = (unsigned)~(CI->getSExtValue());
484     bool UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
485       (ARM_AM::getSOImmVal(Imm) != -1);
486     if (UseImm) {
487       unsigned Opc = isThumb2 ? ARM::t2MVNi : ARM::MVNi;
488       const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass :
489                                                  &ARM::GPRRegClass;
490       unsigned ImmReg = createResultReg(RC);
491       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
492                               TII.get(Opc), ImmReg)
493                       .addImm(Imm));
494       return ImmReg;
495     }
496   }
497 
498   unsigned ResultReg = 0;
499   if (Subtarget->useMovt(*FuncInfo.MF))
500     ResultReg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
501 
502   if (ResultReg)
503     return ResultReg;
504 
505   // Load from constant pool.  For now 32-bit only.
506   if (VT != MVT::i32)
507     return 0;
508 
509   // MachineConstantPool wants an explicit alignment.
510   unsigned Align = DL.getPrefTypeAlignment(C->getType());
511   if (Align == 0) {
512     // TODO: Figure out if this is correct.
513     Align = DL.getTypeAllocSize(C->getType());
514   }
515   unsigned Idx = MCP.getConstantPoolIndex(C, Align);
516   ResultReg = createResultReg(TLI.getRegClassFor(VT));
517   if (isThumb2)
518     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
519                             TII.get(ARM::t2LDRpci), ResultReg)
520                       .addConstantPoolIndex(Idx));
521   else {
522     // The extra immediate is for addrmode2.
523     ResultReg = constrainOperandRegClass(TII.get(ARM::LDRcp), ResultReg, 0);
524     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
525                             TII.get(ARM::LDRcp), ResultReg)
526                       .addConstantPoolIndex(Idx)
527                       .addImm(0));
528   }
529   return ResultReg;
530 }
531 
532 bool ARMFastISel::isPositionIndependent() const {
533   return TLI.isPositionIndependent();
534 }
535 
536 unsigned ARMFastISel::ARMMaterializeGV(const GlobalValue *GV, MVT VT) {
537   // For now 32-bit only.
538   if (VT != MVT::i32 || GV->isThreadLocal()) return 0;
539 
540   // ROPI/RWPI not currently supported.
541   if (Subtarget->isROPI() || Subtarget->isRWPI())
542     return 0;
543 
544   bool IsIndirect = Subtarget->isGVIndirectSymbol(GV);
545   const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass
546                                            : &ARM::GPRRegClass;
547   unsigned DestReg = createResultReg(RC);
548 
549   // FastISel TLS support on non-MachO is broken, punt to SelectionDAG.
550   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
551   bool IsThreadLocal = GVar && GVar->isThreadLocal();
552   if (!Subtarget->isTargetMachO() && IsThreadLocal) return 0;
553 
554   bool IsPositionIndependent = isPositionIndependent();
555   // Use movw+movt when possible, it avoids constant pool entries.
556   // Non-darwin targets only support static movt relocations in FastISel.
557   if (Subtarget->useMovt(*FuncInfo.MF) &&
558       (Subtarget->isTargetMachO() || !IsPositionIndependent)) {
559     unsigned Opc;
560     unsigned char TF = 0;
561     if (Subtarget->isTargetMachO())
562       TF = ARMII::MO_NONLAZY;
563 
564     if (IsPositionIndependent)
565       Opc = isThumb2 ? ARM::t2MOV_ga_pcrel : ARM::MOV_ga_pcrel;
566     else
567       Opc = isThumb2 ? ARM::t2MOVi32imm : ARM::MOVi32imm;
568     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
569                             TII.get(Opc), DestReg).addGlobalAddress(GV, 0, TF));
570   } else {
571     // MachineConstantPool wants an explicit alignment.
572     unsigned Align = DL.getPrefTypeAlignment(GV->getType());
573     if (Align == 0) {
574       // TODO: Figure out if this is correct.
575       Align = DL.getTypeAllocSize(GV->getType());
576     }
577 
578     if (Subtarget->isTargetELF() && IsPositionIndependent)
579       return ARMLowerPICELF(GV, Align, VT);
580 
581     // Grab index.
582     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
583     unsigned Id = AFI->createPICLabelUId();
584     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(GV, Id,
585                                                                 ARMCP::CPValue,
586                                                                 PCAdj);
587     unsigned Idx = MCP.getConstantPoolIndex(CPV, Align);
588 
589     // Load value.
590     MachineInstrBuilder MIB;
591     if (isThumb2) {
592       unsigned Opc = IsPositionIndependent ? ARM::t2LDRpci_pic : ARM::t2LDRpci;
593       MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
594                     DestReg).addConstantPoolIndex(Idx);
595       if (IsPositionIndependent)
596         MIB.addImm(Id);
597       AddOptionalDefs(MIB);
598     } else {
599       // The extra immediate is for addrmode2.
600       DestReg = constrainOperandRegClass(TII.get(ARM::LDRcp), DestReg, 0);
601       MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
602                     TII.get(ARM::LDRcp), DestReg)
603                 .addConstantPoolIndex(Idx)
604                 .addImm(0);
605       AddOptionalDefs(MIB);
606 
607       if (IsPositionIndependent) {
608         unsigned Opc = IsIndirect ? ARM::PICLDR : ARM::PICADD;
609         unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
610 
611         MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
612                                           DbgLoc, TII.get(Opc), NewDestReg)
613                                   .addReg(DestReg)
614                                   .addImm(Id);
615         AddOptionalDefs(MIB);
616         return NewDestReg;
617       }
618     }
619   }
620 
621   if (IsIndirect) {
622     MachineInstrBuilder MIB;
623     unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
624     if (isThumb2)
625       MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
626                     TII.get(ARM::t2LDRi12), NewDestReg)
627             .addReg(DestReg)
628             .addImm(0);
629     else
630       MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
631                     TII.get(ARM::LDRi12), NewDestReg)
632                 .addReg(DestReg)
633                 .addImm(0);
634     DestReg = NewDestReg;
635     AddOptionalDefs(MIB);
636   }
637 
638   return DestReg;
639 }
640 
641 unsigned ARMFastISel::fastMaterializeConstant(const Constant *C) {
642   EVT CEVT = TLI.getValueType(DL, C->getType(), true);
643 
644   // Only handle simple types.
645   if (!CEVT.isSimple()) return 0;
646   MVT VT = CEVT.getSimpleVT();
647 
648   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
649     return ARMMaterializeFP(CFP, VT);
650   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
651     return ARMMaterializeGV(GV, VT);
652   else if (isa<ConstantInt>(C))
653     return ARMMaterializeInt(C, VT);
654 
655   return 0;
656 }
657 
658 // TODO: unsigned ARMFastISel::TargetMaterializeFloatZero(const ConstantFP *CF);
659 
660 unsigned ARMFastISel::fastMaterializeAlloca(const AllocaInst *AI) {
661   // Don't handle dynamic allocas.
662   if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
663 
664   MVT VT;
665   if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
666 
667   DenseMap<const AllocaInst*, int>::iterator SI =
668     FuncInfo.StaticAllocaMap.find(AI);
669 
670   // This will get lowered later into the correct offsets and registers
671   // via rewriteXFrameIndex.
672   if (SI != FuncInfo.StaticAllocaMap.end()) {
673     unsigned Opc = isThumb2 ? ARM::t2ADDri : ARM::ADDri;
674     const TargetRegisterClass* RC = TLI.getRegClassFor(VT);
675     unsigned ResultReg = createResultReg(RC);
676     ResultReg = constrainOperandRegClass(TII.get(Opc), ResultReg, 0);
677 
678     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
679                             TII.get(Opc), ResultReg)
680                             .addFrameIndex(SI->second)
681                             .addImm(0));
682     return ResultReg;
683   }
684 
685   return 0;
686 }
687 
688 bool ARMFastISel::isTypeLegal(Type *Ty, MVT &VT) {
689   EVT evt = TLI.getValueType(DL, Ty, true);
690 
691   // Only handle simple types.
692   if (evt == MVT::Other || !evt.isSimple()) return false;
693   VT = evt.getSimpleVT();
694 
695   // Handle all legal types, i.e. a register that will directly hold this
696   // value.
697   return TLI.isTypeLegal(VT);
698 }
699 
700 bool ARMFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
701   if (isTypeLegal(Ty, VT)) return true;
702 
703   // If this is a type than can be sign or zero-extended to a basic operation
704   // go ahead and accept it now.
705   if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
706     return true;
707 
708   return false;
709 }
710 
711 // Computes the address to get to an object.
712 bool ARMFastISel::ARMComputeAddress(const Value *Obj, Address &Addr) {
713   // Some boilerplate from the X86 FastISel.
714   const User *U = nullptr;
715   unsigned Opcode = Instruction::UserOp1;
716   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
717     // Don't walk into other basic blocks unless the object is an alloca from
718     // another block, otherwise it may not have a virtual register assigned.
719     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
720         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
721       Opcode = I->getOpcode();
722       U = I;
723     }
724   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
725     Opcode = C->getOpcode();
726     U = C;
727   }
728 
729   if (PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
730     if (Ty->getAddressSpace() > 255)
731       // Fast instruction selection doesn't support the special
732       // address spaces.
733       return false;
734 
735   switch (Opcode) {
736     default:
737     break;
738     case Instruction::BitCast:
739       // Look through bitcasts.
740       return ARMComputeAddress(U->getOperand(0), Addr);
741     case Instruction::IntToPtr:
742       // Look past no-op inttoptrs.
743       if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
744           TLI.getPointerTy(DL))
745         return ARMComputeAddress(U->getOperand(0), Addr);
746       break;
747     case Instruction::PtrToInt:
748       // Look past no-op ptrtoints.
749       if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
750         return ARMComputeAddress(U->getOperand(0), Addr);
751       break;
752     case Instruction::GetElementPtr: {
753       Address SavedAddr = Addr;
754       int TmpOffset = Addr.Offset;
755 
756       // Iterate through the GEP folding the constants into offsets where
757       // we can.
758       gep_type_iterator GTI = gep_type_begin(U);
759       for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
760            i != e; ++i, ++GTI) {
761         const Value *Op = *i;
762         if (StructType *STy = GTI.getStructTypeOrNull()) {
763           const StructLayout *SL = DL.getStructLayout(STy);
764           unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
765           TmpOffset += SL->getElementOffset(Idx);
766         } else {
767           uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
768           while (true) {
769             if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
770               // Constant-offset addressing.
771               TmpOffset += CI->getSExtValue() * S;
772               break;
773             }
774             if (canFoldAddIntoGEP(U, Op)) {
775               // A compatible add with a constant operand. Fold the constant.
776               ConstantInt *CI =
777               cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
778               TmpOffset += CI->getSExtValue() * S;
779               // Iterate on the other operand.
780               Op = cast<AddOperator>(Op)->getOperand(0);
781               continue;
782             }
783             // Unsupported
784             goto unsupported_gep;
785           }
786         }
787       }
788 
789       // Try to grab the base operand now.
790       Addr.Offset = TmpOffset;
791       if (ARMComputeAddress(U->getOperand(0), Addr)) return true;
792 
793       // We failed, restore everything and try the other options.
794       Addr = SavedAddr;
795 
796       unsupported_gep:
797       break;
798     }
799     case Instruction::Alloca: {
800       const AllocaInst *AI = cast<AllocaInst>(Obj);
801       DenseMap<const AllocaInst*, int>::iterator SI =
802         FuncInfo.StaticAllocaMap.find(AI);
803       if (SI != FuncInfo.StaticAllocaMap.end()) {
804         Addr.BaseType = Address::FrameIndexBase;
805         Addr.Base.FI = SI->second;
806         return true;
807       }
808       break;
809     }
810   }
811 
812   // Try to get this in a register if nothing else has worked.
813   if (Addr.Base.Reg == 0) Addr.Base.Reg = getRegForValue(Obj);
814   return Addr.Base.Reg != 0;
815 }
816 
817 void ARMFastISel::ARMSimplifyAddress(Address &Addr, MVT VT, bool useAM3) {
818   bool needsLowering = false;
819   switch (VT.SimpleTy) {
820     default: llvm_unreachable("Unhandled load/store type!");
821     case MVT::i1:
822     case MVT::i8:
823     case MVT::i16:
824     case MVT::i32:
825       if (!useAM3) {
826         // Integer loads/stores handle 12-bit offsets.
827         needsLowering = ((Addr.Offset & 0xfff) != Addr.Offset);
828         // Handle negative offsets.
829         if (needsLowering && isThumb2)
830           needsLowering = !(Subtarget->hasV6T2Ops() && Addr.Offset < 0 &&
831                             Addr.Offset > -256);
832       } else {
833         // ARM halfword load/stores and signed byte loads use +/-imm8 offsets.
834         needsLowering = (Addr.Offset > 255 || Addr.Offset < -255);
835       }
836       break;
837     case MVT::f32:
838     case MVT::f64:
839       // Floating point operands handle 8-bit offsets.
840       needsLowering = ((Addr.Offset & 0xff) != Addr.Offset);
841       break;
842   }
843 
844   // If this is a stack pointer and the offset needs to be simplified then
845   // put the alloca address into a register, set the base type back to
846   // register and continue. This should almost never happen.
847   if (needsLowering && Addr.BaseType == Address::FrameIndexBase) {
848     const TargetRegisterClass *RC = isThumb2 ? &ARM::tGPRRegClass
849                                              : &ARM::GPRRegClass;
850     unsigned ResultReg = createResultReg(RC);
851     unsigned Opc = isThumb2 ? ARM::t2ADDri : ARM::ADDri;
852     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
853                             TII.get(Opc), ResultReg)
854                             .addFrameIndex(Addr.Base.FI)
855                             .addImm(0));
856     Addr.Base.Reg = ResultReg;
857     Addr.BaseType = Address::RegBase;
858   }
859 
860   // Since the offset is too large for the load/store instruction
861   // get the reg+offset into a register.
862   if (needsLowering) {
863     Addr.Base.Reg = fastEmit_ri_(MVT::i32, ISD::ADD, Addr.Base.Reg,
864                                  /*Op0IsKill*/false, Addr.Offset, MVT::i32);
865     Addr.Offset = 0;
866   }
867 }
868 
869 void ARMFastISel::AddLoadStoreOperands(MVT VT, Address &Addr,
870                                        const MachineInstrBuilder &MIB,
871                                        MachineMemOperand::Flags Flags,
872                                        bool useAM3) {
873   // addrmode5 output depends on the selection dag addressing dividing the
874   // offset by 4 that it then later multiplies. Do this here as well.
875   if (VT.SimpleTy == MVT::f32 || VT.SimpleTy == MVT::f64)
876     Addr.Offset /= 4;
877 
878   // Frame base works a bit differently. Handle it separately.
879   if (Addr.BaseType == Address::FrameIndexBase) {
880     int FI = Addr.Base.FI;
881     int Offset = Addr.Offset;
882     MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
883         MachinePointerInfo::getFixedStack(*FuncInfo.MF, FI, Offset), Flags,
884         MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
885     // Now add the rest of the operands.
886     MIB.addFrameIndex(FI);
887 
888     // ARM halfword load/stores and signed byte loads need an additional
889     // operand.
890     if (useAM3) {
891       int Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
892       MIB.addReg(0);
893       MIB.addImm(Imm);
894     } else {
895       MIB.addImm(Addr.Offset);
896     }
897     MIB.addMemOperand(MMO);
898   } else {
899     // Now add the rest of the operands.
900     MIB.addReg(Addr.Base.Reg);
901 
902     // ARM halfword load/stores and signed byte loads need an additional
903     // operand.
904     if (useAM3) {
905       int Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
906       MIB.addReg(0);
907       MIB.addImm(Imm);
908     } else {
909       MIB.addImm(Addr.Offset);
910     }
911   }
912   AddOptionalDefs(MIB);
913 }
914 
915 bool ARMFastISel::ARMEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
916                               unsigned Alignment, bool isZExt, bool allocReg) {
917   unsigned Opc;
918   bool useAM3 = false;
919   bool needVMOV = false;
920   const TargetRegisterClass *RC;
921   switch (VT.SimpleTy) {
922     // This is mostly going to be Neon/vector support.
923     default: return false;
924     case MVT::i1:
925     case MVT::i8:
926       if (isThumb2) {
927         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
928           Opc = isZExt ? ARM::t2LDRBi8 : ARM::t2LDRSBi8;
929         else
930           Opc = isZExt ? ARM::t2LDRBi12 : ARM::t2LDRSBi12;
931       } else {
932         if (isZExt) {
933           Opc = ARM::LDRBi12;
934         } else {
935           Opc = ARM::LDRSB;
936           useAM3 = true;
937         }
938       }
939       RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
940       break;
941     case MVT::i16:
942       if (Alignment && Alignment < 2 && !Subtarget->allowsUnalignedMem())
943         return false;
944 
945       if (isThumb2) {
946         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
947           Opc = isZExt ? ARM::t2LDRHi8 : ARM::t2LDRSHi8;
948         else
949           Opc = isZExt ? ARM::t2LDRHi12 : ARM::t2LDRSHi12;
950       } else {
951         Opc = isZExt ? ARM::LDRH : ARM::LDRSH;
952         useAM3 = true;
953       }
954       RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
955       break;
956     case MVT::i32:
957       if (Alignment && Alignment < 4 && !Subtarget->allowsUnalignedMem())
958         return false;
959 
960       if (isThumb2) {
961         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
962           Opc = ARM::t2LDRi8;
963         else
964           Opc = ARM::t2LDRi12;
965       } else {
966         Opc = ARM::LDRi12;
967       }
968       RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
969       break;
970     case MVT::f32:
971       if (!Subtarget->hasVFP2()) return false;
972       // Unaligned loads need special handling. Floats require word-alignment.
973       if (Alignment && Alignment < 4) {
974         needVMOV = true;
975         VT = MVT::i32;
976         Opc = isThumb2 ? ARM::t2LDRi12 : ARM::LDRi12;
977         RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
978       } else {
979         Opc = ARM::VLDRS;
980         RC = TLI.getRegClassFor(VT);
981       }
982       break;
983     case MVT::f64:
984       if (!Subtarget->hasVFP2()) return false;
985       // FIXME: Unaligned loads need special handling.  Doublewords require
986       // word-alignment.
987       if (Alignment && Alignment < 4)
988         return false;
989 
990       Opc = ARM::VLDRD;
991       RC = TLI.getRegClassFor(VT);
992       break;
993   }
994   // Simplify this down to something we can handle.
995   ARMSimplifyAddress(Addr, VT, useAM3);
996 
997   // Create the base instruction, then add the operands.
998   if (allocReg)
999     ResultReg = createResultReg(RC);
1000   assert(ResultReg > 255 && "Expected an allocated virtual register.");
1001   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1002                                     TII.get(Opc), ResultReg);
1003   AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOLoad, useAM3);
1004 
1005   // If we had an unaligned load of a float we've converted it to an regular
1006   // load.  Now we must move from the GRP to the FP register.
1007   if (needVMOV) {
1008     unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1009     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1010                             TII.get(ARM::VMOVSR), MoveReg)
1011                     .addReg(ResultReg));
1012     ResultReg = MoveReg;
1013   }
1014   return true;
1015 }
1016 
1017 bool ARMFastISel::SelectLoad(const Instruction *I) {
1018   // Atomic loads need special handling.
1019   if (cast<LoadInst>(I)->isAtomic())
1020     return false;
1021 
1022   const Value *SV = I->getOperand(0);
1023   if (TLI.supportSwiftError()) {
1024     // Swifterror values can come from either a function parameter with
1025     // swifterror attribute or an alloca with swifterror attribute.
1026     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1027       if (Arg->hasSwiftErrorAttr())
1028         return false;
1029     }
1030 
1031     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1032       if (Alloca->isSwiftError())
1033         return false;
1034     }
1035   }
1036 
1037   // Verify we have a legal type before going any further.
1038   MVT VT;
1039   if (!isLoadTypeLegal(I->getType(), VT))
1040     return false;
1041 
1042   // See if we can handle this address.
1043   Address Addr;
1044   if (!ARMComputeAddress(I->getOperand(0), Addr)) return false;
1045 
1046   unsigned ResultReg;
1047   if (!ARMEmitLoad(VT, ResultReg, Addr, cast<LoadInst>(I)->getAlignment()))
1048     return false;
1049   updateValueMap(I, ResultReg);
1050   return true;
1051 }
1052 
1053 bool ARMFastISel::ARMEmitStore(MVT VT, unsigned SrcReg, Address &Addr,
1054                                unsigned Alignment) {
1055   unsigned StrOpc;
1056   bool useAM3 = false;
1057   switch (VT.SimpleTy) {
1058     // This is mostly going to be Neon/vector support.
1059     default: return false;
1060     case MVT::i1: {
1061       unsigned Res = createResultReg(isThumb2 ? &ARM::tGPRRegClass
1062                                               : &ARM::GPRRegClass);
1063       unsigned Opc = isThumb2 ? ARM::t2ANDri : ARM::ANDri;
1064       SrcReg = constrainOperandRegClass(TII.get(Opc), SrcReg, 1);
1065       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1066                               TII.get(Opc), Res)
1067                       .addReg(SrcReg).addImm(1));
1068       SrcReg = Res;
1069       LLVM_FALLTHROUGH;
1070     }
1071     case MVT::i8:
1072       if (isThumb2) {
1073         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1074           StrOpc = ARM::t2STRBi8;
1075         else
1076           StrOpc = ARM::t2STRBi12;
1077       } else {
1078         StrOpc = ARM::STRBi12;
1079       }
1080       break;
1081     case MVT::i16:
1082       if (Alignment && Alignment < 2 && !Subtarget->allowsUnalignedMem())
1083         return false;
1084 
1085       if (isThumb2) {
1086         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1087           StrOpc = ARM::t2STRHi8;
1088         else
1089           StrOpc = ARM::t2STRHi12;
1090       } else {
1091         StrOpc = ARM::STRH;
1092         useAM3 = true;
1093       }
1094       break;
1095     case MVT::i32:
1096       if (Alignment && Alignment < 4 && !Subtarget->allowsUnalignedMem())
1097         return false;
1098 
1099       if (isThumb2) {
1100         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1101           StrOpc = ARM::t2STRi8;
1102         else
1103           StrOpc = ARM::t2STRi12;
1104       } else {
1105         StrOpc = ARM::STRi12;
1106       }
1107       break;
1108     case MVT::f32:
1109       if (!Subtarget->hasVFP2()) return false;
1110       // Unaligned stores need special handling. Floats require word-alignment.
1111       if (Alignment && Alignment < 4) {
1112         unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::i32));
1113         AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1114                                 TII.get(ARM::VMOVRS), MoveReg)
1115                         .addReg(SrcReg));
1116         SrcReg = MoveReg;
1117         VT = MVT::i32;
1118         StrOpc = isThumb2 ? ARM::t2STRi12 : ARM::STRi12;
1119       } else {
1120         StrOpc = ARM::VSTRS;
1121       }
1122       break;
1123     case MVT::f64:
1124       if (!Subtarget->hasVFP2()) return false;
1125       // FIXME: Unaligned stores need special handling.  Doublewords require
1126       // word-alignment.
1127       if (Alignment && Alignment < 4)
1128           return false;
1129 
1130       StrOpc = ARM::VSTRD;
1131       break;
1132   }
1133   // Simplify this down to something we can handle.
1134   ARMSimplifyAddress(Addr, VT, useAM3);
1135 
1136   // Create the base instruction, then add the operands.
1137   SrcReg = constrainOperandRegClass(TII.get(StrOpc), SrcReg, 0);
1138   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1139                                     TII.get(StrOpc))
1140                             .addReg(SrcReg);
1141   AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOStore, useAM3);
1142   return true;
1143 }
1144 
1145 bool ARMFastISel::SelectStore(const Instruction *I) {
1146   Value *Op0 = I->getOperand(0);
1147   unsigned SrcReg = 0;
1148 
1149   // Atomic stores need special handling.
1150   if (cast<StoreInst>(I)->isAtomic())
1151     return false;
1152 
1153   const Value *PtrV = I->getOperand(1);
1154   if (TLI.supportSwiftError()) {
1155     // Swifterror values can come from either a function parameter with
1156     // swifterror attribute or an alloca with swifterror attribute.
1157     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1158       if (Arg->hasSwiftErrorAttr())
1159         return false;
1160     }
1161 
1162     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1163       if (Alloca->isSwiftError())
1164         return false;
1165     }
1166   }
1167 
1168   // Verify we have a legal type before going any further.
1169   MVT VT;
1170   if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
1171     return false;
1172 
1173   // Get the value to be stored into a register.
1174   SrcReg = getRegForValue(Op0);
1175   if (SrcReg == 0) return false;
1176 
1177   // See if we can handle this address.
1178   Address Addr;
1179   if (!ARMComputeAddress(I->getOperand(1), Addr))
1180     return false;
1181 
1182   if (!ARMEmitStore(VT, SrcReg, Addr, cast<StoreInst>(I)->getAlignment()))
1183     return false;
1184   return true;
1185 }
1186 
1187 static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
1188   switch (Pred) {
1189     // Needs two compares...
1190     case CmpInst::FCMP_ONE:
1191     case CmpInst::FCMP_UEQ:
1192     default:
1193       // AL is our "false" for now. The other two need more compares.
1194       return ARMCC::AL;
1195     case CmpInst::ICMP_EQ:
1196     case CmpInst::FCMP_OEQ:
1197       return ARMCC::EQ;
1198     case CmpInst::ICMP_SGT:
1199     case CmpInst::FCMP_OGT:
1200       return ARMCC::GT;
1201     case CmpInst::ICMP_SGE:
1202     case CmpInst::FCMP_OGE:
1203       return ARMCC::GE;
1204     case CmpInst::ICMP_UGT:
1205     case CmpInst::FCMP_UGT:
1206       return ARMCC::HI;
1207     case CmpInst::FCMP_OLT:
1208       return ARMCC::MI;
1209     case CmpInst::ICMP_ULE:
1210     case CmpInst::FCMP_OLE:
1211       return ARMCC::LS;
1212     case CmpInst::FCMP_ORD:
1213       return ARMCC::VC;
1214     case CmpInst::FCMP_UNO:
1215       return ARMCC::VS;
1216     case CmpInst::FCMP_UGE:
1217       return ARMCC::PL;
1218     case CmpInst::ICMP_SLT:
1219     case CmpInst::FCMP_ULT:
1220       return ARMCC::LT;
1221     case CmpInst::ICMP_SLE:
1222     case CmpInst::FCMP_ULE:
1223       return ARMCC::LE;
1224     case CmpInst::FCMP_UNE:
1225     case CmpInst::ICMP_NE:
1226       return ARMCC::NE;
1227     case CmpInst::ICMP_UGE:
1228       return ARMCC::HS;
1229     case CmpInst::ICMP_ULT:
1230       return ARMCC::LO;
1231   }
1232 }
1233 
1234 bool ARMFastISel::SelectBranch(const Instruction *I) {
1235   const BranchInst *BI = cast<BranchInst>(I);
1236   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1237   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1238 
1239   // Simple branch support.
1240 
1241   // If we can, avoid recomputing the compare - redoing it could lead to wonky
1242   // behavior.
1243   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1244     if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
1245       // Get the compare predicate.
1246       // Try to take advantage of fallthrough opportunities.
1247       CmpInst::Predicate Predicate = CI->getPredicate();
1248       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1249         std::swap(TBB, FBB);
1250         Predicate = CmpInst::getInversePredicate(Predicate);
1251       }
1252 
1253       ARMCC::CondCodes ARMPred = getComparePred(Predicate);
1254 
1255       // We may not handle every CC for now.
1256       if (ARMPred == ARMCC::AL) return false;
1257 
1258       // Emit the compare.
1259       if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1260         return false;
1261 
1262       unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1263       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BrOpc))
1264       .addMBB(TBB).addImm(ARMPred).addReg(ARM::CPSR);
1265       finishCondBranch(BI->getParent(), TBB, FBB);
1266       return true;
1267     }
1268   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1269     MVT SourceVT;
1270     if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1271         (isLoadTypeLegal(TI->getOperand(0)->getType(), SourceVT))) {
1272       unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1273       unsigned OpReg = getRegForValue(TI->getOperand(0));
1274       OpReg = constrainOperandRegClass(TII.get(TstOpc), OpReg, 0);
1275       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1276                               TII.get(TstOpc))
1277                       .addReg(OpReg).addImm(1));
1278 
1279       unsigned CCMode = ARMCC::NE;
1280       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1281         std::swap(TBB, FBB);
1282         CCMode = ARMCC::EQ;
1283       }
1284 
1285       unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1286       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BrOpc))
1287       .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1288 
1289       finishCondBranch(BI->getParent(), TBB, FBB);
1290       return true;
1291     }
1292   } else if (const ConstantInt *CI =
1293              dyn_cast<ConstantInt>(BI->getCondition())) {
1294     uint64_t Imm = CI->getZExtValue();
1295     MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
1296     fastEmitBranch(Target, DbgLoc);
1297     return true;
1298   }
1299 
1300   unsigned CmpReg = getRegForValue(BI->getCondition());
1301   if (CmpReg == 0) return false;
1302 
1303   // We've been divorced from our compare!  Our block was split, and
1304   // now our compare lives in a predecessor block.  We musn't
1305   // re-compare here, as the children of the compare aren't guaranteed
1306   // live across the block boundary (we *could* check for this).
1307   // Regardless, the compare has been done in the predecessor block,
1308   // and it left a value for us in a virtual register.  Ergo, we test
1309   // the one-bit value left in the virtual register.
1310   unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1311   CmpReg = constrainOperandRegClass(TII.get(TstOpc), CmpReg, 0);
1312   AddOptionalDefs(
1313       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TstOpc))
1314           .addReg(CmpReg)
1315           .addImm(1));
1316 
1317   unsigned CCMode = ARMCC::NE;
1318   if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1319     std::swap(TBB, FBB);
1320     CCMode = ARMCC::EQ;
1321   }
1322 
1323   unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1324   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BrOpc))
1325                   .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1326   finishCondBranch(BI->getParent(), TBB, FBB);
1327   return true;
1328 }
1329 
1330 bool ARMFastISel::SelectIndirectBr(const Instruction *I) {
1331   unsigned AddrReg = getRegForValue(I->getOperand(0));
1332   if (AddrReg == 0) return false;
1333 
1334   unsigned Opc = isThumb2 ? ARM::tBRIND : ARM::BX;
1335   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1336                           TII.get(Opc)).addReg(AddrReg));
1337 
1338   const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1339   for (const BasicBlock *SuccBB : IB->successors())
1340     FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[SuccBB]);
1341 
1342   return true;
1343 }
1344 
1345 bool ARMFastISel::ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
1346                              bool isZExt) {
1347   Type *Ty = Src1Value->getType();
1348   EVT SrcEVT = TLI.getValueType(DL, Ty, true);
1349   if (!SrcEVT.isSimple()) return false;
1350   MVT SrcVT = SrcEVT.getSimpleVT();
1351 
1352   bool isFloat = (Ty->isFloatTy() || Ty->isDoubleTy());
1353   if (isFloat && !Subtarget->hasVFP2())
1354     return false;
1355 
1356   // Check to see if the 2nd operand is a constant that we can encode directly
1357   // in the compare.
1358   int Imm = 0;
1359   bool UseImm = false;
1360   bool isNegativeImm = false;
1361   // FIXME: At -O0 we don't have anything that canonicalizes operand order.
1362   // Thus, Src1Value may be a ConstantInt, but we're missing it.
1363   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
1364     if (SrcVT == MVT::i32 || SrcVT == MVT::i16 || SrcVT == MVT::i8 ||
1365         SrcVT == MVT::i1) {
1366       const APInt &CIVal = ConstInt->getValue();
1367       Imm = (isZExt) ? (int)CIVal.getZExtValue() : (int)CIVal.getSExtValue();
1368       // For INT_MIN/LONG_MIN (i.e., 0x80000000) we need to use a cmp, rather
1369       // then a cmn, because there is no way to represent 2147483648 as a
1370       // signed 32-bit int.
1371       if (Imm < 0 && Imm != (int)0x80000000) {
1372         isNegativeImm = true;
1373         Imm = -Imm;
1374       }
1375       UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1376         (ARM_AM::getSOImmVal(Imm) != -1);
1377     }
1378   } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
1379     if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
1380       if (ConstFP->isZero() && !ConstFP->isNegative())
1381         UseImm = true;
1382   }
1383 
1384   unsigned CmpOpc;
1385   bool isICmp = true;
1386   bool needsExt = false;
1387   switch (SrcVT.SimpleTy) {
1388     default: return false;
1389     // TODO: Verify compares.
1390     case MVT::f32:
1391       isICmp = false;
1392       CmpOpc = UseImm ? ARM::VCMPEZS : ARM::VCMPES;
1393       break;
1394     case MVT::f64:
1395       isICmp = false;
1396       CmpOpc = UseImm ? ARM::VCMPEZD : ARM::VCMPED;
1397       break;
1398     case MVT::i1:
1399     case MVT::i8:
1400     case MVT::i16:
1401       needsExt = true;
1402     // Intentional fall-through.
1403     case MVT::i32:
1404       if (isThumb2) {
1405         if (!UseImm)
1406           CmpOpc = ARM::t2CMPrr;
1407         else
1408           CmpOpc = isNegativeImm ? ARM::t2CMNri : ARM::t2CMPri;
1409       } else {
1410         if (!UseImm)
1411           CmpOpc = ARM::CMPrr;
1412         else
1413           CmpOpc = isNegativeImm ? ARM::CMNri : ARM::CMPri;
1414       }
1415       break;
1416   }
1417 
1418   unsigned SrcReg1 = getRegForValue(Src1Value);
1419   if (SrcReg1 == 0) return false;
1420 
1421   unsigned SrcReg2 = 0;
1422   if (!UseImm) {
1423     SrcReg2 = getRegForValue(Src2Value);
1424     if (SrcReg2 == 0) return false;
1425   }
1426 
1427   // We have i1, i8, or i16, we need to either zero extend or sign extend.
1428   if (needsExt) {
1429     SrcReg1 = ARMEmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
1430     if (SrcReg1 == 0) return false;
1431     if (!UseImm) {
1432       SrcReg2 = ARMEmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
1433       if (SrcReg2 == 0) return false;
1434     }
1435   }
1436 
1437   const MCInstrDesc &II = TII.get(CmpOpc);
1438   SrcReg1 = constrainOperandRegClass(II, SrcReg1, 0);
1439   if (!UseImm) {
1440     SrcReg2 = constrainOperandRegClass(II, SrcReg2, 1);
1441     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1442                     .addReg(SrcReg1).addReg(SrcReg2));
1443   } else {
1444     MachineInstrBuilder MIB;
1445     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1446       .addReg(SrcReg1);
1447 
1448     // Only add immediate for icmp as the immediate for fcmp is an implicit 0.0.
1449     if (isICmp)
1450       MIB.addImm(Imm);
1451     AddOptionalDefs(MIB);
1452   }
1453 
1454   // For floating point we need to move the result to a comparison register
1455   // that we can then use for branches.
1456   if (Ty->isFloatTy() || Ty->isDoubleTy())
1457     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1458                             TII.get(ARM::FMSTAT)));
1459   return true;
1460 }
1461 
1462 bool ARMFastISel::SelectCmp(const Instruction *I) {
1463   const CmpInst *CI = cast<CmpInst>(I);
1464 
1465   // Get the compare predicate.
1466   ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
1467 
1468   // We may not handle every CC for now.
1469   if (ARMPred == ARMCC::AL) return false;
1470 
1471   // Emit the compare.
1472   if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1473     return false;
1474 
1475   // Now set a register based on the comparison. Explicitly set the predicates
1476   // here.
1477   unsigned MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1478   const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass
1479                                            : &ARM::GPRRegClass;
1480   unsigned DestReg = createResultReg(RC);
1481   Constant *Zero = ConstantInt::get(Type::getInt32Ty(*Context), 0);
1482   unsigned ZeroReg = fastMaterializeConstant(Zero);
1483   // ARMEmitCmp emits a FMSTAT when necessary, so it's always safe to use CPSR.
1484   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovCCOpc), DestReg)
1485           .addReg(ZeroReg).addImm(1)
1486           .addImm(ARMPred).addReg(ARM::CPSR);
1487 
1488   updateValueMap(I, DestReg);
1489   return true;
1490 }
1491 
1492 bool ARMFastISel::SelectFPExt(const Instruction *I) {
1493   // Make sure we have VFP and that we're extending float to double.
1494   if (!Subtarget->hasVFP2()) return false;
1495 
1496   Value *V = I->getOperand(0);
1497   if (!I->getType()->isDoubleTy() ||
1498       !V->getType()->isFloatTy()) return false;
1499 
1500   unsigned Op = getRegForValue(V);
1501   if (Op == 0) return false;
1502 
1503   unsigned Result = createResultReg(&ARM::DPRRegClass);
1504   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1505                           TII.get(ARM::VCVTDS), Result)
1506                   .addReg(Op));
1507   updateValueMap(I, Result);
1508   return true;
1509 }
1510 
1511 bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
1512   // Make sure we have VFP and that we're truncating double to float.
1513   if (!Subtarget->hasVFP2()) return false;
1514 
1515   Value *V = I->getOperand(0);
1516   if (!(I->getType()->isFloatTy() &&
1517         V->getType()->isDoubleTy())) return false;
1518 
1519   unsigned Op = getRegForValue(V);
1520   if (Op == 0) return false;
1521 
1522   unsigned Result = createResultReg(&ARM::SPRRegClass);
1523   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1524                           TII.get(ARM::VCVTSD), Result)
1525                   .addReg(Op));
1526   updateValueMap(I, Result);
1527   return true;
1528 }
1529 
1530 bool ARMFastISel::SelectIToFP(const Instruction *I, bool isSigned) {
1531   // Make sure we have VFP.
1532   if (!Subtarget->hasVFP2()) return false;
1533 
1534   MVT DstVT;
1535   Type *Ty = I->getType();
1536   if (!isTypeLegal(Ty, DstVT))
1537     return false;
1538 
1539   Value *Src = I->getOperand(0);
1540   EVT SrcEVT = TLI.getValueType(DL, Src->getType(), true);
1541   if (!SrcEVT.isSimple())
1542     return false;
1543   MVT SrcVT = SrcEVT.getSimpleVT();
1544   if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
1545     return false;
1546 
1547   unsigned SrcReg = getRegForValue(Src);
1548   if (SrcReg == 0) return false;
1549 
1550   // Handle sign-extension.
1551   if (SrcVT == MVT::i16 || SrcVT == MVT::i8) {
1552     SrcReg = ARMEmitIntExt(SrcVT, SrcReg, MVT::i32,
1553                                        /*isZExt*/!isSigned);
1554     if (SrcReg == 0) return false;
1555   }
1556 
1557   // The conversion routine works on fp-reg to fp-reg and the operand above
1558   // was an integer, move it to the fp registers if possible.
1559   unsigned FP = ARMMoveToFPReg(MVT::f32, SrcReg);
1560   if (FP == 0) return false;
1561 
1562   unsigned Opc;
1563   if (Ty->isFloatTy()) Opc = isSigned ? ARM::VSITOS : ARM::VUITOS;
1564   else if (Ty->isDoubleTy()) Opc = isSigned ? ARM::VSITOD : ARM::VUITOD;
1565   else return false;
1566 
1567   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1568   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1569                           TII.get(Opc), ResultReg).addReg(FP));
1570   updateValueMap(I, ResultReg);
1571   return true;
1572 }
1573 
1574 bool ARMFastISel::SelectFPToI(const Instruction *I, bool isSigned) {
1575   // Make sure we have VFP.
1576   if (!Subtarget->hasVFP2()) return false;
1577 
1578   MVT DstVT;
1579   Type *RetTy = I->getType();
1580   if (!isTypeLegal(RetTy, DstVT))
1581     return false;
1582 
1583   unsigned Op = getRegForValue(I->getOperand(0));
1584   if (Op == 0) return false;
1585 
1586   unsigned Opc;
1587   Type *OpTy = I->getOperand(0)->getType();
1588   if (OpTy->isFloatTy()) Opc = isSigned ? ARM::VTOSIZS : ARM::VTOUIZS;
1589   else if (OpTy->isDoubleTy()) Opc = isSigned ? ARM::VTOSIZD : ARM::VTOUIZD;
1590   else return false;
1591 
1592   // f64->s32/u32 or f32->s32/u32 both need an intermediate f32 reg.
1593   unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1594   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1595                           TII.get(Opc), ResultReg).addReg(Op));
1596 
1597   // This result needs to be in an integer register, but the conversion only
1598   // takes place in fp-regs.
1599   unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1600   if (IntReg == 0) return false;
1601 
1602   updateValueMap(I, IntReg);
1603   return true;
1604 }
1605 
1606 bool ARMFastISel::SelectSelect(const Instruction *I) {
1607   MVT VT;
1608   if (!isTypeLegal(I->getType(), VT))
1609     return false;
1610 
1611   // Things need to be register sized for register moves.
1612   if (VT != MVT::i32) return false;
1613 
1614   unsigned CondReg = getRegForValue(I->getOperand(0));
1615   if (CondReg == 0) return false;
1616   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1617   if (Op1Reg == 0) return false;
1618 
1619   // Check to see if we can use an immediate in the conditional move.
1620   int Imm = 0;
1621   bool UseImm = false;
1622   bool isNegativeImm = false;
1623   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(2))) {
1624     assert(VT == MVT::i32 && "Expecting an i32.");
1625     Imm = (int)ConstInt->getValue().getZExtValue();
1626     if (Imm < 0) {
1627       isNegativeImm = true;
1628       Imm = ~Imm;
1629     }
1630     UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1631       (ARM_AM::getSOImmVal(Imm) != -1);
1632   }
1633 
1634   unsigned Op2Reg = 0;
1635   if (!UseImm) {
1636     Op2Reg = getRegForValue(I->getOperand(2));
1637     if (Op2Reg == 0) return false;
1638   }
1639 
1640   unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1641   CondReg = constrainOperandRegClass(TII.get(TstOpc), CondReg, 0);
1642   AddOptionalDefs(
1643       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TstOpc))
1644           .addReg(CondReg)
1645           .addImm(1));
1646 
1647   unsigned MovCCOpc;
1648   const TargetRegisterClass *RC;
1649   if (!UseImm) {
1650     RC = isThumb2 ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
1651     MovCCOpc = isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr;
1652   } else {
1653     RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass;
1654     if (!isNegativeImm)
1655       MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1656     else
1657       MovCCOpc = isThumb2 ? ARM::t2MVNCCi : ARM::MVNCCi;
1658   }
1659   unsigned ResultReg = createResultReg(RC);
1660   if (!UseImm) {
1661     Op2Reg = constrainOperandRegClass(TII.get(MovCCOpc), Op2Reg, 1);
1662     Op1Reg = constrainOperandRegClass(TII.get(MovCCOpc), Op1Reg, 2);
1663     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovCCOpc),
1664             ResultReg)
1665         .addReg(Op2Reg)
1666         .addReg(Op1Reg)
1667         .addImm(ARMCC::NE)
1668         .addReg(ARM::CPSR);
1669   } else {
1670     Op1Reg = constrainOperandRegClass(TII.get(MovCCOpc), Op1Reg, 1);
1671     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovCCOpc),
1672             ResultReg)
1673         .addReg(Op1Reg)
1674         .addImm(Imm)
1675         .addImm(ARMCC::EQ)
1676         .addReg(ARM::CPSR);
1677   }
1678   updateValueMap(I, ResultReg);
1679   return true;
1680 }
1681 
1682 bool ARMFastISel::SelectDiv(const Instruction *I, bool isSigned) {
1683   MVT VT;
1684   Type *Ty = I->getType();
1685   if (!isTypeLegal(Ty, VT))
1686     return false;
1687 
1688   // If we have integer div support we should have selected this automagically.
1689   // In case we have a real miss go ahead and return false and we'll pick
1690   // it up later.
1691   if (Subtarget->hasDivide()) return false;
1692 
1693   // Otherwise emit a libcall.
1694   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1695   if (VT == MVT::i8)
1696     LC = isSigned ? RTLIB::SDIV_I8 : RTLIB::UDIV_I8;
1697   else if (VT == MVT::i16)
1698     LC = isSigned ? RTLIB::SDIV_I16 : RTLIB::UDIV_I16;
1699   else if (VT == MVT::i32)
1700     LC = isSigned ? RTLIB::SDIV_I32 : RTLIB::UDIV_I32;
1701   else if (VT == MVT::i64)
1702     LC = isSigned ? RTLIB::SDIV_I64 : RTLIB::UDIV_I64;
1703   else if (VT == MVT::i128)
1704     LC = isSigned ? RTLIB::SDIV_I128 : RTLIB::UDIV_I128;
1705   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1706 
1707   return ARMEmitLibcall(I, LC);
1708 }
1709 
1710 bool ARMFastISel::SelectRem(const Instruction *I, bool isSigned) {
1711   MVT VT;
1712   Type *Ty = I->getType();
1713   if (!isTypeLegal(Ty, VT))
1714     return false;
1715 
1716   // Many ABIs do not provide a libcall for standalone remainder, so we need to
1717   // use divrem (see the RTABI 4.3.1). Since FastISel can't handle non-double
1718   // multi-reg returns, we'll have to bail out.
1719   if (!TLI.hasStandaloneRem(VT)) {
1720     return false;
1721   }
1722 
1723   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1724   if (VT == MVT::i8)
1725     LC = isSigned ? RTLIB::SREM_I8 : RTLIB::UREM_I8;
1726   else if (VT == MVT::i16)
1727     LC = isSigned ? RTLIB::SREM_I16 : RTLIB::UREM_I16;
1728   else if (VT == MVT::i32)
1729     LC = isSigned ? RTLIB::SREM_I32 : RTLIB::UREM_I32;
1730   else if (VT == MVT::i64)
1731     LC = isSigned ? RTLIB::SREM_I64 : RTLIB::UREM_I64;
1732   else if (VT == MVT::i128)
1733     LC = isSigned ? RTLIB::SREM_I128 : RTLIB::UREM_I128;
1734   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1735 
1736   return ARMEmitLibcall(I, LC);
1737 }
1738 
1739 bool ARMFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1740   EVT DestVT = TLI.getValueType(DL, I->getType(), true);
1741 
1742   // We can get here in the case when we have a binary operation on a non-legal
1743   // type and the target independent selector doesn't know how to handle it.
1744   if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
1745     return false;
1746 
1747   unsigned Opc;
1748   switch (ISDOpcode) {
1749     default: return false;
1750     case ISD::ADD:
1751       Opc = isThumb2 ? ARM::t2ADDrr : ARM::ADDrr;
1752       break;
1753     case ISD::OR:
1754       Opc = isThumb2 ? ARM::t2ORRrr : ARM::ORRrr;
1755       break;
1756     case ISD::SUB:
1757       Opc = isThumb2 ? ARM::t2SUBrr : ARM::SUBrr;
1758       break;
1759   }
1760 
1761   unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1762   if (SrcReg1 == 0) return false;
1763 
1764   // TODO: Often the 2nd operand is an immediate, which can be encoded directly
1765   // in the instruction, rather then materializing the value in a register.
1766   unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1767   if (SrcReg2 == 0) return false;
1768 
1769   unsigned ResultReg = createResultReg(&ARM::GPRnopcRegClass);
1770   SrcReg1 = constrainOperandRegClass(TII.get(Opc), SrcReg1, 1);
1771   SrcReg2 = constrainOperandRegClass(TII.get(Opc), SrcReg2, 2);
1772   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1773                           TII.get(Opc), ResultReg)
1774                   .addReg(SrcReg1).addReg(SrcReg2));
1775   updateValueMap(I, ResultReg);
1776   return true;
1777 }
1778 
1779 bool ARMFastISel::SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode) {
1780   EVT FPVT = TLI.getValueType(DL, I->getType(), true);
1781   if (!FPVT.isSimple()) return false;
1782   MVT VT = FPVT.getSimpleVT();
1783 
1784   // FIXME: Support vector types where possible.
1785   if (VT.isVector())
1786     return false;
1787 
1788   // We can get here in the case when we want to use NEON for our fp
1789   // operations, but can't figure out how to. Just use the vfp instructions
1790   // if we have them.
1791   // FIXME: It'd be nice to use NEON instructions.
1792   Type *Ty = I->getType();
1793   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1794   if (isFloat && !Subtarget->hasVFP2())
1795     return false;
1796 
1797   unsigned Opc;
1798   bool is64bit = VT == MVT::f64 || VT == MVT::i64;
1799   switch (ISDOpcode) {
1800     default: return false;
1801     case ISD::FADD:
1802       Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1803       break;
1804     case ISD::FSUB:
1805       Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1806       break;
1807     case ISD::FMUL:
1808       Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1809       break;
1810   }
1811   unsigned Op1 = getRegForValue(I->getOperand(0));
1812   if (Op1 == 0) return false;
1813 
1814   unsigned Op2 = getRegForValue(I->getOperand(1));
1815   if (Op2 == 0) return false;
1816 
1817   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT.SimpleTy));
1818   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1819                           TII.get(Opc), ResultReg)
1820                   .addReg(Op1).addReg(Op2));
1821   updateValueMap(I, ResultReg);
1822   return true;
1823 }
1824 
1825 // Call Handling Code
1826 
1827 // This is largely taken directly from CCAssignFnForNode
1828 // TODO: We may not support all of this.
1829 CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC,
1830                                            bool Return,
1831                                            bool isVarArg) {
1832   switch (CC) {
1833   default:
1834     llvm_unreachable("Unsupported calling convention");
1835   case CallingConv::Fast:
1836     if (Subtarget->hasVFP2() && !isVarArg) {
1837       if (!Subtarget->isAAPCS_ABI())
1838         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1839       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1840       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1841     }
1842     LLVM_FALLTHROUGH;
1843   case CallingConv::C:
1844   case CallingConv::CXX_FAST_TLS:
1845     // Use target triple & subtarget features to do actual dispatch.
1846     if (Subtarget->isAAPCS_ABI()) {
1847       if (Subtarget->hasVFP2() &&
1848           TM.Options.FloatABIType == FloatABI::Hard && !isVarArg)
1849         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1850       else
1851         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1852     } else {
1853       return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1854     }
1855   case CallingConv::ARM_AAPCS_VFP:
1856   case CallingConv::Swift:
1857     if (!isVarArg)
1858       return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1859     // Fall through to soft float variant, variadic functions don't
1860     // use hard floating point ABI.
1861     LLVM_FALLTHROUGH;
1862   case CallingConv::ARM_AAPCS:
1863     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1864   case CallingConv::ARM_APCS:
1865     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1866   case CallingConv::GHC:
1867     if (Return)
1868       llvm_unreachable("Can't return in GHC call convention");
1869     else
1870       return CC_ARM_APCS_GHC;
1871   }
1872 }
1873 
1874 bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1875                                   SmallVectorImpl<unsigned> &ArgRegs,
1876                                   SmallVectorImpl<MVT> &ArgVTs,
1877                                   SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1878                                   SmallVectorImpl<unsigned> &RegArgs,
1879                                   CallingConv::ID CC,
1880                                   unsigned &NumBytes,
1881                                   bool isVarArg) {
1882   SmallVector<CCValAssign, 16> ArgLocs;
1883   CCState CCInfo(CC, isVarArg, *FuncInfo.MF, ArgLocs, *Context);
1884   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags,
1885                              CCAssignFnForCall(CC, false, isVarArg));
1886 
1887   // Check that we can handle all of the arguments. If we can't, then bail out
1888   // now before we add code to the MBB.
1889   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1890     CCValAssign &VA = ArgLocs[i];
1891     MVT ArgVT = ArgVTs[VA.getValNo()];
1892 
1893     // We don't handle NEON/vector parameters yet.
1894     if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64)
1895       return false;
1896 
1897     // Now copy/store arg to correct locations.
1898     if (VA.isRegLoc() && !VA.needsCustom()) {
1899       continue;
1900     } else if (VA.needsCustom()) {
1901       // TODO: We need custom lowering for vector (v2f64) args.
1902       if (VA.getLocVT() != MVT::f64 ||
1903           // TODO: Only handle register args for now.
1904           !VA.isRegLoc() || !ArgLocs[++i].isRegLoc())
1905         return false;
1906     } else {
1907       switch (ArgVT.SimpleTy) {
1908       default:
1909         return false;
1910       case MVT::i1:
1911       case MVT::i8:
1912       case MVT::i16:
1913       case MVT::i32:
1914         break;
1915       case MVT::f32:
1916         if (!Subtarget->hasVFP2())
1917           return false;
1918         break;
1919       case MVT::f64:
1920         if (!Subtarget->hasVFP2())
1921           return false;
1922         break;
1923       }
1924     }
1925   }
1926 
1927   // At the point, we are able to handle the call's arguments in fast isel.
1928 
1929   // Get a count of how many bytes are to be pushed on the stack.
1930   NumBytes = CCInfo.getNextStackOffset();
1931 
1932   // Issue CALLSEQ_START
1933   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1934   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1935                           TII.get(AdjStackDown))
1936                   .addImm(NumBytes));
1937 
1938   // Process the args.
1939   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1940     CCValAssign &VA = ArgLocs[i];
1941     const Value *ArgVal = Args[VA.getValNo()];
1942     unsigned Arg = ArgRegs[VA.getValNo()];
1943     MVT ArgVT = ArgVTs[VA.getValNo()];
1944 
1945     assert((!ArgVT.isVector() && ArgVT.getSizeInBits() <= 64) &&
1946            "We don't handle NEON/vector parameters yet.");
1947 
1948     // Handle arg promotion, etc.
1949     switch (VA.getLocInfo()) {
1950       case CCValAssign::Full: break;
1951       case CCValAssign::SExt: {
1952         MVT DestVT = VA.getLocVT();
1953         Arg = ARMEmitIntExt(ArgVT, Arg, DestVT, /*isZExt*/false);
1954         assert(Arg != 0 && "Failed to emit a sext");
1955         ArgVT = DestVT;
1956         break;
1957       }
1958       case CCValAssign::AExt:
1959         // Intentional fall-through.  Handle AExt and ZExt.
1960       case CCValAssign::ZExt: {
1961         MVT DestVT = VA.getLocVT();
1962         Arg = ARMEmitIntExt(ArgVT, Arg, DestVT, /*isZExt*/true);
1963         assert(Arg != 0 && "Failed to emit a zext");
1964         ArgVT = DestVT;
1965         break;
1966       }
1967       case CCValAssign::BCvt: {
1968         unsigned BC = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, Arg,
1969                                  /*TODO: Kill=*/false);
1970         assert(BC != 0 && "Failed to emit a bitcast!");
1971         Arg = BC;
1972         ArgVT = VA.getLocVT();
1973         break;
1974       }
1975       default: llvm_unreachable("Unknown arg promotion!");
1976     }
1977 
1978     // Now copy/store arg to correct locations.
1979     if (VA.isRegLoc() && !VA.needsCustom()) {
1980       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1981               TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
1982       RegArgs.push_back(VA.getLocReg());
1983     } else if (VA.needsCustom()) {
1984       // TODO: We need custom lowering for vector (v2f64) args.
1985       assert(VA.getLocVT() == MVT::f64 &&
1986              "Custom lowering for v2f64 args not available");
1987 
1988       CCValAssign &NextVA = ArgLocs[++i];
1989 
1990       assert(VA.isRegLoc() && NextVA.isRegLoc() &&
1991              "We only handle register args!");
1992 
1993       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1994                               TII.get(ARM::VMOVRRD), VA.getLocReg())
1995                       .addReg(NextVA.getLocReg(), RegState::Define)
1996                       .addReg(Arg));
1997       RegArgs.push_back(VA.getLocReg());
1998       RegArgs.push_back(NextVA.getLocReg());
1999     } else {
2000       assert(VA.isMemLoc());
2001       // Need to store on the stack.
2002 
2003       // Don't emit stores for undef values.
2004       if (isa<UndefValue>(ArgVal))
2005         continue;
2006 
2007       Address Addr;
2008       Addr.BaseType = Address::RegBase;
2009       Addr.Base.Reg = ARM::SP;
2010       Addr.Offset = VA.getLocMemOffset();
2011 
2012       bool EmitRet = ARMEmitStore(ArgVT, Arg, Addr); (void)EmitRet;
2013       assert(EmitRet && "Could not emit a store for argument!");
2014     }
2015   }
2016 
2017   return true;
2018 }
2019 
2020 bool ARMFastISel::FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
2021                              const Instruction *I, CallingConv::ID CC,
2022                              unsigned &NumBytes, bool isVarArg) {
2023   // Issue CALLSEQ_END
2024   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2025   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2026                           TII.get(AdjStackUp))
2027                   .addImm(NumBytes).addImm(0));
2028 
2029   // Now the return value.
2030   if (RetVT != MVT::isVoid) {
2031     SmallVector<CCValAssign, 16> RVLocs;
2032     CCState CCInfo(CC, isVarArg, *FuncInfo.MF, RVLocs, *Context);
2033     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, isVarArg));
2034 
2035     // Copy all of the result registers out of their specified physreg.
2036     if (RVLocs.size() == 2 && RetVT == MVT::f64) {
2037       // For this move we copy into two registers and then move into the
2038       // double fp reg we want.
2039       MVT DestVT = RVLocs[0].getValVT();
2040       const TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
2041       unsigned ResultReg = createResultReg(DstRC);
2042       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2043                               TII.get(ARM::VMOVDRR), ResultReg)
2044                       .addReg(RVLocs[0].getLocReg())
2045                       .addReg(RVLocs[1].getLocReg()));
2046 
2047       UsedRegs.push_back(RVLocs[0].getLocReg());
2048       UsedRegs.push_back(RVLocs[1].getLocReg());
2049 
2050       // Finally update the result.
2051       updateValueMap(I, ResultReg);
2052     } else {
2053       assert(RVLocs.size() == 1 &&"Can't handle non-double multi-reg retvals!");
2054       MVT CopyVT = RVLocs[0].getValVT();
2055 
2056       // Special handling for extended integers.
2057       if (RetVT == MVT::i1 || RetVT == MVT::i8 || RetVT == MVT::i16)
2058         CopyVT = MVT::i32;
2059 
2060       const TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
2061 
2062       unsigned ResultReg = createResultReg(DstRC);
2063       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2064               TII.get(TargetOpcode::COPY),
2065               ResultReg).addReg(RVLocs[0].getLocReg());
2066       UsedRegs.push_back(RVLocs[0].getLocReg());
2067 
2068       // Finally update the result.
2069       updateValueMap(I, ResultReg);
2070     }
2071   }
2072 
2073   return true;
2074 }
2075 
2076 bool ARMFastISel::SelectRet(const Instruction *I) {
2077   const ReturnInst *Ret = cast<ReturnInst>(I);
2078   const Function &F = *I->getParent()->getParent();
2079 
2080   if (!FuncInfo.CanLowerReturn)
2081     return false;
2082 
2083   if (TLI.supportSwiftError() &&
2084       F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
2085     return false;
2086 
2087   if (TLI.supportSplitCSR(FuncInfo.MF))
2088     return false;
2089 
2090   // Build a list of return value registers.
2091   SmallVector<unsigned, 4> RetRegs;
2092 
2093   CallingConv::ID CC = F.getCallingConv();
2094   if (Ret->getNumOperands() > 0) {
2095     SmallVector<ISD::OutputArg, 4> Outs;
2096     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
2097 
2098     // Analyze operands of the call, assigning locations to each operand.
2099     SmallVector<CCValAssign, 16> ValLocs;
2100     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
2101     CCInfo.AnalyzeReturn(Outs, CCAssignFnForCall(CC, true /* is Ret */,
2102                                                  F.isVarArg()));
2103 
2104     const Value *RV = Ret->getOperand(0);
2105     unsigned Reg = getRegForValue(RV);
2106     if (Reg == 0)
2107       return false;
2108 
2109     // Only handle a single return value for now.
2110     if (ValLocs.size() != 1)
2111       return false;
2112 
2113     CCValAssign &VA = ValLocs[0];
2114 
2115     // Don't bother handling odd stuff for now.
2116     if (VA.getLocInfo() != CCValAssign::Full)
2117       return false;
2118     // Only handle register returns for now.
2119     if (!VA.isRegLoc())
2120       return false;
2121 
2122     unsigned SrcReg = Reg + VA.getValNo();
2123     EVT RVEVT = TLI.getValueType(DL, RV->getType());
2124     if (!RVEVT.isSimple()) return false;
2125     MVT RVVT = RVEVT.getSimpleVT();
2126     MVT DestVT = VA.getValVT();
2127     // Special handling for extended integers.
2128     if (RVVT != DestVT) {
2129       if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
2130         return false;
2131 
2132       assert(DestVT == MVT::i32 && "ARM should always ext to i32");
2133 
2134       // Perform extension if flagged as either zext or sext.  Otherwise, do
2135       // nothing.
2136       if (Outs[0].Flags.isZExt() || Outs[0].Flags.isSExt()) {
2137         SrcReg = ARMEmitIntExt(RVVT, SrcReg, DestVT, Outs[0].Flags.isZExt());
2138         if (SrcReg == 0) return false;
2139       }
2140     }
2141 
2142     // Make the copy.
2143     unsigned DstReg = VA.getLocReg();
2144     const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
2145     // Avoid a cross-class copy. This is very unlikely.
2146     if (!SrcRC->contains(DstReg))
2147       return false;
2148     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2149             TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
2150 
2151     // Add register to return instruction.
2152     RetRegs.push_back(VA.getLocReg());
2153   }
2154 
2155   unsigned RetOpc = isThumb2 ? ARM::tBX_RET : ARM::BX_RET;
2156   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2157                                     TII.get(RetOpc));
2158   AddOptionalDefs(MIB);
2159   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
2160     MIB.addReg(RetRegs[i], RegState::Implicit);
2161   return true;
2162 }
2163 
2164 unsigned ARMFastISel::ARMSelectCallOp(bool UseReg) {
2165   if (UseReg)
2166     return isThumb2 ? ARM::tBLXr : ARM::BLX;
2167   else
2168     return isThumb2 ? ARM::tBL : ARM::BL;
2169 }
2170 
2171 unsigned ARMFastISel::getLibcallReg(const Twine &Name) {
2172   // Manually compute the global's type to avoid building it when unnecessary.
2173   Type *GVTy = Type::getInt32PtrTy(*Context, /*AS=*/0);
2174   EVT LCREVT = TLI.getValueType(DL, GVTy);
2175   if (!LCREVT.isSimple()) return 0;
2176 
2177   GlobalValue *GV = new GlobalVariable(M, Type::getInt32Ty(*Context), false,
2178                                        GlobalValue::ExternalLinkage, nullptr,
2179                                        Name);
2180   assert(GV->getType() == GVTy && "We miscomputed the type for the global!");
2181   return ARMMaterializeGV(GV, LCREVT.getSimpleVT());
2182 }
2183 
2184 // A quick function that will emit a call for a named libcall in F with the
2185 // vector of passed arguments for the Instruction in I. We can assume that we
2186 // can emit a call for any libcall we can produce. This is an abridged version
2187 // of the full call infrastructure since we won't need to worry about things
2188 // like computed function pointers or strange arguments at call sites.
2189 // TODO: Try to unify this and the normal call bits for ARM, then try to unify
2190 // with X86.
2191 bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
2192   CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
2193 
2194   // Handle *simple* calls for now.
2195   Type *RetTy = I->getType();
2196   MVT RetVT;
2197   if (RetTy->isVoidTy())
2198     RetVT = MVT::isVoid;
2199   else if (!isTypeLegal(RetTy, RetVT))
2200     return false;
2201 
2202   // Can't handle non-double multi-reg retvals.
2203   if (RetVT != MVT::isVoid && RetVT != MVT::i32) {
2204     SmallVector<CCValAssign, 16> RVLocs;
2205     CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
2206     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, false));
2207     if (RVLocs.size() >= 2 && RetVT != MVT::f64)
2208       return false;
2209   }
2210 
2211   // Set up the argument vectors.
2212   SmallVector<Value*, 8> Args;
2213   SmallVector<unsigned, 8> ArgRegs;
2214   SmallVector<MVT, 8> ArgVTs;
2215   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2216   Args.reserve(I->getNumOperands());
2217   ArgRegs.reserve(I->getNumOperands());
2218   ArgVTs.reserve(I->getNumOperands());
2219   ArgFlags.reserve(I->getNumOperands());
2220   for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2221     Value *Op = I->getOperand(i);
2222     unsigned Arg = getRegForValue(Op);
2223     if (Arg == 0) return false;
2224 
2225     Type *ArgTy = Op->getType();
2226     MVT ArgVT;
2227     if (!isTypeLegal(ArgTy, ArgVT)) return false;
2228 
2229     ISD::ArgFlagsTy Flags;
2230     unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2231     Flags.setOrigAlign(OriginalAlignment);
2232 
2233     Args.push_back(Op);
2234     ArgRegs.push_back(Arg);
2235     ArgVTs.push_back(ArgVT);
2236     ArgFlags.push_back(Flags);
2237   }
2238 
2239   // Handle the arguments now that we've gotten them.
2240   SmallVector<unsigned, 4> RegArgs;
2241   unsigned NumBytes;
2242   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
2243                        RegArgs, CC, NumBytes, false))
2244     return false;
2245 
2246   unsigned CalleeReg = 0;
2247   if (Subtarget->genLongCalls()) {
2248     CalleeReg = getLibcallReg(TLI.getLibcallName(Call));
2249     if (CalleeReg == 0) return false;
2250   }
2251 
2252   // Issue the call.
2253   unsigned CallOpc = ARMSelectCallOp(Subtarget->genLongCalls());
2254   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2255                                     DbgLoc, TII.get(CallOpc));
2256   // BL / BLX don't take a predicate, but tBL / tBLX do.
2257   if (isThumb2)
2258     MIB.add(predOps(ARMCC::AL));
2259   if (Subtarget->genLongCalls())
2260     MIB.addReg(CalleeReg);
2261   else
2262     MIB.addExternalSymbol(TLI.getLibcallName(Call));
2263 
2264   // Add implicit physical register uses to the call.
2265   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2266     MIB.addReg(RegArgs[i], RegState::Implicit);
2267 
2268   // Add a register mask with the call-preserved registers.
2269   // Proper defs for return values will be added by setPhysRegsDeadExcept().
2270   MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
2271 
2272   // Finish off the call including any return values.
2273   SmallVector<unsigned, 4> UsedRegs;
2274   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes, false)) return false;
2275 
2276   // Set all unused physreg defs as dead.
2277   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2278 
2279   return true;
2280 }
2281 
2282 bool ARMFastISel::SelectCall(const Instruction *I,
2283                              const char *IntrMemName = nullptr) {
2284   const CallInst *CI = cast<CallInst>(I);
2285   const Value *Callee = CI->getCalledValue();
2286 
2287   // Can't handle inline asm.
2288   if (isa<InlineAsm>(Callee)) return false;
2289 
2290   // Allow SelectionDAG isel to handle tail calls.
2291   if (CI->isTailCall()) return false;
2292 
2293   // Check the calling convention.
2294   ImmutableCallSite CS(CI);
2295   CallingConv::ID CC = CS.getCallingConv();
2296 
2297   // TODO: Avoid some calling conventions?
2298 
2299   FunctionType *FTy = CS.getFunctionType();
2300   bool isVarArg = FTy->isVarArg();
2301 
2302   // Handle *simple* calls for now.
2303   Type *RetTy = I->getType();
2304   MVT RetVT;
2305   if (RetTy->isVoidTy())
2306     RetVT = MVT::isVoid;
2307   else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
2308            RetVT != MVT::i8  && RetVT != MVT::i1)
2309     return false;
2310 
2311   // Can't handle non-double multi-reg retvals.
2312   if (RetVT != MVT::isVoid && RetVT != MVT::i1 && RetVT != MVT::i8 &&
2313       RetVT != MVT::i16 && RetVT != MVT::i32) {
2314     SmallVector<CCValAssign, 16> RVLocs;
2315     CCState CCInfo(CC, isVarArg, *FuncInfo.MF, RVLocs, *Context);
2316     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, isVarArg));
2317     if (RVLocs.size() >= 2 && RetVT != MVT::f64)
2318       return false;
2319   }
2320 
2321   // Set up the argument vectors.
2322   SmallVector<Value*, 8> Args;
2323   SmallVector<unsigned, 8> ArgRegs;
2324   SmallVector<MVT, 8> ArgVTs;
2325   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2326   unsigned arg_size = CS.arg_size();
2327   Args.reserve(arg_size);
2328   ArgRegs.reserve(arg_size);
2329   ArgVTs.reserve(arg_size);
2330   ArgFlags.reserve(arg_size);
2331   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2332        i != e; ++i) {
2333     // If we're lowering a memory intrinsic instead of a regular call, skip the
2334     // last two arguments, which shouldn't be passed to the underlying function.
2335     if (IntrMemName && e-i <= 2)
2336       break;
2337 
2338     ISD::ArgFlagsTy Flags;
2339     unsigned AttrInd = i - CS.arg_begin() + 1;
2340     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2341       Flags.setSExt();
2342     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2343       Flags.setZExt();
2344 
2345     // FIXME: Only handle *easy* calls for now.
2346     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
2347         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
2348         CS.paramHasAttr(AttrInd, Attribute::SwiftSelf) ||
2349         CS.paramHasAttr(AttrInd, Attribute::SwiftError) ||
2350         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
2351         CS.paramHasAttr(AttrInd, Attribute::ByVal))
2352       return false;
2353 
2354     Type *ArgTy = (*i)->getType();
2355     MVT ArgVT;
2356     if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8 &&
2357         ArgVT != MVT::i1)
2358       return false;
2359 
2360     unsigned Arg = getRegForValue(*i);
2361     if (Arg == 0)
2362       return false;
2363 
2364     unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2365     Flags.setOrigAlign(OriginalAlignment);
2366 
2367     Args.push_back(*i);
2368     ArgRegs.push_back(Arg);
2369     ArgVTs.push_back(ArgVT);
2370     ArgFlags.push_back(Flags);
2371   }
2372 
2373   // Handle the arguments now that we've gotten them.
2374   SmallVector<unsigned, 4> RegArgs;
2375   unsigned NumBytes;
2376   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
2377                        RegArgs, CC, NumBytes, isVarArg))
2378     return false;
2379 
2380   bool UseReg = false;
2381   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
2382   if (!GV || Subtarget->genLongCalls()) UseReg = true;
2383 
2384   unsigned CalleeReg = 0;
2385   if (UseReg) {
2386     if (IntrMemName)
2387       CalleeReg = getLibcallReg(IntrMemName);
2388     else
2389       CalleeReg = getRegForValue(Callee);
2390 
2391     if (CalleeReg == 0) return false;
2392   }
2393 
2394   // Issue the call.
2395   unsigned CallOpc = ARMSelectCallOp(UseReg);
2396   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2397                                     DbgLoc, TII.get(CallOpc));
2398 
2399   // ARM calls don't take a predicate, but tBL / tBLX do.
2400   if(isThumb2)
2401     MIB.add(predOps(ARMCC::AL));
2402   if (UseReg)
2403     MIB.addReg(CalleeReg);
2404   else if (!IntrMemName)
2405     MIB.addGlobalAddress(GV, 0, 0);
2406   else
2407     MIB.addExternalSymbol(IntrMemName, 0);
2408 
2409   // Add implicit physical register uses to the call.
2410   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2411     MIB.addReg(RegArgs[i], RegState::Implicit);
2412 
2413   // Add a register mask with the call-preserved registers.
2414   // Proper defs for return values will be added by setPhysRegsDeadExcept().
2415   MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
2416 
2417   // Finish off the call including any return values.
2418   SmallVector<unsigned, 4> UsedRegs;
2419   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes, isVarArg))
2420     return false;
2421 
2422   // Set all unused physreg defs as dead.
2423   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2424 
2425   return true;
2426 }
2427 
2428 bool ARMFastISel::ARMIsMemCpySmall(uint64_t Len) {
2429   return Len <= 16;
2430 }
2431 
2432 bool ARMFastISel::ARMTryEmitSmallMemCpy(Address Dest, Address Src,
2433                                         uint64_t Len, unsigned Alignment) {
2434   // Make sure we don't bloat code by inlining very large memcpy's.
2435   if (!ARMIsMemCpySmall(Len))
2436     return false;
2437 
2438   while (Len) {
2439     MVT VT;
2440     if (!Alignment || Alignment >= 4) {
2441       if (Len >= 4)
2442         VT = MVT::i32;
2443       else if (Len >= 2)
2444         VT = MVT::i16;
2445       else {
2446         assert(Len == 1 && "Expected a length of 1!");
2447         VT = MVT::i8;
2448       }
2449     } else {
2450       // Bound based on alignment.
2451       if (Len >= 2 && Alignment == 2)
2452         VT = MVT::i16;
2453       else {
2454         VT = MVT::i8;
2455       }
2456     }
2457 
2458     bool RV;
2459     unsigned ResultReg;
2460     RV = ARMEmitLoad(VT, ResultReg, Src);
2461     assert(RV && "Should be able to handle this load.");
2462     RV = ARMEmitStore(VT, ResultReg, Dest);
2463     assert(RV && "Should be able to handle this store.");
2464     (void)RV;
2465 
2466     unsigned Size = VT.getSizeInBits()/8;
2467     Len -= Size;
2468     Dest.Offset += Size;
2469     Src.Offset += Size;
2470   }
2471 
2472   return true;
2473 }
2474 
2475 bool ARMFastISel::SelectIntrinsicCall(const IntrinsicInst &I) {
2476   // FIXME: Handle more intrinsics.
2477   switch (I.getIntrinsicID()) {
2478   default: return false;
2479   case Intrinsic::frameaddress: {
2480     MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
2481     MFI.setFrameAddressIsTaken(true);
2482 
2483     unsigned LdrOpc = isThumb2 ? ARM::t2LDRi12 : ARM::LDRi12;
2484     const TargetRegisterClass *RC = isThumb2 ? &ARM::tGPRRegClass
2485                                              : &ARM::GPRRegClass;
2486 
2487     const ARMBaseRegisterInfo *RegInfo =
2488         static_cast<const ARMBaseRegisterInfo *>(Subtarget->getRegisterInfo());
2489     unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
2490     unsigned SrcReg = FramePtr;
2491 
2492     // Recursively load frame address
2493     // ldr r0 [fp]
2494     // ldr r0 [r0]
2495     // ldr r0 [r0]
2496     // ...
2497     unsigned DestReg;
2498     unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
2499     while (Depth--) {
2500       DestReg = createResultReg(RC);
2501       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2502                               TII.get(LdrOpc), DestReg)
2503                       .addReg(SrcReg).addImm(0));
2504       SrcReg = DestReg;
2505     }
2506     updateValueMap(&I, SrcReg);
2507     return true;
2508   }
2509   case Intrinsic::memcpy:
2510   case Intrinsic::memmove: {
2511     const MemTransferInst &MTI = cast<MemTransferInst>(I);
2512     // Don't handle volatile.
2513     if (MTI.isVolatile())
2514       return false;
2515 
2516     // Disable inlining for memmove before calls to ComputeAddress.  Otherwise,
2517     // we would emit dead code because we don't currently handle memmoves.
2518     bool isMemCpy = (I.getIntrinsicID() == Intrinsic::memcpy);
2519     if (isa<ConstantInt>(MTI.getLength()) && isMemCpy) {
2520       // Small memcpy's are common enough that we want to do them without a call
2521       // if possible.
2522       uint64_t Len = cast<ConstantInt>(MTI.getLength())->getZExtValue();
2523       if (ARMIsMemCpySmall(Len)) {
2524         Address Dest, Src;
2525         if (!ARMComputeAddress(MTI.getRawDest(), Dest) ||
2526             !ARMComputeAddress(MTI.getRawSource(), Src))
2527           return false;
2528         unsigned Alignment = MTI.getAlignment();
2529         if (ARMTryEmitSmallMemCpy(Dest, Src, Len, Alignment))
2530           return true;
2531       }
2532     }
2533 
2534     if (!MTI.getLength()->getType()->isIntegerTy(32))
2535       return false;
2536 
2537     if (MTI.getSourceAddressSpace() > 255 || MTI.getDestAddressSpace() > 255)
2538       return false;
2539 
2540     const char *IntrMemName = isa<MemCpyInst>(I) ? "memcpy" : "memmove";
2541     return SelectCall(&I, IntrMemName);
2542   }
2543   case Intrinsic::memset: {
2544     const MemSetInst &MSI = cast<MemSetInst>(I);
2545     // Don't handle volatile.
2546     if (MSI.isVolatile())
2547       return false;
2548 
2549     if (!MSI.getLength()->getType()->isIntegerTy(32))
2550       return false;
2551 
2552     if (MSI.getDestAddressSpace() > 255)
2553       return false;
2554 
2555     return SelectCall(&I, "memset");
2556   }
2557   case Intrinsic::trap: {
2558     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(
2559       Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP));
2560     return true;
2561   }
2562   }
2563 }
2564 
2565 bool ARMFastISel::SelectTrunc(const Instruction *I) {
2566   // The high bits for a type smaller than the register size are assumed to be
2567   // undefined.
2568   Value *Op = I->getOperand(0);
2569 
2570   EVT SrcVT, DestVT;
2571   SrcVT = TLI.getValueType(DL, Op->getType(), true);
2572   DestVT = TLI.getValueType(DL, I->getType(), true);
2573 
2574   if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
2575     return false;
2576   if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
2577     return false;
2578 
2579   unsigned SrcReg = getRegForValue(Op);
2580   if (!SrcReg) return false;
2581 
2582   // Because the high bits are undefined, a truncate doesn't generate
2583   // any code.
2584   updateValueMap(I, SrcReg);
2585   return true;
2586 }
2587 
2588 unsigned ARMFastISel::ARMEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
2589                                     bool isZExt) {
2590   if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
2591     return 0;
2592   if (SrcVT != MVT::i16 && SrcVT != MVT::i8 && SrcVT != MVT::i1)
2593     return 0;
2594 
2595   // Table of which combinations can be emitted as a single instruction,
2596   // and which will require two.
2597   static const uint8_t isSingleInstrTbl[3][2][2][2] = {
2598     //            ARM                     Thumb
2599     //           !hasV6Ops  hasV6Ops     !hasV6Ops  hasV6Ops
2600     //    ext:     s  z      s  z          s  z      s  z
2601     /*  1 */ { { { 0, 1 }, { 0, 1 } }, { { 0, 0 }, { 0, 1 } } },
2602     /*  8 */ { { { 0, 1 }, { 1, 1 } }, { { 0, 0 }, { 1, 1 } } },
2603     /* 16 */ { { { 0, 0 }, { 1, 1 } }, { { 0, 0 }, { 1, 1 } } }
2604   };
2605 
2606   // Target registers for:
2607   //  - For ARM can never be PC.
2608   //  - For 16-bit Thumb are restricted to lower 8 registers.
2609   //  - For 32-bit Thumb are restricted to non-SP and non-PC.
2610   static const TargetRegisterClass *RCTbl[2][2] = {
2611     // Instructions: Two                     Single
2612     /* ARM      */ { &ARM::GPRnopcRegClass, &ARM::GPRnopcRegClass },
2613     /* Thumb    */ { &ARM::tGPRRegClass,    &ARM::rGPRRegClass    }
2614   };
2615 
2616   // Table governing the instruction(s) to be emitted.
2617   static const struct InstructionTable {
2618     uint32_t Opc   : 16;
2619     uint32_t hasS  :  1; // Some instructions have an S bit, always set it to 0.
2620     uint32_t Shift :  7; // For shift operand addressing mode, used by MOVsi.
2621     uint32_t Imm   :  8; // All instructions have either a shift or a mask.
2622   } IT[2][2][3][2] = {
2623     { // Two instructions (first is left shift, second is in this table).
2624       { // ARM                Opc           S  Shift             Imm
2625         /*  1 bit sext */ { { ARM::MOVsi  , 1, ARM_AM::asr     ,  31 },
2626         /*  1 bit zext */   { ARM::MOVsi  , 1, ARM_AM::lsr     ,  31 } },
2627         /*  8 bit sext */ { { ARM::MOVsi  , 1, ARM_AM::asr     ,  24 },
2628         /*  8 bit zext */   { ARM::MOVsi  , 1, ARM_AM::lsr     ,  24 } },
2629         /* 16 bit sext */ { { ARM::MOVsi  , 1, ARM_AM::asr     ,  16 },
2630         /* 16 bit zext */   { ARM::MOVsi  , 1, ARM_AM::lsr     ,  16 } }
2631       },
2632       { // Thumb              Opc           S  Shift             Imm
2633         /*  1 bit sext */ { { ARM::tASRri , 0, ARM_AM::no_shift,  31 },
2634         /*  1 bit zext */   { ARM::tLSRri , 0, ARM_AM::no_shift,  31 } },
2635         /*  8 bit sext */ { { ARM::tASRri , 0, ARM_AM::no_shift,  24 },
2636         /*  8 bit zext */   { ARM::tLSRri , 0, ARM_AM::no_shift,  24 } },
2637         /* 16 bit sext */ { { ARM::tASRri , 0, ARM_AM::no_shift,  16 },
2638         /* 16 bit zext */   { ARM::tLSRri , 0, ARM_AM::no_shift,  16 } }
2639       }
2640     },
2641     { // Single instruction.
2642       { // ARM                Opc           S  Shift             Imm
2643         /*  1 bit sext */ { { ARM::KILL   , 0, ARM_AM::no_shift,   0 },
2644         /*  1 bit zext */   { ARM::ANDri  , 1, ARM_AM::no_shift,   1 } },
2645         /*  8 bit sext */ { { ARM::SXTB   , 0, ARM_AM::no_shift,   0 },
2646         /*  8 bit zext */   { ARM::ANDri  , 1, ARM_AM::no_shift, 255 } },
2647         /* 16 bit sext */ { { ARM::SXTH   , 0, ARM_AM::no_shift,   0 },
2648         /* 16 bit zext */   { ARM::UXTH   , 0, ARM_AM::no_shift,   0 } }
2649       },
2650       { // Thumb              Opc           S  Shift             Imm
2651         /*  1 bit sext */ { { ARM::KILL   , 0, ARM_AM::no_shift,   0 },
2652         /*  1 bit zext */   { ARM::t2ANDri, 1, ARM_AM::no_shift,   1 } },
2653         /*  8 bit sext */ { { ARM::t2SXTB , 0, ARM_AM::no_shift,   0 },
2654         /*  8 bit zext */   { ARM::t2ANDri, 1, ARM_AM::no_shift, 255 } },
2655         /* 16 bit sext */ { { ARM::t2SXTH , 0, ARM_AM::no_shift,   0 },
2656         /* 16 bit zext */   { ARM::t2UXTH , 0, ARM_AM::no_shift,   0 } }
2657       }
2658     }
2659   };
2660 
2661   unsigned SrcBits = SrcVT.getSizeInBits();
2662   unsigned DestBits = DestVT.getSizeInBits();
2663   (void) DestBits;
2664   assert((SrcBits < DestBits) && "can only extend to larger types");
2665   assert((DestBits == 32 || DestBits == 16 || DestBits == 8) &&
2666          "other sizes unimplemented");
2667   assert((SrcBits == 16 || SrcBits == 8 || SrcBits == 1) &&
2668          "other sizes unimplemented");
2669 
2670   bool hasV6Ops = Subtarget->hasV6Ops();
2671   unsigned Bitness = SrcBits / 8;  // {1,8,16}=>{0,1,2}
2672   assert((Bitness < 3) && "sanity-check table bounds");
2673 
2674   bool isSingleInstr = isSingleInstrTbl[Bitness][isThumb2][hasV6Ops][isZExt];
2675   const TargetRegisterClass *RC = RCTbl[isThumb2][isSingleInstr];
2676   const InstructionTable *ITP = &IT[isSingleInstr][isThumb2][Bitness][isZExt];
2677   unsigned Opc = ITP->Opc;
2678   assert(ARM::KILL != Opc && "Invalid table entry");
2679   unsigned hasS = ITP->hasS;
2680   ARM_AM::ShiftOpc Shift = (ARM_AM::ShiftOpc) ITP->Shift;
2681   assert(((Shift == ARM_AM::no_shift) == (Opc != ARM::MOVsi)) &&
2682          "only MOVsi has shift operand addressing mode");
2683   unsigned Imm = ITP->Imm;
2684 
2685   // 16-bit Thumb instructions always set CPSR (unless they're in an IT block).
2686   bool setsCPSR = &ARM::tGPRRegClass == RC;
2687   unsigned LSLOpc = isThumb2 ? ARM::tLSLri : ARM::MOVsi;
2688   unsigned ResultReg;
2689   // MOVsi encodes shift and immediate in shift operand addressing mode.
2690   // The following condition has the same value when emitting two
2691   // instruction sequences: both are shifts.
2692   bool ImmIsSO = (Shift != ARM_AM::no_shift);
2693 
2694   // Either one or two instructions are emitted.
2695   // They're always of the form:
2696   //   dst = in OP imm
2697   // CPSR is set only by 16-bit Thumb instructions.
2698   // Predicate, if any, is AL.
2699   // S bit, if available, is always 0.
2700   // When two are emitted the first's result will feed as the second's input,
2701   // that value is then dead.
2702   unsigned NumInstrsEmitted = isSingleInstr ? 1 : 2;
2703   for (unsigned Instr = 0; Instr != NumInstrsEmitted; ++Instr) {
2704     ResultReg = createResultReg(RC);
2705     bool isLsl = (0 == Instr) && !isSingleInstr;
2706     unsigned Opcode = isLsl ? LSLOpc : Opc;
2707     ARM_AM::ShiftOpc ShiftAM = isLsl ? ARM_AM::lsl : Shift;
2708     unsigned ImmEnc = ImmIsSO ? ARM_AM::getSORegOpc(ShiftAM, Imm) : Imm;
2709     bool isKill = 1 == Instr;
2710     MachineInstrBuilder MIB = BuildMI(
2711         *FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opcode), ResultReg);
2712     if (setsCPSR)
2713       MIB.addReg(ARM::CPSR, RegState::Define);
2714     SrcReg = constrainOperandRegClass(TII.get(Opcode), SrcReg, 1 + setsCPSR);
2715     MIB.addReg(SrcReg, isKill * RegState::Kill)
2716         .addImm(ImmEnc)
2717         .add(predOps(ARMCC::AL));
2718     if (hasS)
2719       MIB.add(condCodeOp());
2720     // Second instruction consumes the first's result.
2721     SrcReg = ResultReg;
2722   }
2723 
2724   return ResultReg;
2725 }
2726 
2727 bool ARMFastISel::SelectIntExt(const Instruction *I) {
2728   // On ARM, in general, integer casts don't involve legal types; this code
2729   // handles promotable integers.
2730   Type *DestTy = I->getType();
2731   Value *Src = I->getOperand(0);
2732   Type *SrcTy = Src->getType();
2733 
2734   bool isZExt = isa<ZExtInst>(I);
2735   unsigned SrcReg = getRegForValue(Src);
2736   if (!SrcReg) return false;
2737 
2738   EVT SrcEVT, DestEVT;
2739   SrcEVT = TLI.getValueType(DL, SrcTy, true);
2740   DestEVT = TLI.getValueType(DL, DestTy, true);
2741   if (!SrcEVT.isSimple()) return false;
2742   if (!DestEVT.isSimple()) return false;
2743 
2744   MVT SrcVT = SrcEVT.getSimpleVT();
2745   MVT DestVT = DestEVT.getSimpleVT();
2746   unsigned ResultReg = ARMEmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
2747   if (ResultReg == 0) return false;
2748   updateValueMap(I, ResultReg);
2749   return true;
2750 }
2751 
2752 bool ARMFastISel::SelectShift(const Instruction *I,
2753                               ARM_AM::ShiftOpc ShiftTy) {
2754   // We handle thumb2 mode by target independent selector
2755   // or SelectionDAG ISel.
2756   if (isThumb2)
2757     return false;
2758 
2759   // Only handle i32 now.
2760   EVT DestVT = TLI.getValueType(DL, I->getType(), true);
2761   if (DestVT != MVT::i32)
2762     return false;
2763 
2764   unsigned Opc = ARM::MOVsr;
2765   unsigned ShiftImm;
2766   Value *Src2Value = I->getOperand(1);
2767   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Src2Value)) {
2768     ShiftImm = CI->getZExtValue();
2769 
2770     // Fall back to selection DAG isel if the shift amount
2771     // is zero or greater than the width of the value type.
2772     if (ShiftImm == 0 || ShiftImm >=32)
2773       return false;
2774 
2775     Opc = ARM::MOVsi;
2776   }
2777 
2778   Value *Src1Value = I->getOperand(0);
2779   unsigned Reg1 = getRegForValue(Src1Value);
2780   if (Reg1 == 0) return false;
2781 
2782   unsigned Reg2 = 0;
2783   if (Opc == ARM::MOVsr) {
2784     Reg2 = getRegForValue(Src2Value);
2785     if (Reg2 == 0) return false;
2786   }
2787 
2788   unsigned ResultReg = createResultReg(&ARM::GPRnopcRegClass);
2789   if(ResultReg == 0) return false;
2790 
2791   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2792                                     TII.get(Opc), ResultReg)
2793                             .addReg(Reg1);
2794 
2795   if (Opc == ARM::MOVsi)
2796     MIB.addImm(ARM_AM::getSORegOpc(ShiftTy, ShiftImm));
2797   else if (Opc == ARM::MOVsr) {
2798     MIB.addReg(Reg2);
2799     MIB.addImm(ARM_AM::getSORegOpc(ShiftTy, 0));
2800   }
2801 
2802   AddOptionalDefs(MIB);
2803   updateValueMap(I, ResultReg);
2804   return true;
2805 }
2806 
2807 // TODO: SoftFP support.
2808 bool ARMFastISel::fastSelectInstruction(const Instruction *I) {
2809   switch (I->getOpcode()) {
2810     case Instruction::Load:
2811       return SelectLoad(I);
2812     case Instruction::Store:
2813       return SelectStore(I);
2814     case Instruction::Br:
2815       return SelectBranch(I);
2816     case Instruction::IndirectBr:
2817       return SelectIndirectBr(I);
2818     case Instruction::ICmp:
2819     case Instruction::FCmp:
2820       return SelectCmp(I);
2821     case Instruction::FPExt:
2822       return SelectFPExt(I);
2823     case Instruction::FPTrunc:
2824       return SelectFPTrunc(I);
2825     case Instruction::SIToFP:
2826       return SelectIToFP(I, /*isSigned*/ true);
2827     case Instruction::UIToFP:
2828       return SelectIToFP(I, /*isSigned*/ false);
2829     case Instruction::FPToSI:
2830       return SelectFPToI(I, /*isSigned*/ true);
2831     case Instruction::FPToUI:
2832       return SelectFPToI(I, /*isSigned*/ false);
2833     case Instruction::Add:
2834       return SelectBinaryIntOp(I, ISD::ADD);
2835     case Instruction::Or:
2836       return SelectBinaryIntOp(I, ISD::OR);
2837     case Instruction::Sub:
2838       return SelectBinaryIntOp(I, ISD::SUB);
2839     case Instruction::FAdd:
2840       return SelectBinaryFPOp(I, ISD::FADD);
2841     case Instruction::FSub:
2842       return SelectBinaryFPOp(I, ISD::FSUB);
2843     case Instruction::FMul:
2844       return SelectBinaryFPOp(I, ISD::FMUL);
2845     case Instruction::SDiv:
2846       return SelectDiv(I, /*isSigned*/ true);
2847     case Instruction::UDiv:
2848       return SelectDiv(I, /*isSigned*/ false);
2849     case Instruction::SRem:
2850       return SelectRem(I, /*isSigned*/ true);
2851     case Instruction::URem:
2852       return SelectRem(I, /*isSigned*/ false);
2853     case Instruction::Call:
2854       if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2855         return SelectIntrinsicCall(*II);
2856       return SelectCall(I);
2857     case Instruction::Select:
2858       return SelectSelect(I);
2859     case Instruction::Ret:
2860       return SelectRet(I);
2861     case Instruction::Trunc:
2862       return SelectTrunc(I);
2863     case Instruction::ZExt:
2864     case Instruction::SExt:
2865       return SelectIntExt(I);
2866     case Instruction::Shl:
2867       return SelectShift(I, ARM_AM::lsl);
2868     case Instruction::LShr:
2869       return SelectShift(I, ARM_AM::lsr);
2870     case Instruction::AShr:
2871       return SelectShift(I, ARM_AM::asr);
2872     default: break;
2873   }
2874   return false;
2875 }
2876 
2877 namespace {
2878 
2879 // This table describes sign- and zero-extend instructions which can be
2880 // folded into a preceding load. All of these extends have an immediate
2881 // (sometimes a mask and sometimes a shift) that's applied after
2882 // extension.
2883 const struct FoldableLoadExtendsStruct {
2884   uint16_t Opc[2];  // ARM, Thumb.
2885   uint8_t ExpectedImm;
2886   uint8_t isZExt     : 1;
2887   uint8_t ExpectedVT : 7;
2888 } FoldableLoadExtends[] = {
2889   { { ARM::SXTH,  ARM::t2SXTH  },   0, 0, MVT::i16 },
2890   { { ARM::UXTH,  ARM::t2UXTH  },   0, 1, MVT::i16 },
2891   { { ARM::ANDri, ARM::t2ANDri }, 255, 1, MVT::i8  },
2892   { { ARM::SXTB,  ARM::t2SXTB  },   0, 0, MVT::i8  },
2893   { { ARM::UXTB,  ARM::t2UXTB  },   0, 1, MVT::i8  }
2894 };
2895 
2896 } // end anonymous namespace
2897 
2898 /// \brief The specified machine instr operand is a vreg, and that
2899 /// vreg is being provided by the specified load instruction.  If possible,
2900 /// try to fold the load as an operand to the instruction, returning true if
2901 /// successful.
2902 bool ARMFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2903                                       const LoadInst *LI) {
2904   // Verify we have a legal type before going any further.
2905   MVT VT;
2906   if (!isLoadTypeLegal(LI->getType(), VT))
2907     return false;
2908 
2909   // Combine load followed by zero- or sign-extend.
2910   // ldrb r1, [r0]       ldrb r1, [r0]
2911   // uxtb r2, r1     =>
2912   // mov  r3, r2         mov  r3, r1
2913   if (MI->getNumOperands() < 3 || !MI->getOperand(2).isImm())
2914     return false;
2915   const uint64_t Imm = MI->getOperand(2).getImm();
2916 
2917   bool Found = false;
2918   bool isZExt;
2919   for (unsigned i = 0, e = array_lengthof(FoldableLoadExtends);
2920        i != e; ++i) {
2921     if (FoldableLoadExtends[i].Opc[isThumb2] == MI->getOpcode() &&
2922         (uint64_t)FoldableLoadExtends[i].ExpectedImm == Imm &&
2923         MVT((MVT::SimpleValueType)FoldableLoadExtends[i].ExpectedVT) == VT) {
2924       Found = true;
2925       isZExt = FoldableLoadExtends[i].isZExt;
2926     }
2927   }
2928   if (!Found) return false;
2929 
2930   // See if we can handle this address.
2931   Address Addr;
2932   if (!ARMComputeAddress(LI->getOperand(0), Addr)) return false;
2933 
2934   unsigned ResultReg = MI->getOperand(0).getReg();
2935   if (!ARMEmitLoad(VT, ResultReg, Addr, LI->getAlignment(), isZExt, false))
2936     return false;
2937   MI->eraseFromParent();
2938   return true;
2939 }
2940 
2941 unsigned ARMFastISel::ARMLowerPICELF(const GlobalValue *GV,
2942                                      unsigned Align, MVT VT) {
2943   bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
2944 
2945   LLVMContext *Context = &MF->getFunction()->getContext();
2946   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2947   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2948   ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2949       GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2950       UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2951       /*AddCurrentAddress=*/UseGOT_PREL);
2952 
2953   unsigned ConstAlign =
2954       MF->getDataLayout().getPrefTypeAlignment(Type::getInt32PtrTy(*Context));
2955   unsigned Idx = MF->getConstantPool()->getConstantPoolIndex(CPV, ConstAlign);
2956 
2957   unsigned TempReg = MF->getRegInfo().createVirtualRegister(&ARM::rGPRRegClass);
2958   unsigned Opc = isThumb2 ? ARM::t2LDRpci : ARM::LDRcp;
2959   MachineInstrBuilder MIB =
2960       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), TempReg)
2961           .addConstantPoolIndex(Idx);
2962   if (Opc == ARM::LDRcp)
2963     MIB.addImm(0);
2964   MIB.add(predOps(ARMCC::AL));
2965 
2966   // Fix the address by adding pc.
2967   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
2968   Opc = Subtarget->isThumb() ? ARM::tPICADD : UseGOT_PREL ? ARM::PICLDR
2969                                                           : ARM::PICADD;
2970   DestReg = constrainOperandRegClass(TII.get(Opc), DestReg, 0);
2971   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
2972             .addReg(TempReg)
2973             .addImm(ARMPCLabelIndex);
2974   if (!Subtarget->isThumb())
2975     MIB.add(predOps(ARMCC::AL));
2976 
2977   if (UseGOT_PREL && Subtarget->isThumb()) {
2978     unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
2979     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2980                   TII.get(ARM::t2LDRi12), NewDestReg)
2981               .addReg(DestReg)
2982               .addImm(0);
2983     DestReg = NewDestReg;
2984     AddOptionalDefs(MIB);
2985   }
2986   return DestReg;
2987 }
2988 
2989 bool ARMFastISel::fastLowerArguments() {
2990   if (!FuncInfo.CanLowerReturn)
2991     return false;
2992 
2993   const Function *F = FuncInfo.Fn;
2994   if (F->isVarArg())
2995     return false;
2996 
2997   CallingConv::ID CC = F->getCallingConv();
2998   switch (CC) {
2999   default:
3000     return false;
3001   case CallingConv::Fast:
3002   case CallingConv::C:
3003   case CallingConv::ARM_AAPCS_VFP:
3004   case CallingConv::ARM_AAPCS:
3005   case CallingConv::ARM_APCS:
3006   case CallingConv::Swift:
3007     break;
3008   }
3009 
3010   // Only handle simple cases. i.e. Up to 4 i8/i16/i32 scalar arguments
3011   // which are passed in r0 - r3.
3012   unsigned Idx = 1;
3013   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
3014        I != E; ++I, ++Idx) {
3015     if (Idx > 4)
3016       return false;
3017 
3018     if (F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
3019         F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
3020         F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
3021         F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
3022         F->getAttributes().hasAttribute(Idx, Attribute::ByVal))
3023       return false;
3024 
3025     Type *ArgTy = I->getType();
3026     if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
3027       return false;
3028 
3029     EVT ArgVT = TLI.getValueType(DL, ArgTy);
3030     if (!ArgVT.isSimple()) return false;
3031     switch (ArgVT.getSimpleVT().SimpleTy) {
3032     case MVT::i8:
3033     case MVT::i16:
3034     case MVT::i32:
3035       break;
3036     default:
3037       return false;
3038     }
3039   }
3040 
3041   static const MCPhysReg GPRArgRegs[] = {
3042     ARM::R0, ARM::R1, ARM::R2, ARM::R3
3043   };
3044 
3045   const TargetRegisterClass *RC = &ARM::rGPRRegClass;
3046   Idx = 0;
3047   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
3048        I != E; ++I, ++Idx) {
3049     unsigned SrcReg = GPRArgRegs[Idx];
3050     unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3051     // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3052     // Without this, EmitLiveInCopies may eliminate the livein if its only
3053     // use is a bitcast (which isn't turned into an instruction).
3054     unsigned ResultReg = createResultReg(RC);
3055     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3056             TII.get(TargetOpcode::COPY),
3057             ResultReg).addReg(DstReg, getKillRegState(true));
3058     updateValueMap(&*I, ResultReg);
3059   }
3060 
3061   return true;
3062 }
3063 
3064 namespace llvm {
3065 
3066   FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo,
3067                                 const TargetLibraryInfo *libInfo) {
3068     if (funcInfo.MF->getSubtarget<ARMSubtarget>().useFastISel())
3069       return new ARMFastISel(funcInfo, libInfo);
3070 
3071     return nullptr;
3072   }
3073 
3074 } // end namespace llvm
3075