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