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