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