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