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