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