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