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