Fix a rather obscure crash caused by ARM fast-isel generating code which redefines...
[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 "ARMRegisterInfo.h"
20 #include "ARMTargetMachine.h"
21 #include "ARMSubtarget.h"
22 #include "ARMConstantPoolValue.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/Module.h"
29 #include "llvm/Operator.h"
30 #include "llvm/CodeGen/Analysis.h"
31 #include "llvm/CodeGen/FastISel.h"
32 #include "llvm/CodeGen/FunctionLoweringInfo.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineConstantPool.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/PseudoSourceValue.h"
40 #include "llvm/Support/CallSite.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/GetElementPtrTypeIterator.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 using namespace llvm;
50
51 static cl::opt<bool>
52 DisableARMFastISel("disable-arm-fast-isel",
53                     cl::desc("Turn off experimental ARM fast-isel support"),
54                     cl::init(false), cl::Hidden);
55
56 extern cl::opt<bool> EnableARMLongCalls;
57
58 namespace {
59
60   // All possible address modes, plus some.
61   typedef struct Address {
62     enum {
63       RegBase,
64       FrameIndexBase
65     } BaseType;
66
67     union {
68       unsigned Reg;
69       int FI;
70     } Base;
71
72     int Offset;
73     unsigned Scale;
74     unsigned PlusReg;
75
76     // Innocuous defaults for our address.
77     Address()
78      : BaseType(RegBase), Offset(0), Scale(0), PlusReg(0) {
79        Base.Reg = 0;
80      }
81   } Address;
82
83 class ARMFastISel : public FastISel {
84
85   /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
86   /// make the right decision when generating code for different targets.
87   const ARMSubtarget *Subtarget;
88   const TargetMachine &TM;
89   const TargetInstrInfo &TII;
90   const TargetLowering &TLI;
91   ARMFunctionInfo *AFI;
92
93   // Convenience variables to avoid some queries.
94   bool isThumb;
95   LLVMContext *Context;
96
97   public:
98     explicit ARMFastISel(FunctionLoweringInfo &funcInfo)
99     : FastISel(funcInfo),
100       TM(funcInfo.MF->getTarget()),
101       TII(*TM.getInstrInfo()),
102       TLI(*TM.getTargetLowering()) {
103       Subtarget = &TM.getSubtarget<ARMSubtarget>();
104       AFI = funcInfo.MF->getInfo<ARMFunctionInfo>();
105       isThumb = AFI->isThumbFunction();
106       Context = &funcInfo.Fn->getContext();
107     }
108
109     // Code from FastISel.cpp.
110     virtual unsigned FastEmitInst_(unsigned MachineInstOpcode,
111                                    const TargetRegisterClass *RC);
112     virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
113                                     const TargetRegisterClass *RC,
114                                     unsigned Op0, bool Op0IsKill);
115     virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
116                                      const TargetRegisterClass *RC,
117                                      unsigned Op0, bool Op0IsKill,
118                                      unsigned Op1, bool Op1IsKill);
119     virtual unsigned FastEmitInst_rrr(unsigned MachineInstOpcode,
120                                       const TargetRegisterClass *RC,
121                                       unsigned Op0, bool Op0IsKill,
122                                       unsigned Op1, bool Op1IsKill,
123                                       unsigned Op2, bool Op2IsKill);
124     virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
125                                      const TargetRegisterClass *RC,
126                                      unsigned Op0, bool Op0IsKill,
127                                      uint64_t Imm);
128     virtual unsigned FastEmitInst_rf(unsigned MachineInstOpcode,
129                                      const TargetRegisterClass *RC,
130                                      unsigned Op0, bool Op0IsKill,
131                                      const ConstantFP *FPImm);
132     virtual unsigned FastEmitInst_rri(unsigned MachineInstOpcode,
133                                       const TargetRegisterClass *RC,
134                                       unsigned Op0, bool Op0IsKill,
135                                       unsigned Op1, bool Op1IsKill,
136                                       uint64_t Imm);
137     virtual unsigned FastEmitInst_i(unsigned MachineInstOpcode,
138                                     const TargetRegisterClass *RC,
139                                     uint64_t Imm);
140
141     virtual unsigned FastEmitInst_extractsubreg(MVT RetVT,
142                                                 unsigned Op0, bool Op0IsKill,
143                                                 uint32_t Idx);
144
145     // Backend specific FastISel code.
146     virtual bool TargetSelectInstruction(const Instruction *I);
147     virtual unsigned TargetMaterializeConstant(const Constant *C);
148     virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
149
150   #include "ARMGenFastISel.inc"
151
152     // Instruction selection routines.
153   private:
154     bool SelectLoad(const Instruction *I);
155     bool SelectStore(const Instruction *I);
156     bool SelectBranch(const Instruction *I);
157     bool SelectCmp(const Instruction *I);
158     bool SelectFPExt(const Instruction *I);
159     bool SelectFPTrunc(const Instruction *I);
160     bool SelectBinaryOp(const Instruction *I, unsigned ISDOpcode);
161     bool SelectSIToFP(const Instruction *I);
162     bool SelectFPToSI(const Instruction *I);
163     bool SelectSDiv(const Instruction *I);
164     bool SelectSRem(const Instruction *I);
165     bool SelectCall(const Instruction *I);
166     bool SelectSelect(const Instruction *I);
167     bool SelectRet(const Instruction *I);
168
169     // Utility routines.
170   private:
171     bool isTypeLegal(const Type *Ty, MVT &VT);
172     bool isLoadTypeLegal(const Type *Ty, MVT &VT);
173     bool ARMEmitLoad(EVT VT, unsigned &ResultReg, Address &Addr);
174     bool ARMEmitStore(EVT VT, unsigned SrcReg, Address &Addr);
175     bool ARMComputeAddress(const Value *Obj, Address &Addr);
176     void ARMSimplifyAddress(Address &Addr, EVT VT);
177     unsigned ARMMaterializeFP(const ConstantFP *CFP, EVT VT);
178     unsigned ARMMaterializeInt(const Constant *C, EVT VT);
179     unsigned ARMMaterializeGV(const GlobalValue *GV, EVT VT);
180     unsigned ARMMoveToFPReg(EVT VT, unsigned SrcReg);
181     unsigned ARMMoveToIntReg(EVT VT, unsigned SrcReg);
182     unsigned ARMSelectCallOp(const GlobalValue *GV);
183
184     // Call handling routines.
185   private:
186     bool FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
187                         unsigned &ResultReg);
188     CCAssignFn *CCAssignFnForCall(CallingConv::ID CC, bool Return);
189     bool ProcessCallArgs(SmallVectorImpl<Value*> &Args,
190                          SmallVectorImpl<unsigned> &ArgRegs,
191                          SmallVectorImpl<MVT> &ArgVTs,
192                          SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
193                          SmallVectorImpl<unsigned> &RegArgs,
194                          CallingConv::ID CC,
195                          unsigned &NumBytes);
196     bool FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
197                     const Instruction *I, CallingConv::ID CC,
198                     unsigned &NumBytes);
199     bool ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call);
200
201     // OptionalDef handling routines.
202   private:
203     bool isARMNEONPred(const MachineInstr *MI);
204     bool DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR);
205     const MachineInstrBuilder &AddOptionalDefs(const MachineInstrBuilder &MIB);
206     void AddLoadStoreOperands(EVT VT, Address &Addr,
207                               const MachineInstrBuilder &MIB);
208 };
209
210 } // end anonymous namespace
211
212 #include "ARMGenCallingConv.inc"
213
214 // DefinesOptionalPredicate - This is different from DefinesPredicate in that
215 // we don't care about implicit defs here, just places we'll need to add a
216 // default CCReg argument. Sets CPSR if we're setting CPSR instead of CCR.
217 bool ARMFastISel::DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR) {
218   const TargetInstrDesc &TID = MI->getDesc();
219   if (!TID.hasOptionalDef())
220     return false;
221
222   // Look to see if our OptionalDef is defining CPSR or CCR.
223   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
224     const MachineOperand &MO = MI->getOperand(i);
225     if (!MO.isReg() || !MO.isDef()) continue;
226     if (MO.getReg() == ARM::CPSR)
227       *CPSR = true;
228   }
229   return true;
230 }
231
232 bool ARMFastISel::isARMNEONPred(const MachineInstr *MI) {
233   const TargetInstrDesc &TID = MI->getDesc();
234   
235   // If we're a thumb2 or not NEON function we were handled via isPredicable.
236   if ((TID.TSFlags & ARMII::DomainMask) != ARMII::DomainNEON ||
237        AFI->isThumb2Function())
238     return false;
239   
240   for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i)
241     if (TID.OpInfo[i].isPredicate())
242       return true;
243   
244   return false;
245 }
246
247 // If the machine is predicable go ahead and add the predicate operands, if
248 // it needs default CC operands add those.
249 // TODO: If we want to support thumb1 then we'll need to deal with optional
250 // CPSR defs that need to be added before the remaining operands. See s_cc_out
251 // for descriptions why.
252 const MachineInstrBuilder &
253 ARMFastISel::AddOptionalDefs(const MachineInstrBuilder &MIB) {
254   MachineInstr *MI = &*MIB;
255
256   // Do we use a predicate? or...
257   // Are we NEON in ARM mode and have a predicate operand? If so, I know
258   // we're not predicable but add it anyways.
259   if (TII.isPredicable(MI) || isARMNEONPred(MI))
260     AddDefaultPred(MIB);
261   
262   // Do we optionally set a predicate?  Preds is size > 0 iff the predicate
263   // defines CPSR. All other OptionalDefines in ARM are the CCR register.
264   bool CPSR = false;
265   if (DefinesOptionalPredicate(MI, &CPSR)) {
266     if (CPSR)
267       AddDefaultT1CC(MIB);
268     else
269       AddDefaultCC(MIB);
270   }
271   return MIB;
272 }
273
274 unsigned ARMFastISel::FastEmitInst_(unsigned MachineInstOpcode,
275                                     const TargetRegisterClass* RC) {
276   unsigned ResultReg = createResultReg(RC);
277   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
278
279   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg));
280   return ResultReg;
281 }
282
283 unsigned ARMFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
284                                      const TargetRegisterClass *RC,
285                                      unsigned Op0, bool Op0IsKill) {
286   unsigned ResultReg = createResultReg(RC);
287   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
288
289   if (II.getNumDefs() >= 1)
290     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
291                    .addReg(Op0, Op0IsKill * RegState::Kill));
292   else {
293     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
294                    .addReg(Op0, Op0IsKill * RegState::Kill));
295     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
296                    TII.get(TargetOpcode::COPY), ResultReg)
297                    .addReg(II.ImplicitDefs[0]));
298   }
299   return ResultReg;
300 }
301
302 unsigned ARMFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
303                                       const TargetRegisterClass *RC,
304                                       unsigned Op0, bool Op0IsKill,
305                                       unsigned Op1, bool Op1IsKill) {
306   unsigned ResultReg = createResultReg(RC);
307   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
308
309   if (II.getNumDefs() >= 1)
310     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
311                    .addReg(Op0, Op0IsKill * RegState::Kill)
312                    .addReg(Op1, Op1IsKill * RegState::Kill));
313   else {
314     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
315                    .addReg(Op0, Op0IsKill * RegState::Kill)
316                    .addReg(Op1, Op1IsKill * RegState::Kill));
317     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
318                            TII.get(TargetOpcode::COPY), ResultReg)
319                    .addReg(II.ImplicitDefs[0]));
320   }
321   return ResultReg;
322 }
323
324 unsigned ARMFastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
325                                        const TargetRegisterClass *RC,
326                                        unsigned Op0, bool Op0IsKill,
327                                        unsigned Op1, bool Op1IsKill,
328                                        unsigned Op2, bool Op2IsKill) {
329   unsigned ResultReg = createResultReg(RC);
330   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
331
332   if (II.getNumDefs() >= 1)
333     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
334                    .addReg(Op0, Op0IsKill * RegState::Kill)
335                    .addReg(Op1, Op1IsKill * RegState::Kill)
336                    .addReg(Op2, Op2IsKill * RegState::Kill));
337   else {
338     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
339                    .addReg(Op0, Op0IsKill * RegState::Kill)
340                    .addReg(Op1, Op1IsKill * RegState::Kill)
341                    .addReg(Op2, Op2IsKill * RegState::Kill));
342     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
343                            TII.get(TargetOpcode::COPY), ResultReg)
344                    .addReg(II.ImplicitDefs[0]));
345   }
346   return ResultReg;
347 }
348
349 unsigned ARMFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
350                                       const TargetRegisterClass *RC,
351                                       unsigned Op0, bool Op0IsKill,
352                                       uint64_t Imm) {
353   unsigned ResultReg = createResultReg(RC);
354   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
355
356   if (II.getNumDefs() >= 1)
357     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
358                    .addReg(Op0, Op0IsKill * RegState::Kill)
359                    .addImm(Imm));
360   else {
361     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
362                    .addReg(Op0, Op0IsKill * RegState::Kill)
363                    .addImm(Imm));
364     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
365                            TII.get(TargetOpcode::COPY), ResultReg)
366                    .addReg(II.ImplicitDefs[0]));
367   }
368   return ResultReg;
369 }
370
371 unsigned ARMFastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
372                                       const TargetRegisterClass *RC,
373                                       unsigned Op0, bool Op0IsKill,
374                                       const ConstantFP *FPImm) {
375   unsigned ResultReg = createResultReg(RC);
376   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
377
378   if (II.getNumDefs() >= 1)
379     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
380                    .addReg(Op0, Op0IsKill * RegState::Kill)
381                    .addFPImm(FPImm));
382   else {
383     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
384                    .addReg(Op0, Op0IsKill * RegState::Kill)
385                    .addFPImm(FPImm));
386     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
387                            TII.get(TargetOpcode::COPY), ResultReg)
388                    .addReg(II.ImplicitDefs[0]));
389   }
390   return ResultReg;
391 }
392
393 unsigned ARMFastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
394                                        const TargetRegisterClass *RC,
395                                        unsigned Op0, bool Op0IsKill,
396                                        unsigned Op1, bool Op1IsKill,
397                                        uint64_t Imm) {
398   unsigned ResultReg = createResultReg(RC);
399   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
400
401   if (II.getNumDefs() >= 1)
402     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
403                    .addReg(Op0, Op0IsKill * RegState::Kill)
404                    .addReg(Op1, Op1IsKill * RegState::Kill)
405                    .addImm(Imm));
406   else {
407     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
408                    .addReg(Op0, Op0IsKill * RegState::Kill)
409                    .addReg(Op1, Op1IsKill * RegState::Kill)
410                    .addImm(Imm));
411     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
412                            TII.get(TargetOpcode::COPY), ResultReg)
413                    .addReg(II.ImplicitDefs[0]));
414   }
415   return ResultReg;
416 }
417
418 unsigned ARMFastISel::FastEmitInst_i(unsigned MachineInstOpcode,
419                                      const TargetRegisterClass *RC,
420                                      uint64_t Imm) {
421   unsigned ResultReg = createResultReg(RC);
422   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
423
424   if (II.getNumDefs() >= 1)
425     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
426                    .addImm(Imm));
427   else {
428     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
429                    .addImm(Imm));
430     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
431                            TII.get(TargetOpcode::COPY), ResultReg)
432                    .addReg(II.ImplicitDefs[0]));
433   }
434   return ResultReg;
435 }
436
437 unsigned ARMFastISel::FastEmitInst_extractsubreg(MVT RetVT,
438                                                  unsigned Op0, bool Op0IsKill,
439                                                  uint32_t Idx) {
440   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
441   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
442          "Cannot yet extract from physregs");
443   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
444                          DL, TII.get(TargetOpcode::COPY), ResultReg)
445                  .addReg(Op0, getKillRegState(Op0IsKill), Idx));
446   return ResultReg;
447 }
448
449 // TODO: Don't worry about 64-bit now, but when this is fixed remove the
450 // checks from the various callers.
451 unsigned ARMFastISel::ARMMoveToFPReg(EVT VT, unsigned SrcReg) {
452   if (VT == MVT::f64) return 0;
453
454   unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
455   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
456                           TII.get(ARM::VMOVRS), MoveReg)
457                   .addReg(SrcReg));
458   return MoveReg;
459 }
460
461 unsigned ARMFastISel::ARMMoveToIntReg(EVT VT, unsigned SrcReg) {
462   if (VT == MVT::i64) return 0;
463
464   unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
465   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
466                           TII.get(ARM::VMOVSR), MoveReg)
467                   .addReg(SrcReg));
468   return MoveReg;
469 }
470
471 // For double width floating point we need to materialize two constants
472 // (the high and the low) into integer registers then use a move to get
473 // the combined constant into an FP reg.
474 unsigned ARMFastISel::ARMMaterializeFP(const ConstantFP *CFP, EVT VT) {
475   const APFloat Val = CFP->getValueAPF();
476   bool is64bit = VT == MVT::f64;
477
478   // This checks to see if we can use VFP3 instructions to materialize
479   // a constant, otherwise we have to go through the constant pool.
480   if (TLI.isFPImmLegal(Val, VT)) {
481     unsigned Opc = is64bit ? ARM::FCONSTD : ARM::FCONSTS;
482     unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
483     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
484                             DestReg)
485                     .addFPImm(CFP));
486     return DestReg;
487   }
488
489   // Require VFP2 for loading fp constants.
490   if (!Subtarget->hasVFP2()) return false;
491
492   // MachineConstantPool wants an explicit alignment.
493   unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
494   if (Align == 0) {
495     // TODO: Figure out if this is correct.
496     Align = TD.getTypeAllocSize(CFP->getType());
497   }
498   unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
499   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
500   unsigned Opc = is64bit ? ARM::VLDRD : ARM::VLDRS;
501
502   // The extra reg is for addrmode5.
503   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
504                           DestReg)
505                   .addConstantPoolIndex(Idx)
506                   .addReg(0));
507   return DestReg;
508 }
509
510 unsigned ARMFastISel::ARMMaterializeInt(const Constant *C, EVT VT) {
511
512   // For now 32-bit only.
513   if (VT != MVT::i32) return false;
514
515   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
516
517   // If we can do this in a single instruction without a constant pool entry
518   // do so now.
519   const ConstantInt *CI = cast<ConstantInt>(C);
520   if (Subtarget->hasV6T2Ops() && isUInt<16>(CI->getSExtValue())) {
521     unsigned Opc = isThumb ? ARM::t2MOVi16 : ARM::MOVi16;
522     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
523                             TII.get(Opc), DestReg)
524                     .addImm(CI->getSExtValue()));
525     return DestReg;
526   }
527
528   // MachineConstantPool wants an explicit alignment.
529   unsigned Align = TD.getPrefTypeAlignment(C->getType());
530   if (Align == 0) {
531     // TODO: Figure out if this is correct.
532     Align = TD.getTypeAllocSize(C->getType());
533   }
534   unsigned Idx = MCP.getConstantPoolIndex(C, Align);
535
536   if (isThumb)
537     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
538                             TII.get(ARM::t2LDRpci), DestReg)
539                     .addConstantPoolIndex(Idx));
540   else
541     // The extra immediate is for addrmode2.
542     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
543                             TII.get(ARM::LDRcp), DestReg)
544                     .addConstantPoolIndex(Idx)
545                     .addImm(0));
546
547   return DestReg;
548 }
549
550 unsigned ARMFastISel::ARMMaterializeGV(const GlobalValue *GV, EVT VT) {
551   // For now 32-bit only.
552   if (VT != MVT::i32) return 0;
553
554   Reloc::Model RelocM = TM.getRelocationModel();
555
556   // TODO: No external globals for now.
557   if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) return 0;
558
559   // TODO: Need more magic for ARM PIC.
560   if (!isThumb && (RelocM == Reloc::PIC_)) return 0;
561
562   // MachineConstantPool wants an explicit alignment.
563   unsigned Align = TD.getPrefTypeAlignment(GV->getType());
564   if (Align == 0) {
565     // TODO: Figure out if this is correct.
566     Align = TD.getTypeAllocSize(GV->getType());
567   }
568
569   // Grab index.
570   unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb() ? 4 : 8);
571   unsigned Id = AFI->createPICLabelUId();
572   ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, Id,
573                                                        ARMCP::CPValue, PCAdj);
574   unsigned Idx = MCP.getConstantPoolIndex(CPV, Align);
575
576   // Load value.
577   MachineInstrBuilder MIB;
578   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
579   if (isThumb) {
580     unsigned Opc = (RelocM != Reloc::PIC_) ? ARM::t2LDRpci : ARM::t2LDRpci_pic;
581     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
582           .addConstantPoolIndex(Idx);
583     if (RelocM == Reloc::PIC_)
584       MIB.addImm(Id);
585   } else {
586     // The extra immediate is for addrmode2.
587     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::LDRcp),
588                   DestReg)
589           .addConstantPoolIndex(Idx)
590           .addImm(0);
591   }
592   AddOptionalDefs(MIB);
593   return DestReg;
594 }
595
596 unsigned ARMFastISel::TargetMaterializeConstant(const Constant *C) {
597   EVT VT = TLI.getValueType(C->getType(), true);
598
599   // Only handle simple types.
600   if (!VT.isSimple()) return 0;
601
602   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
603     return ARMMaterializeFP(CFP, VT);
604   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
605     return ARMMaterializeGV(GV, VT);
606   else if (isa<ConstantInt>(C))
607     return ARMMaterializeInt(C, VT);
608
609   return 0;
610 }
611
612 unsigned ARMFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
613   // Don't handle dynamic allocas.
614   if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
615
616   MVT VT;
617   if (!isLoadTypeLegal(AI->getType(), VT)) return false;
618
619   DenseMap<const AllocaInst*, int>::iterator SI =
620     FuncInfo.StaticAllocaMap.find(AI);
621
622   // This will get lowered later into the correct offsets and registers
623   // via rewriteXFrameIndex.
624   if (SI != FuncInfo.StaticAllocaMap.end()) {
625     TargetRegisterClass* RC = TLI.getRegClassFor(VT);
626     unsigned ResultReg = createResultReg(RC);
627     unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
628     AddOptionalDefs(BuildMI(*FuncInfo.MBB, *FuncInfo.InsertPt, DL,
629                             TII.get(Opc), ResultReg)
630                             .addFrameIndex(SI->second)
631                             .addImm(0));
632     return ResultReg;
633   }
634
635   return 0;
636 }
637
638 bool ARMFastISel::isTypeLegal(const Type *Ty, MVT &VT) {
639   EVT evt = TLI.getValueType(Ty, true);
640
641   // Only handle simple types.
642   if (evt == MVT::Other || !evt.isSimple()) return false;
643   VT = evt.getSimpleVT();
644
645   // Handle all legal types, i.e. a register that will directly hold this
646   // value.
647   return TLI.isTypeLegal(VT);
648 }
649
650 bool ARMFastISel::isLoadTypeLegal(const Type *Ty, MVT &VT) {
651   if (isTypeLegal(Ty, VT)) return true;
652
653   // If this is a type than can be sign or zero-extended to a basic operation
654   // go ahead and accept it now.
655   if (VT == MVT::i8 || VT == MVT::i16)
656     return true;
657
658   return false;
659 }
660
661 // Computes the address to get to an object.
662 bool ARMFastISel::ARMComputeAddress(const Value *Obj, Address &Addr) {
663   // Some boilerplate from the X86 FastISel.
664   const User *U = NULL;
665   unsigned Opcode = Instruction::UserOp1;
666   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
667     // Don't walk into other basic blocks unless the object is an alloca from
668     // another block, otherwise it may not have a virtual register assigned.
669     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
670         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
671       Opcode = I->getOpcode();
672       U = I;
673     }
674   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
675     Opcode = C->getOpcode();
676     U = C;
677   }
678
679   if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
680     if (Ty->getAddressSpace() > 255)
681       // Fast instruction selection doesn't support the special
682       // address spaces.
683       return false;
684
685   switch (Opcode) {
686     default:
687     break;
688     case Instruction::BitCast: {
689       // Look through bitcasts.
690       return ARMComputeAddress(U->getOperand(0), Addr);
691     }
692     case Instruction::IntToPtr: {
693       // Look past no-op inttoptrs.
694       if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
695         return ARMComputeAddress(U->getOperand(0), Addr);
696       break;
697     }
698     case Instruction::PtrToInt: {
699       // Look past no-op ptrtoints.
700       if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
701         return ARMComputeAddress(U->getOperand(0), Addr);
702       break;
703     }
704     case Instruction::GetElementPtr: {
705       Address SavedAddr = Addr;
706       int TmpOffset = Addr.Offset;
707
708       // Iterate through the GEP folding the constants into offsets where
709       // we can.
710       gep_type_iterator GTI = gep_type_begin(U);
711       for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
712            i != e; ++i, ++GTI) {
713         const Value *Op = *i;
714         if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
715           const StructLayout *SL = TD.getStructLayout(STy);
716           unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
717           TmpOffset += SL->getElementOffset(Idx);
718         } else {
719           uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
720           for (;;) {
721             if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
722               // Constant-offset addressing.
723               TmpOffset += CI->getSExtValue() * S;
724               break;
725             }
726             if (isa<AddOperator>(Op) &&
727                 (!isa<Instruction>(Op) ||
728                  FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
729                  == FuncInfo.MBB) &&
730                 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
731               // An add (in the same block) with a constant operand. Fold the 
732               // constant.
733               ConstantInt *CI =
734               cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
735               TmpOffset += CI->getSExtValue() * S;
736               // Iterate on the other operand.
737               Op = cast<AddOperator>(Op)->getOperand(0);
738               continue;
739             } 
740             // Unsupported
741             goto unsupported_gep;
742           }
743         }
744       }
745
746       // Try to grab the base operand now.
747       Addr.Offset = TmpOffset;
748       if (ARMComputeAddress(U->getOperand(0), Addr)) return true;
749
750       // We failed, restore everything and try the other options.
751       Addr = SavedAddr;
752
753       unsupported_gep:
754       break;
755     }
756     case Instruction::Alloca: {
757       const AllocaInst *AI = cast<AllocaInst>(Obj);
758       DenseMap<const AllocaInst*, int>::iterator SI =
759         FuncInfo.StaticAllocaMap.find(AI);
760       if (SI != FuncInfo.StaticAllocaMap.end()) {
761         Addr.BaseType = Address::FrameIndexBase;
762         Addr.Base.FI = SI->second;
763         return true;
764       }
765       break;
766     }
767   }
768
769   // Materialize the global variable's address into a reg which can
770   // then be used later to load the variable.
771   if (const GlobalValue *GV = dyn_cast<GlobalValue>(Obj)) {
772     unsigned Tmp = ARMMaterializeGV(GV, TLI.getValueType(Obj->getType()));
773     if (Tmp == 0) return false;
774
775     Addr.Base.Reg = Tmp;
776     return true;
777   }
778
779   // Try to get this in a register if nothing else has worked.
780   if (Addr.Base.Reg == 0) Addr.Base.Reg = getRegForValue(Obj);
781   return Addr.Base.Reg != 0;
782 }
783
784 void ARMFastISel::ARMSimplifyAddress(Address &Addr, EVT VT) {
785
786   assert(VT.isSimple() && "Non-simple types are invalid here!");
787
788   bool needsLowering = false;
789   switch (VT.getSimpleVT().SimpleTy) {
790     default:
791       assert(false && "Unhandled load/store type!");
792     case MVT::i1:
793     case MVT::i8:
794     case MVT::i16:
795     case MVT::i32:
796       // Integer loads/stores handle 12-bit offsets.
797       needsLowering = ((Addr.Offset & 0xfff) != Addr.Offset);
798       break;
799     case MVT::f32:
800     case MVT::f64:
801       // Floating point operands handle 8-bit offsets.
802       needsLowering = ((Addr.Offset & 0xff) != Addr.Offset);
803       break;
804   }
805
806   // If this is a stack pointer and the offset needs to be simplified then
807   // put the alloca address into a register, set the base type back to
808   // register and continue. This should almost never happen.
809   if (needsLowering && Addr.BaseType == Address::FrameIndexBase) {
810     TargetRegisterClass *RC = isThumb ? ARM::tGPRRegisterClass :
811                               ARM::GPRRegisterClass;
812     unsigned ResultReg = createResultReg(RC);
813     unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
814     AddOptionalDefs(BuildMI(*FuncInfo.MBB, *FuncInfo.InsertPt, DL,
815                             TII.get(Opc), ResultReg)
816                             .addFrameIndex(Addr.Base.FI)
817                             .addImm(0));
818     Addr.Base.Reg = ResultReg;
819     Addr.BaseType = Address::RegBase;
820   }
821
822   // Since the offset is too large for the load/store instruction
823   // get the reg+offset into a register.
824   if (needsLowering) {
825     Addr.Base.Reg = FastEmit_ri_(MVT::i32, ISD::ADD, Addr.Base.Reg,
826                                  /*Op0IsKill*/false, Addr.Offset, MVT::i32);
827     Addr.Offset = 0;
828   }
829 }
830
831 void ARMFastISel::AddLoadStoreOperands(EVT VT, Address &Addr,
832                                        const MachineInstrBuilder &MIB) {
833   // addrmode5 output depends on the selection dag addressing dividing the
834   // offset by 4 that it then later multiplies. Do this here as well.
835   if (VT.getSimpleVT().SimpleTy == MVT::f32 ||
836       VT.getSimpleVT().SimpleTy == MVT::f64)
837     Addr.Offset /= 4;
838     
839   // Frame base works a bit differently. Handle it separately.
840   if (Addr.BaseType == Address::FrameIndexBase) {
841     int FI = Addr.Base.FI;
842     int Offset = Addr.Offset;
843     MachineMemOperand *MMO =
844           FuncInfo.MF->getMachineMemOperand(
845                                   MachinePointerInfo::getFixedStack(FI, Offset),
846                                   MachineMemOperand::MOLoad,
847                                   MFI.getObjectSize(FI),
848                                   MFI.getObjectAlignment(FI));
849     // Now add the rest of the operands.
850     MIB.addFrameIndex(FI);
851
852     // ARM halfword load/stores need an additional operand.
853     if (!isThumb && VT.getSimpleVT().SimpleTy == MVT::i16) MIB.addReg(0);
854
855     MIB.addImm(Addr.Offset);
856     MIB.addMemOperand(MMO);
857   } else {
858     // Now add the rest of the operands.
859     MIB.addReg(Addr.Base.Reg);
860   
861     // ARM halfword load/stores need an additional operand.
862     if (!isThumb && VT.getSimpleVT().SimpleTy == MVT::i16) MIB.addReg(0);
863
864     MIB.addImm(Addr.Offset);
865   }
866   AddOptionalDefs(MIB);
867 }
868
869 bool ARMFastISel::ARMEmitLoad(EVT VT, unsigned &ResultReg, Address &Addr) {
870
871   assert(VT.isSimple() && "Non-simple types are invalid here!");
872   unsigned Opc;
873   TargetRegisterClass *RC;
874   switch (VT.getSimpleVT().SimpleTy) {
875     // This is mostly going to be Neon/vector support.
876     default: return false;
877     case MVT::i16:
878       Opc = isThumb ? ARM::t2LDRHi12 : ARM::LDRH;
879       RC = ARM::GPRRegisterClass;
880       break;
881     case MVT::i8:
882       Opc = isThumb ? ARM::t2LDRBi12 : ARM::LDRBi12;
883       RC = ARM::GPRRegisterClass;
884       break;
885     case MVT::i32:
886       Opc = isThumb ? ARM::t2LDRi12 : ARM::LDRi12;
887       RC = ARM::GPRRegisterClass;
888       break;
889     case MVT::f32:
890       Opc = ARM::VLDRS;
891       RC = TLI.getRegClassFor(VT);
892       break;
893     case MVT::f64:
894       Opc = ARM::VLDRD;
895       RC = TLI.getRegClassFor(VT);
896       break;
897   }
898   // Simplify this down to something we can handle.
899   ARMSimplifyAddress(Addr, VT);
900
901   // Create the base instruction, then add the operands.
902   ResultReg = createResultReg(RC);
903   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
904                                     TII.get(Opc), ResultReg);
905   AddLoadStoreOperands(VT, Addr, MIB);
906   return true;
907 }
908
909 bool ARMFastISel::SelectLoad(const Instruction *I) {
910   // Verify we have a legal type before going any further.
911   MVT VT;
912   if (!isLoadTypeLegal(I->getType(), VT))
913     return false;
914
915   // See if we can handle this address.
916   Address Addr;
917   if (!ARMComputeAddress(I->getOperand(0), Addr)) return false;
918
919   unsigned ResultReg;
920   if (!ARMEmitLoad(VT, ResultReg, Addr)) return false;
921   UpdateValueMap(I, ResultReg);
922   return true;
923 }
924
925 bool ARMFastISel::ARMEmitStore(EVT VT, unsigned SrcReg, Address &Addr) {
926   unsigned StrOpc;
927   switch (VT.getSimpleVT().SimpleTy) {
928     // This is mostly going to be Neon/vector support.
929     default: return false;
930     case MVT::i1: {
931       unsigned Res = createResultReg(isThumb ? ARM::tGPRRegisterClass :
932                                                ARM::GPRRegisterClass);
933       unsigned Opc = isThumb ? ARM::t2ANDri : ARM::ANDri;
934       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
935                               TII.get(Opc), Res)
936                       .addReg(SrcReg).addImm(1));
937       SrcReg = Res;
938     } // Fallthrough here.
939     case MVT::i8:
940       StrOpc = isThumb ? ARM::t2STRBi12 : ARM::STRBi12;
941       break;
942     case MVT::i16:
943       StrOpc = isThumb ? ARM::t2STRHi12 : ARM::STRH;
944       break;
945     case MVT::i32:
946       StrOpc = isThumb ? ARM::t2STRi12 : ARM::STRi12;
947       break;
948     case MVT::f32:
949       if (!Subtarget->hasVFP2()) return false;
950       StrOpc = ARM::VSTRS;
951       break;
952     case MVT::f64:
953       if (!Subtarget->hasVFP2()) return false;
954       StrOpc = ARM::VSTRD;
955       break;
956   }
957   // Simplify this down to something we can handle.
958   ARMSimplifyAddress(Addr, VT);
959
960   // Create the base instruction, then add the operands.
961   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
962                                     TII.get(StrOpc))
963                             .addReg(SrcReg, getKillRegState(true));
964   AddLoadStoreOperands(VT, Addr, MIB);
965   return true;
966 }
967
968 bool ARMFastISel::SelectStore(const Instruction *I) {
969   Value *Op0 = I->getOperand(0);
970   unsigned SrcReg = 0;
971
972   // Verify we have a legal type before going any further.
973   MVT VT;
974   if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
975     return false;
976
977   // Get the value to be stored into a register.
978   SrcReg = getRegForValue(Op0);
979   if (SrcReg == 0) return false;
980
981   // See if we can handle this address.
982   Address Addr;
983   if (!ARMComputeAddress(I->getOperand(1), Addr))
984     return false;
985
986   if (!ARMEmitStore(VT, SrcReg, Addr)) return false;
987   return true;
988 }
989
990 static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
991   switch (Pred) {
992     // Needs two compares...
993     case CmpInst::FCMP_ONE:
994     case CmpInst::FCMP_UEQ:
995     default:
996       // AL is our "false" for now. The other two need more compares.
997       return ARMCC::AL;
998     case CmpInst::ICMP_EQ:
999     case CmpInst::FCMP_OEQ:
1000       return ARMCC::EQ;
1001     case CmpInst::ICMP_SGT:
1002     case CmpInst::FCMP_OGT:
1003       return ARMCC::GT;
1004     case CmpInst::ICMP_SGE:
1005     case CmpInst::FCMP_OGE:
1006       return ARMCC::GE;
1007     case CmpInst::ICMP_UGT:
1008     case CmpInst::FCMP_UGT:
1009       return ARMCC::HI;
1010     case CmpInst::FCMP_OLT:
1011       return ARMCC::MI;
1012     case CmpInst::ICMP_ULE:
1013     case CmpInst::FCMP_OLE:
1014       return ARMCC::LS;
1015     case CmpInst::FCMP_ORD:
1016       return ARMCC::VC;
1017     case CmpInst::FCMP_UNO:
1018       return ARMCC::VS;
1019     case CmpInst::FCMP_UGE:
1020       return ARMCC::PL;
1021     case CmpInst::ICMP_SLT:
1022     case CmpInst::FCMP_ULT:
1023       return ARMCC::LT;
1024     case CmpInst::ICMP_SLE:
1025     case CmpInst::FCMP_ULE:
1026       return ARMCC::LE;
1027     case CmpInst::FCMP_UNE:
1028     case CmpInst::ICMP_NE:
1029       return ARMCC::NE;
1030     case CmpInst::ICMP_UGE:
1031       return ARMCC::HS;
1032     case CmpInst::ICMP_ULT:
1033       return ARMCC::LO;
1034   }
1035 }
1036
1037 bool ARMFastISel::SelectBranch(const Instruction *I) {
1038   const BranchInst *BI = cast<BranchInst>(I);
1039   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1040   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1041
1042   // Simple branch support.
1043
1044   // If we can, avoid recomputing the compare - redoing it could lead to wonky
1045   // behavior.
1046   // TODO: Factor this out.
1047   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1048     if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
1049       MVT VT;
1050       const Type *Ty = CI->getOperand(0)->getType();
1051       if (!isTypeLegal(Ty, VT))
1052         return false;
1053
1054       bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1055       if (isFloat && !Subtarget->hasVFP2())
1056         return false;
1057
1058       unsigned CmpOpc;
1059       switch (VT.SimpleTy) {
1060         default: return false;
1061         // TODO: Verify compares.
1062         case MVT::f32:
1063           CmpOpc = ARM::VCMPES;
1064           break;
1065         case MVT::f64:
1066           CmpOpc = ARM::VCMPED;
1067           break;
1068         case MVT::i32:
1069           CmpOpc = isThumb ? ARM::t2CMPrr : ARM::CMPrr;
1070           break;
1071       }
1072
1073       // Get the compare predicate.
1074       ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
1075
1076       // We may not handle every CC for now.
1077       if (ARMPred == ARMCC::AL) return false;
1078
1079       unsigned Arg1 = getRegForValue(CI->getOperand(0));
1080       if (Arg1 == 0) return false;
1081
1082       unsigned Arg2 = getRegForValue(CI->getOperand(1));
1083       if (Arg2 == 0) return false;
1084
1085       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1086                               TII.get(CmpOpc))
1087                       .addReg(Arg1).addReg(Arg2));
1088
1089       // For floating point we need to move the result to a comparison register
1090       // that we can then use for branches.
1091       if (isFloat)
1092         AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1093                                 TII.get(ARM::FMSTAT)));
1094
1095       unsigned BrOpc = isThumb ? ARM::t2Bcc : ARM::Bcc;
1096       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1097       .addMBB(TBB).addImm(ARMPred).addReg(ARM::CPSR);
1098       FastEmitBranch(FBB, DL);
1099       FuncInfo.MBB->addSuccessor(TBB);
1100       return true;
1101     }
1102   }
1103
1104   unsigned CmpReg = getRegForValue(BI->getCondition());
1105   if (CmpReg == 0) return false;
1106
1107   // We've been divorced from our compare!  Our block was split, and
1108   // now our compare lives in a predecessor block.  We musn't
1109   // re-compare here, as the children of the compare aren't guaranteed
1110   // live across the block boundary (we *could* check for this).
1111   // Regardless, the compare has been done in the predecessor block,
1112   // and it left a value for us in a virtual register.  Ergo, we test
1113   // the one-bit value left in the virtual register.
1114   unsigned TstOpc = isThumb ? ARM::t2TSTri : ARM::TSTri;
1115   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TstOpc))
1116                   .addReg(CmpReg).addImm(1));
1117
1118   
1119   unsigned CCMode = ARMCC::NE;
1120   if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1121     std::swap(TBB, FBB);
1122     CCMode = ARMCC::EQ;
1123   }
1124
1125   unsigned BrOpc = isThumb ? ARM::t2Bcc : ARM::Bcc;
1126   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1127                   .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1128   FastEmitBranch(FBB, DL);
1129   FuncInfo.MBB->addSuccessor(TBB);
1130   return true;
1131 }
1132
1133 bool ARMFastISel::SelectCmp(const Instruction *I) {
1134   const CmpInst *CI = cast<CmpInst>(I);
1135
1136   MVT VT;
1137   const Type *Ty = CI->getOperand(0)->getType();
1138   if (!isTypeLegal(Ty, VT))
1139     return false;
1140
1141   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1142   if (isFloat && !Subtarget->hasVFP2())
1143     return false;
1144
1145   unsigned CmpOpc;
1146   unsigned CondReg;
1147   switch (VT.SimpleTy) {
1148     default: return false;
1149     // TODO: Verify compares.
1150     case MVT::f32:
1151       CmpOpc = ARM::VCMPES;
1152       CondReg = ARM::FPSCR;
1153       break;
1154     case MVT::f64:
1155       CmpOpc = ARM::VCMPED;
1156       CondReg = ARM::FPSCR;
1157       break;
1158     case MVT::i32:
1159       CmpOpc = isThumb ? ARM::t2CMPrr : ARM::CMPrr;
1160       CondReg = ARM::CPSR;
1161       break;
1162   }
1163
1164   // Get the compare predicate.
1165   ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
1166
1167   // We may not handle every CC for now.
1168   if (ARMPred == ARMCC::AL) return false;
1169
1170   unsigned Arg1 = getRegForValue(CI->getOperand(0));
1171   if (Arg1 == 0) return false;
1172
1173   unsigned Arg2 = getRegForValue(CI->getOperand(1));
1174   if (Arg2 == 0) return false;
1175
1176   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1177                   .addReg(Arg1).addReg(Arg2));
1178
1179   // For floating point we need to move the result to a comparison register
1180   // that we can then use for branches.
1181   if (isFloat)
1182     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1183                             TII.get(ARM::FMSTAT)));
1184
1185   // Now set a register based on the comparison. Explicitly set the predicates
1186   // here.
1187   unsigned MovCCOpc = isThumb ? ARM::t2MOVCCi : ARM::MOVCCi;
1188   TargetRegisterClass *RC = isThumb ? ARM::rGPRRegisterClass
1189                                     : ARM::GPRRegisterClass;
1190   unsigned DestReg = createResultReg(RC);
1191   Constant *Zero
1192     = ConstantInt::get(Type::getInt32Ty(*Context), 0);
1193   unsigned ZeroReg = TargetMaterializeConstant(Zero);
1194   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), DestReg)
1195           .addReg(ZeroReg).addImm(1)
1196           .addImm(ARMPred).addReg(CondReg);
1197
1198   UpdateValueMap(I, DestReg);
1199   return true;
1200 }
1201
1202 bool ARMFastISel::SelectFPExt(const Instruction *I) {
1203   // Make sure we have VFP and that we're extending float to double.
1204   if (!Subtarget->hasVFP2()) return false;
1205
1206   Value *V = I->getOperand(0);
1207   if (!I->getType()->isDoubleTy() ||
1208       !V->getType()->isFloatTy()) return false;
1209
1210   unsigned Op = getRegForValue(V);
1211   if (Op == 0) return false;
1212
1213   unsigned Result = createResultReg(ARM::DPRRegisterClass);
1214   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1215                           TII.get(ARM::VCVTDS), Result)
1216                   .addReg(Op));
1217   UpdateValueMap(I, Result);
1218   return true;
1219 }
1220
1221 bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
1222   // Make sure we have VFP and that we're truncating double to float.
1223   if (!Subtarget->hasVFP2()) return false;
1224
1225   Value *V = I->getOperand(0);
1226   if (!(I->getType()->isFloatTy() &&
1227         V->getType()->isDoubleTy())) return false;
1228
1229   unsigned Op = getRegForValue(V);
1230   if (Op == 0) return false;
1231
1232   unsigned Result = createResultReg(ARM::SPRRegisterClass);
1233   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1234                           TII.get(ARM::VCVTSD), Result)
1235                   .addReg(Op));
1236   UpdateValueMap(I, Result);
1237   return true;
1238 }
1239
1240 bool ARMFastISel::SelectSIToFP(const Instruction *I) {
1241   // Make sure we have VFP.
1242   if (!Subtarget->hasVFP2()) return false;
1243
1244   MVT DstVT;
1245   const Type *Ty = I->getType();
1246   if (!isTypeLegal(Ty, DstVT))
1247     return false;
1248
1249   unsigned Op = getRegForValue(I->getOperand(0));
1250   if (Op == 0) return false;
1251
1252   // The conversion routine works on fp-reg to fp-reg and the operand above
1253   // was an integer, move it to the fp registers if possible.
1254   unsigned FP = ARMMoveToFPReg(MVT::f32, Op);
1255   if (FP == 0) return false;
1256
1257   unsigned Opc;
1258   if (Ty->isFloatTy()) Opc = ARM::VSITOS;
1259   else if (Ty->isDoubleTy()) Opc = ARM::VSITOD;
1260   else return 0;
1261
1262   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1263   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1264                           ResultReg)
1265                   .addReg(FP));
1266   UpdateValueMap(I, ResultReg);
1267   return true;
1268 }
1269
1270 bool ARMFastISel::SelectFPToSI(const Instruction *I) {
1271   // Make sure we have VFP.
1272   if (!Subtarget->hasVFP2()) return false;
1273
1274   MVT DstVT;
1275   const Type *RetTy = I->getType();
1276   if (!isTypeLegal(RetTy, DstVT))
1277     return false;
1278
1279   unsigned Op = getRegForValue(I->getOperand(0));
1280   if (Op == 0) return false;
1281
1282   unsigned Opc;
1283   const Type *OpTy = I->getOperand(0)->getType();
1284   if (OpTy->isFloatTy()) Opc = ARM::VTOSIZS;
1285   else if (OpTy->isDoubleTy()) Opc = ARM::VTOSIZD;
1286   else return 0;
1287
1288   // f64->s32 or f32->s32 both need an intermediate f32 reg.
1289   unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1290   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1291                           ResultReg)
1292                   .addReg(Op));
1293
1294   // This result needs to be in an integer register, but the conversion only
1295   // takes place in fp-regs.
1296   unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1297   if (IntReg == 0) return false;
1298
1299   UpdateValueMap(I, IntReg);
1300   return true;
1301 }
1302
1303 bool ARMFastISel::SelectSelect(const Instruction *I) {
1304   MVT VT;
1305   if (!isTypeLegal(I->getType(), VT))
1306     return false;
1307
1308   // Things need to be register sized for register moves.
1309   if (VT != MVT::i32) return false;
1310   const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
1311
1312   unsigned CondReg = getRegForValue(I->getOperand(0));
1313   if (CondReg == 0) return false;
1314   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1315   if (Op1Reg == 0) return false;
1316   unsigned Op2Reg = getRegForValue(I->getOperand(2));
1317   if (Op2Reg == 0) return false;
1318
1319   unsigned CmpOpc = isThumb ? ARM::t2TSTri : ARM::TSTri;
1320   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1321                   .addReg(CondReg).addImm(1));
1322   unsigned ResultReg = createResultReg(RC);
1323   unsigned MovCCOpc = isThumb ? ARM::t2MOVCCr : ARM::MOVCCr;
1324   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1325     .addReg(Op1Reg).addReg(Op2Reg)
1326     .addImm(ARMCC::EQ).addReg(ARM::CPSR);
1327   UpdateValueMap(I, ResultReg);
1328   return true;
1329 }
1330
1331 bool ARMFastISel::SelectSDiv(const Instruction *I) {
1332   MVT VT;
1333   const Type *Ty = I->getType();
1334   if (!isTypeLegal(Ty, VT))
1335     return false;
1336
1337   // If we have integer div support we should have selected this automagically.
1338   // In case we have a real miss go ahead and return false and we'll pick
1339   // it up later.
1340   if (Subtarget->hasDivide()) return false;
1341
1342   // Otherwise emit a libcall.
1343   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1344   if (VT == MVT::i8)
1345     LC = RTLIB::SDIV_I8;
1346   else if (VT == MVT::i16)
1347     LC = RTLIB::SDIV_I16;
1348   else if (VT == MVT::i32)
1349     LC = RTLIB::SDIV_I32;
1350   else if (VT == MVT::i64)
1351     LC = RTLIB::SDIV_I64;
1352   else if (VT == MVT::i128)
1353     LC = RTLIB::SDIV_I128;
1354   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1355
1356   return ARMEmitLibcall(I, LC);
1357 }
1358
1359 bool ARMFastISel::SelectSRem(const Instruction *I) {
1360   MVT VT;
1361   const Type *Ty = I->getType();
1362   if (!isTypeLegal(Ty, VT))
1363     return false;
1364
1365   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1366   if (VT == MVT::i8)
1367     LC = RTLIB::SREM_I8;
1368   else if (VT == MVT::i16)
1369     LC = RTLIB::SREM_I16;
1370   else if (VT == MVT::i32)
1371     LC = RTLIB::SREM_I32;
1372   else if (VT == MVT::i64)
1373     LC = RTLIB::SREM_I64;
1374   else if (VT == MVT::i128)
1375     LC = RTLIB::SREM_I128;
1376   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1377
1378   return ARMEmitLibcall(I, LC);
1379 }
1380
1381 bool ARMFastISel::SelectBinaryOp(const Instruction *I, unsigned ISDOpcode) {
1382   EVT VT  = TLI.getValueType(I->getType(), true);
1383
1384   // We can get here in the case when we want to use NEON for our fp
1385   // operations, but can't figure out how to. Just use the vfp instructions
1386   // if we have them.
1387   // FIXME: It'd be nice to use NEON instructions.
1388   const Type *Ty = I->getType();
1389   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1390   if (isFloat && !Subtarget->hasVFP2())
1391     return false;
1392
1393   unsigned Op1 = getRegForValue(I->getOperand(0));
1394   if (Op1 == 0) return false;
1395
1396   unsigned Op2 = getRegForValue(I->getOperand(1));
1397   if (Op2 == 0) return false;
1398
1399   unsigned Opc;
1400   bool is64bit = VT == MVT::f64 || VT == MVT::i64;
1401   switch (ISDOpcode) {
1402     default: return false;
1403     case ISD::FADD:
1404       Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1405       break;
1406     case ISD::FSUB:
1407       Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1408       break;
1409     case ISD::FMUL:
1410       Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1411       break;
1412   }
1413   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1414   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1415                           TII.get(Opc), ResultReg)
1416                   .addReg(Op1).addReg(Op2));
1417   UpdateValueMap(I, ResultReg);
1418   return true;
1419 }
1420
1421 // Call Handling Code
1422
1423 bool ARMFastISel::FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src,
1424                                  EVT SrcVT, unsigned &ResultReg) {
1425   unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
1426                            Src, /*TODO: Kill=*/false);
1427
1428   if (RR != 0) {
1429     ResultReg = RR;
1430     return true;
1431   } else
1432     return false;
1433 }
1434
1435 // This is largely taken directly from CCAssignFnForNode - we don't support
1436 // varargs in FastISel so that part has been removed.
1437 // TODO: We may not support all of this.
1438 CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC, bool Return) {
1439   switch (CC) {
1440   default:
1441     llvm_unreachable("Unsupported calling convention");
1442   case CallingConv::Fast:
1443     // Ignore fastcc. Silence compiler warnings.
1444     (void)RetFastCC_ARM_APCS;
1445     (void)FastCC_ARM_APCS;
1446     // Fallthrough
1447   case CallingConv::C:
1448     // Use target triple & subtarget features to do actual dispatch.
1449     if (Subtarget->isAAPCS_ABI()) {
1450       if (Subtarget->hasVFP2() &&
1451           FloatABIType == FloatABI::Hard)
1452         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1453       else
1454         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1455     } else
1456         return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1457   case CallingConv::ARM_AAPCS_VFP:
1458     return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1459   case CallingConv::ARM_AAPCS:
1460     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1461   case CallingConv::ARM_APCS:
1462     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1463   }
1464 }
1465
1466 bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1467                                   SmallVectorImpl<unsigned> &ArgRegs,
1468                                   SmallVectorImpl<MVT> &ArgVTs,
1469                                   SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1470                                   SmallVectorImpl<unsigned> &RegArgs,
1471                                   CallingConv::ID CC,
1472                                   unsigned &NumBytes) {
1473   SmallVector<CCValAssign, 16> ArgLocs;
1474   CCState CCInfo(CC, false, TM, ArgLocs, *Context);
1475   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC, false));
1476
1477   // Get a count of how many bytes are to be pushed on the stack.
1478   NumBytes = CCInfo.getNextStackOffset();
1479
1480   // Issue CALLSEQ_START
1481   unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1482   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1483                           TII.get(AdjStackDown))
1484                   .addImm(NumBytes));
1485
1486   // Process the args.
1487   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1488     CCValAssign &VA = ArgLocs[i];
1489     unsigned Arg = ArgRegs[VA.getValNo()];
1490     MVT ArgVT = ArgVTs[VA.getValNo()];
1491
1492     // We don't handle NEON/vector parameters yet.
1493     if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64)
1494       return false;
1495
1496     // Handle arg promotion, etc.
1497     switch (VA.getLocInfo()) {
1498       case CCValAssign::Full: break;
1499       case CCValAssign::SExt: {
1500         bool Emitted = FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1501                                          Arg, ArgVT, Arg);
1502         assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
1503         Emitted = true;
1504         ArgVT = VA.getLocVT();
1505         break;
1506       }
1507       case CCValAssign::ZExt: {
1508         bool Emitted = FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1509                                          Arg, ArgVT, Arg);
1510         assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
1511         Emitted = true;
1512         ArgVT = VA.getLocVT();
1513         break;
1514       }
1515       case CCValAssign::AExt: {
1516         bool Emitted = FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1517                                          Arg, ArgVT, Arg);
1518         if (!Emitted)
1519           Emitted = FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1520                                       Arg, ArgVT, Arg);
1521         if (!Emitted)
1522           Emitted = FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1523                                       Arg, ArgVT, Arg);
1524
1525         assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
1526         ArgVT = VA.getLocVT();
1527         break;
1528       }
1529       case CCValAssign::BCvt: {
1530         unsigned BC = FastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, Arg,
1531                                  /*TODO: Kill=*/false);
1532         assert(BC != 0 && "Failed to emit a bitcast!");
1533         Arg = BC;
1534         ArgVT = VA.getLocVT();
1535         break;
1536       }
1537       default: llvm_unreachable("Unknown arg promotion!");
1538     }
1539
1540     // Now copy/store arg to correct locations.
1541     if (VA.isRegLoc() && !VA.needsCustom()) {
1542       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1543               VA.getLocReg())
1544       .addReg(Arg);
1545       RegArgs.push_back(VA.getLocReg());
1546     } else if (VA.needsCustom()) {
1547       // TODO: We need custom lowering for vector (v2f64) args.
1548       if (VA.getLocVT() != MVT::f64) return false;
1549
1550       CCValAssign &NextVA = ArgLocs[++i];
1551
1552       // TODO: Only handle register args for now.
1553       if(!(VA.isRegLoc() && NextVA.isRegLoc())) return false;
1554
1555       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1556                               TII.get(ARM::VMOVRRD), VA.getLocReg())
1557                       .addReg(NextVA.getLocReg(), RegState::Define)
1558                       .addReg(Arg));
1559       RegArgs.push_back(VA.getLocReg());
1560       RegArgs.push_back(NextVA.getLocReg());
1561     } else {
1562       assert(VA.isMemLoc());
1563       // Need to store on the stack.
1564       Address Addr;
1565       Addr.BaseType = Address::RegBase;
1566       Addr.Base.Reg = ARM::SP;
1567       Addr.Offset = VA.getLocMemOffset();
1568
1569       if (!ARMEmitStore(ArgVT, Arg, Addr)) return false;
1570     }
1571   }
1572   return true;
1573 }
1574
1575 bool ARMFastISel::FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1576                              const Instruction *I, CallingConv::ID CC,
1577                              unsigned &NumBytes) {
1578   // Issue CALLSEQ_END
1579   unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1580   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1581                           TII.get(AdjStackUp))
1582                   .addImm(NumBytes).addImm(0));
1583
1584   // Now the return value.
1585   if (RetVT != MVT::isVoid) {
1586     SmallVector<CCValAssign, 16> RVLocs;
1587     CCState CCInfo(CC, false, TM, RVLocs, *Context);
1588     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true));
1589
1590     // Copy all of the result registers out of their specified physreg.
1591     if (RVLocs.size() == 2 && RetVT == MVT::f64) {
1592       // For this move we copy into two registers and then move into the
1593       // double fp reg we want.
1594       EVT DestVT = RVLocs[0].getValVT();
1595       TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
1596       unsigned ResultReg = createResultReg(DstRC);
1597       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1598                               TII.get(ARM::VMOVDRR), ResultReg)
1599                       .addReg(RVLocs[0].getLocReg())
1600                       .addReg(RVLocs[1].getLocReg()));
1601
1602       UsedRegs.push_back(RVLocs[0].getLocReg());
1603       UsedRegs.push_back(RVLocs[1].getLocReg());
1604
1605       // Finally update the result.
1606       UpdateValueMap(I, ResultReg);
1607     } else {
1608       assert(RVLocs.size() == 1 &&"Can't handle non-double multi-reg retvals!");
1609       EVT CopyVT = RVLocs[0].getValVT();
1610       TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1611
1612       unsigned ResultReg = createResultReg(DstRC);
1613       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1614               ResultReg).addReg(RVLocs[0].getLocReg());
1615       UsedRegs.push_back(RVLocs[0].getLocReg());
1616
1617       // Finally update the result.
1618       UpdateValueMap(I, ResultReg);
1619     }
1620   }
1621
1622   return true;
1623 }
1624
1625 bool ARMFastISel::SelectRet(const Instruction *I) {
1626   const ReturnInst *Ret = cast<ReturnInst>(I);
1627   const Function &F = *I->getParent()->getParent();
1628
1629   if (!FuncInfo.CanLowerReturn)
1630     return false;
1631
1632   if (F.isVarArg())
1633     return false;
1634
1635   CallingConv::ID CC = F.getCallingConv();
1636   if (Ret->getNumOperands() > 0) {
1637     SmallVector<ISD::OutputArg, 4> Outs;
1638     GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
1639                   Outs, TLI);
1640
1641     // Analyze operands of the call, assigning locations to each operand.
1642     SmallVector<CCValAssign, 16> ValLocs;
1643     CCState CCInfo(CC, F.isVarArg(), TM, ValLocs, I->getContext());
1644     CCInfo.AnalyzeReturn(Outs, CCAssignFnForCall(CC, true /* is Ret */));
1645
1646     const Value *RV = Ret->getOperand(0);
1647     unsigned Reg = getRegForValue(RV);
1648     if (Reg == 0)
1649       return false;
1650
1651     // Only handle a single return value for now.
1652     if (ValLocs.size() != 1)
1653       return false;
1654
1655     CCValAssign &VA = ValLocs[0];
1656
1657     // Don't bother handling odd stuff for now.
1658     if (VA.getLocInfo() != CCValAssign::Full)
1659       return false;
1660     // Only handle register returns for now.
1661     if (!VA.isRegLoc())
1662       return false;
1663     // TODO: For now, don't try to handle cases where getLocInfo()
1664     // says Full but the types don't match.
1665     if (TLI.getValueType(RV->getType()) != VA.getValVT())
1666       return false;
1667
1668     // Make the copy.
1669     unsigned SrcReg = Reg + VA.getValNo();
1670     unsigned DstReg = VA.getLocReg();
1671     const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
1672     // Avoid a cross-class copy. This is very unlikely.
1673     if (!SrcRC->contains(DstReg))
1674       return false;
1675     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1676             DstReg).addReg(SrcReg);
1677
1678     // Mark the register as live out of the function.
1679     MRI.addLiveOut(VA.getLocReg());
1680   }
1681
1682   unsigned RetOpc = isThumb ? ARM::tBX_RET : ARM::BX_RET;
1683   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1684                           TII.get(RetOpc)));
1685   return true;
1686 }
1687
1688 unsigned ARMFastISel::ARMSelectCallOp(const GlobalValue *GV) {
1689
1690   // Darwin needs the r9 versions of the opcodes.
1691   bool isDarwin = Subtarget->isTargetDarwin();
1692   if (isThumb) {
1693     return isDarwin ? ARM::tBLr9 : ARM::tBL;
1694   } else  {
1695     return isDarwin ? ARM::BLr9 : ARM::BL;
1696   }
1697 }
1698
1699 // A quick function that will emit a call for a named libcall in F with the
1700 // vector of passed arguments for the Instruction in I. We can assume that we
1701 // can emit a call for any libcall we can produce. This is an abridged version
1702 // of the full call infrastructure since we won't need to worry about things
1703 // like computed function pointers or strange arguments at call sites.
1704 // TODO: Try to unify this and the normal call bits for ARM, then try to unify
1705 // with X86.
1706 bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
1707   CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
1708
1709   // Handle *simple* calls for now.
1710   const Type *RetTy = I->getType();
1711   MVT RetVT;
1712   if (RetTy->isVoidTy())
1713     RetVT = MVT::isVoid;
1714   else if (!isTypeLegal(RetTy, RetVT))
1715     return false;
1716
1717   // For now we're using BLX etc on the assumption that we have v5t ops.
1718   if (!Subtarget->hasV5TOps()) return false;
1719
1720   // TODO: For now if we have long calls specified we don't handle the call.
1721   if (EnableARMLongCalls) return false;
1722
1723   // Set up the argument vectors.
1724   SmallVector<Value*, 8> Args;
1725   SmallVector<unsigned, 8> ArgRegs;
1726   SmallVector<MVT, 8> ArgVTs;
1727   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1728   Args.reserve(I->getNumOperands());
1729   ArgRegs.reserve(I->getNumOperands());
1730   ArgVTs.reserve(I->getNumOperands());
1731   ArgFlags.reserve(I->getNumOperands());
1732   for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1733     Value *Op = I->getOperand(i);
1734     unsigned Arg = getRegForValue(Op);
1735     if (Arg == 0) return false;
1736
1737     const Type *ArgTy = Op->getType();
1738     MVT ArgVT;
1739     if (!isTypeLegal(ArgTy, ArgVT)) return false;
1740
1741     ISD::ArgFlagsTy Flags;
1742     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1743     Flags.setOrigAlign(OriginalAlignment);
1744
1745     Args.push_back(Op);
1746     ArgRegs.push_back(Arg);
1747     ArgVTs.push_back(ArgVT);
1748     ArgFlags.push_back(Flags);
1749   }
1750
1751   // Handle the arguments now that we've gotten them.
1752   SmallVector<unsigned, 4> RegArgs;
1753   unsigned NumBytes;
1754   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1755     return false;
1756
1757   // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1758   // TODO: Turn this into the table of arm call ops.
1759   MachineInstrBuilder MIB;
1760   unsigned CallOpc = ARMSelectCallOp(NULL);
1761   if(isThumb)
1762     // Explicitly adding the predicate here.
1763     MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1764                          TII.get(CallOpc)))
1765                          .addExternalSymbol(TLI.getLibcallName(Call));
1766   else
1767     // Explicitly adding the predicate here.
1768     MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1769                          TII.get(CallOpc))
1770           .addExternalSymbol(TLI.getLibcallName(Call)));
1771
1772   // Add implicit physical register uses to the call.
1773   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1774     MIB.addReg(RegArgs[i]);
1775
1776   // Finish off the call including any return values.
1777   SmallVector<unsigned, 4> UsedRegs;
1778   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1779
1780   // Set all unused physreg defs as dead.
1781   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1782
1783   return true;
1784 }
1785
1786 bool ARMFastISel::SelectCall(const Instruction *I) {
1787   const CallInst *CI = cast<CallInst>(I);
1788   const Value *Callee = CI->getCalledValue();
1789
1790   // Can't handle inline asm or worry about intrinsics yet.
1791   if (isa<InlineAsm>(Callee) || isa<IntrinsicInst>(CI)) return false;
1792
1793   // Only handle global variable Callees that are direct calls.
1794   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1795   if (!GV || Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel()))
1796     return false;
1797
1798   // Check the calling convention.
1799   ImmutableCallSite CS(CI);
1800   CallingConv::ID CC = CS.getCallingConv();
1801
1802   // TODO: Avoid some calling conventions?
1803
1804   // Let SDISel handle vararg functions.
1805   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1806   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1807   if (FTy->isVarArg())
1808     return false;
1809
1810   // Handle *simple* calls for now.
1811   const Type *RetTy = I->getType();
1812   MVT RetVT;
1813   if (RetTy->isVoidTy())
1814     RetVT = MVT::isVoid;
1815   else if (!isTypeLegal(RetTy, RetVT))
1816     return false;
1817
1818   // For now we're using BLX etc on the assumption that we have v5t ops.
1819   // TODO: Maybe?
1820   if (!Subtarget->hasV5TOps()) return false;
1821
1822   // TODO: For now if we have long calls specified we don't handle the call.
1823   if (EnableARMLongCalls) return false;
1824   
1825   // Set up the argument vectors.
1826   SmallVector<Value*, 8> Args;
1827   SmallVector<unsigned, 8> ArgRegs;
1828   SmallVector<MVT, 8> ArgVTs;
1829   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1830   Args.reserve(CS.arg_size());
1831   ArgRegs.reserve(CS.arg_size());
1832   ArgVTs.reserve(CS.arg_size());
1833   ArgFlags.reserve(CS.arg_size());
1834   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1835        i != e; ++i) {
1836     unsigned Arg = getRegForValue(*i);
1837
1838     if (Arg == 0)
1839       return false;
1840     ISD::ArgFlagsTy Flags;
1841     unsigned AttrInd = i - CS.arg_begin() + 1;
1842     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1843       Flags.setSExt();
1844     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1845       Flags.setZExt();
1846
1847          // FIXME: Only handle *easy* calls for now.
1848     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1849         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1850         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1851         CS.paramHasAttr(AttrInd, Attribute::ByVal))
1852       return false;
1853
1854     const Type *ArgTy = (*i)->getType();
1855     MVT ArgVT;
1856     if (!isTypeLegal(ArgTy, ArgVT))
1857       return false;
1858     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1859     Flags.setOrigAlign(OriginalAlignment);
1860
1861     Args.push_back(*i);
1862     ArgRegs.push_back(Arg);
1863     ArgVTs.push_back(ArgVT);
1864     ArgFlags.push_back(Flags);
1865   }
1866
1867   // Handle the arguments now that we've gotten them.
1868   SmallVector<unsigned, 4> RegArgs;
1869   unsigned NumBytes;
1870   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1871     return false;
1872
1873   // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1874   // TODO: Turn this into the table of arm call ops.
1875   MachineInstrBuilder MIB;
1876   unsigned CallOpc = ARMSelectCallOp(GV);
1877   // Explicitly adding the predicate here.
1878   if(isThumb)
1879     // Explicitly adding the predicate here.
1880     MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1881                          TII.get(CallOpc)))
1882           .addGlobalAddress(GV, 0, 0);
1883   else
1884     // Explicitly adding the predicate here.
1885     MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1886                          TII.get(CallOpc))
1887           .addGlobalAddress(GV, 0, 0));
1888   
1889   // Add implicit physical register uses to the call.
1890   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1891     MIB.addReg(RegArgs[i]);
1892
1893   // Finish off the call including any return values.
1894   SmallVector<unsigned, 4> UsedRegs;
1895   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1896
1897   // Set all unused physreg defs as dead.
1898   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1899
1900   return true;
1901
1902 }
1903
1904 // TODO: SoftFP support.
1905 bool ARMFastISel::TargetSelectInstruction(const Instruction *I) {
1906
1907   switch (I->getOpcode()) {
1908     case Instruction::Load:
1909       return SelectLoad(I);
1910     case Instruction::Store:
1911       return SelectStore(I);
1912     case Instruction::Br:
1913       return SelectBranch(I);
1914     case Instruction::ICmp:
1915     case Instruction::FCmp:
1916       return SelectCmp(I);
1917     case Instruction::FPExt:
1918       return SelectFPExt(I);
1919     case Instruction::FPTrunc:
1920       return SelectFPTrunc(I);
1921     case Instruction::SIToFP:
1922       return SelectSIToFP(I);
1923     case Instruction::FPToSI:
1924       return SelectFPToSI(I);
1925     case Instruction::FAdd:
1926       return SelectBinaryOp(I, ISD::FADD);
1927     case Instruction::FSub:
1928       return SelectBinaryOp(I, ISD::FSUB);
1929     case Instruction::FMul:
1930       return SelectBinaryOp(I, ISD::FMUL);
1931     case Instruction::SDiv:
1932       return SelectSDiv(I);
1933     case Instruction::SRem:
1934       return SelectSRem(I);
1935     case Instruction::Call:
1936       return SelectCall(I);
1937     case Instruction::Select:
1938       return SelectSelect(I);
1939     case Instruction::Ret:
1940       return SelectRet(I);
1941     default: break;
1942   }
1943   return false;
1944 }
1945
1946 namespace llvm {
1947   llvm::FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo) {
1948     // Completely untested on non-darwin.
1949     const TargetMachine &TM = funcInfo.MF->getTarget();
1950
1951     // Darwin and thumb1 only for now.
1952     const ARMSubtarget *Subtarget = &TM.getSubtarget<ARMSubtarget>();
1953     if (Subtarget->isTargetDarwin() && !Subtarget->isThumb1Only() &&
1954         !DisableARMFastISel)
1955       return new ARMFastISel(funcInfo);
1956     return 0;
1957   }
1958 }