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