Fix the store part of this as well. Fixes smg2000.
[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/CodeGen/Analysis.h"
30 #include "llvm/CodeGen/FastISel.h"
31 #include "llvm/CodeGen/FunctionLoweringInfo.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineConstantPool.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/Support/CallSite.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/GetElementPtrTypeIterator.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetOptions.h"
46 using namespace llvm;
47
48 static cl::opt<bool>
49 EnableARMFastISel("arm-fast-isel",
50                   cl::desc("Turn on experimental ARM fast-isel support"),
51                   cl::init(false), cl::Hidden);
52
53 namespace {
54
55 class ARMFastISel : public FastISel {
56
57   /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
58   /// make the right decision when generating code for different targets.
59   const ARMSubtarget *Subtarget;
60   const TargetMachine &TM;
61   const TargetInstrInfo &TII;
62   const TargetLowering &TLI;
63   ARMFunctionInfo *AFI;
64
65   // Convenience variables to avoid some queries.
66   bool isThumb;
67   LLVMContext *Context;
68
69   public:
70     explicit ARMFastISel(FunctionLoweringInfo &funcInfo)
71     : FastISel(funcInfo),
72       TM(funcInfo.MF->getTarget()),
73       TII(*TM.getInstrInfo()),
74       TLI(*TM.getTargetLowering()) {
75       Subtarget = &TM.getSubtarget<ARMSubtarget>();
76       AFI = funcInfo.MF->getInfo<ARMFunctionInfo>();
77       isThumb = AFI->isThumbFunction();
78       Context = &funcInfo.Fn->getContext();
79     }
80
81     // Code from FastISel.cpp.
82     virtual unsigned FastEmitInst_(unsigned MachineInstOpcode,
83                                    const TargetRegisterClass *RC);
84     virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
85                                     const TargetRegisterClass *RC,
86                                     unsigned Op0, bool Op0IsKill);
87     virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
88                                      const TargetRegisterClass *RC,
89                                      unsigned Op0, bool Op0IsKill,
90                                      unsigned Op1, bool Op1IsKill);
91     virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
92                                      const TargetRegisterClass *RC,
93                                      unsigned Op0, bool Op0IsKill,
94                                      uint64_t Imm);
95     virtual unsigned FastEmitInst_rf(unsigned MachineInstOpcode,
96                                      const TargetRegisterClass *RC,
97                                      unsigned Op0, bool Op0IsKill,
98                                      const ConstantFP *FPImm);
99     virtual unsigned FastEmitInst_i(unsigned MachineInstOpcode,
100                                     const TargetRegisterClass *RC,
101                                     uint64_t Imm);
102     virtual unsigned FastEmitInst_rri(unsigned MachineInstOpcode,
103                                       const TargetRegisterClass *RC,
104                                       unsigned Op0, bool Op0IsKill,
105                                       unsigned Op1, bool Op1IsKill,
106                                       uint64_t Imm);
107     virtual unsigned FastEmitInst_extractsubreg(MVT RetVT,
108                                                 unsigned Op0, bool Op0IsKill,
109                                                 uint32_t Idx);
110
111     // Backend specific FastISel code.
112     virtual bool TargetSelectInstruction(const Instruction *I);
113     virtual unsigned TargetMaterializeConstant(const Constant *C);
114     virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
115
116   #include "ARMGenFastISel.inc"
117
118     // Instruction selection routines.
119   private:
120     virtual bool SelectLoad(const Instruction *I);
121     virtual bool SelectStore(const Instruction *I);
122     virtual bool SelectBranch(const Instruction *I);
123     virtual bool SelectCmp(const Instruction *I);
124     virtual bool SelectFPExt(const Instruction *I);
125     virtual bool SelectFPTrunc(const Instruction *I);
126     virtual bool SelectBinaryOp(const Instruction *I, unsigned ISDOpcode);
127     virtual bool SelectSIToFP(const Instruction *I);
128     virtual bool SelectFPToSI(const Instruction *I);
129     virtual bool SelectSDiv(const Instruction *I);
130     virtual bool SelectCall(const Instruction *I);
131
132     // Utility routines.
133   private:
134     bool isTypeLegal(const Type *Ty, EVT &VT);
135     bool isLoadTypeLegal(const Type *Ty, EVT &VT);
136     bool ARMEmitLoad(EVT VT, unsigned &ResultReg, unsigned Reg, int Offset);
137     bool ARMEmitStore(EVT VT, unsigned SrcReg, unsigned Reg, int Offset);
138     bool ARMLoadAlloca(const Instruction *I, EVT VT);
139     bool ARMStoreAlloca(const Instruction *I, unsigned SrcReg, EVT VT);
140     bool ARMComputeRegOffset(const Value *Obj, unsigned &Reg, int &Offset);
141     unsigned ARMMaterializeFP(const ConstantFP *CFP, EVT VT);
142     unsigned ARMMaterializeInt(const Constant *C, EVT VT);
143     unsigned ARMMaterializeGV(const GlobalValue *GV, EVT VT);
144     unsigned ARMMoveToFPReg(EVT VT, unsigned SrcReg);
145     unsigned ARMMoveToIntReg(EVT VT, unsigned SrcReg);
146
147     // Call handling routines.
148   private:
149     CCAssignFn *CCAssignFnForCall(CallingConv::ID CC, bool Return);
150     bool ProcessCallArgs(SmallVectorImpl<Value*> &Args, 
151                          SmallVectorImpl<unsigned> &ArgRegs,
152                          SmallVectorImpl<EVT> &ArgVTs,
153                          SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
154                          SmallVectorImpl<unsigned> &RegArgs,
155                          CallingConv::ID CC,
156                          unsigned &NumBytes);
157     bool FinishCall(EVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
158                     const Instruction *I, CallingConv::ID CC,
159                     unsigned &NumBytes);
160     bool ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call);
161
162     // OptionalDef handling routines.
163   private:
164     bool DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR);
165     const MachineInstrBuilder &AddOptionalDefs(const MachineInstrBuilder &MIB);
166 };
167
168 } // end anonymous namespace
169
170 #include "ARMGenCallingConv.inc"
171
172 // DefinesOptionalPredicate - This is different from DefinesPredicate in that
173 // we don't care about implicit defs here, just places we'll need to add a
174 // default CCReg argument. Sets CPSR if we're setting CPSR instead of CCR.
175 bool ARMFastISel::DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR) {
176   const TargetInstrDesc &TID = MI->getDesc();
177   if (!TID.hasOptionalDef())
178     return false;
179
180   // Look to see if our OptionalDef is defining CPSR or CCR.
181   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
182     const MachineOperand &MO = MI->getOperand(i);
183     if (!MO.isReg() || !MO.isDef()) continue;
184     if (MO.getReg() == ARM::CPSR)
185       *CPSR = true;
186   }
187   return true;
188 }
189
190 // If the machine is predicable go ahead and add the predicate operands, if
191 // it needs default CC operands add those.
192 const MachineInstrBuilder &
193 ARMFastISel::AddOptionalDefs(const MachineInstrBuilder &MIB) {
194   MachineInstr *MI = &*MIB;
195
196   // Do we use a predicate?
197   if (TII.isPredicable(MI))
198     AddDefaultPred(MIB);
199
200   // Do we optionally set a predicate?  Preds is size > 0 iff the predicate
201   // defines CPSR. All other OptionalDefines in ARM are the CCR register.
202   bool CPSR = false;
203   if (DefinesOptionalPredicate(MI, &CPSR)) {
204     if (CPSR)
205       AddDefaultT1CC(MIB);
206     else
207       AddDefaultCC(MIB);
208   }
209   return MIB;
210 }
211
212 unsigned ARMFastISel::FastEmitInst_(unsigned MachineInstOpcode,
213                                     const TargetRegisterClass* RC) {
214   unsigned ResultReg = createResultReg(RC);
215   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
216
217   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg));
218   return ResultReg;
219 }
220
221 unsigned ARMFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
222                                      const TargetRegisterClass *RC,
223                                      unsigned Op0, bool Op0IsKill) {
224   unsigned ResultReg = createResultReg(RC);
225   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
226
227   if (II.getNumDefs() >= 1)
228     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
229                    .addReg(Op0, Op0IsKill * RegState::Kill));
230   else {
231     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
232                    .addReg(Op0, Op0IsKill * RegState::Kill));
233     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
234                    TII.get(TargetOpcode::COPY), ResultReg)
235                    .addReg(II.ImplicitDefs[0]));
236   }
237   return ResultReg;
238 }
239
240 unsigned ARMFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
241                                       const TargetRegisterClass *RC,
242                                       unsigned Op0, bool Op0IsKill,
243                                       unsigned Op1, bool Op1IsKill) {
244   unsigned ResultReg = createResultReg(RC);
245   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
246
247   if (II.getNumDefs() >= 1)
248     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
249                    .addReg(Op0, Op0IsKill * RegState::Kill)
250                    .addReg(Op1, Op1IsKill * RegState::Kill));
251   else {
252     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
253                    .addReg(Op0, Op0IsKill * RegState::Kill)
254                    .addReg(Op1, Op1IsKill * RegState::Kill));
255     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
256                            TII.get(TargetOpcode::COPY), ResultReg)
257                    .addReg(II.ImplicitDefs[0]));
258   }
259   return ResultReg;
260 }
261
262 unsigned ARMFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
263                                       const TargetRegisterClass *RC,
264                                       unsigned Op0, bool Op0IsKill,
265                                       uint64_t Imm) {
266   unsigned ResultReg = createResultReg(RC);
267   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
268
269   if (II.getNumDefs() >= 1)
270     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
271                    .addReg(Op0, Op0IsKill * RegState::Kill)
272                    .addImm(Imm));
273   else {
274     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
275                    .addReg(Op0, Op0IsKill * RegState::Kill)
276                    .addImm(Imm));
277     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
278                            TII.get(TargetOpcode::COPY), ResultReg)
279                    .addReg(II.ImplicitDefs[0]));
280   }
281   return ResultReg;
282 }
283
284 unsigned ARMFastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
285                                       const TargetRegisterClass *RC,
286                                       unsigned Op0, bool Op0IsKill,
287                                       const ConstantFP *FPImm) {
288   unsigned ResultReg = createResultReg(RC);
289   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
290
291   if (II.getNumDefs() >= 1)
292     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
293                    .addReg(Op0, Op0IsKill * RegState::Kill)
294                    .addFPImm(FPImm));
295   else {
296     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
297                    .addReg(Op0, Op0IsKill * RegState::Kill)
298                    .addFPImm(FPImm));
299     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
300                            TII.get(TargetOpcode::COPY), ResultReg)
301                    .addReg(II.ImplicitDefs[0]));
302   }
303   return ResultReg;
304 }
305
306 unsigned ARMFastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
307                                        const TargetRegisterClass *RC,
308                                        unsigned Op0, bool Op0IsKill,
309                                        unsigned Op1, bool Op1IsKill,
310                                        uint64_t Imm) {
311   unsigned ResultReg = createResultReg(RC);
312   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
313
314   if (II.getNumDefs() >= 1)
315     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
316                    .addReg(Op0, Op0IsKill * RegState::Kill)
317                    .addReg(Op1, Op1IsKill * RegState::Kill)
318                    .addImm(Imm));
319   else {
320     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
321                    .addReg(Op0, Op0IsKill * RegState::Kill)
322                    .addReg(Op1, Op1IsKill * RegState::Kill)
323                    .addImm(Imm));
324     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
325                            TII.get(TargetOpcode::COPY), ResultReg)
326                    .addReg(II.ImplicitDefs[0]));
327   }
328   return ResultReg;
329 }
330
331 unsigned ARMFastISel::FastEmitInst_i(unsigned MachineInstOpcode,
332                                      const TargetRegisterClass *RC,
333                                      uint64_t Imm) {
334   unsigned ResultReg = createResultReg(RC);
335   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
336
337   if (II.getNumDefs() >= 1)
338     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
339                    .addImm(Imm));
340   else {
341     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
342                    .addImm(Imm));
343     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
344                            TII.get(TargetOpcode::COPY), ResultReg)
345                    .addReg(II.ImplicitDefs[0]));
346   }
347   return ResultReg;
348 }
349
350 unsigned ARMFastISel::FastEmitInst_extractsubreg(MVT RetVT,
351                                                  unsigned Op0, bool Op0IsKill,
352                                                  uint32_t Idx) {
353   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
354   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
355          "Cannot yet extract from physregs");
356   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
357                          DL, TII.get(TargetOpcode::COPY), ResultReg)
358                  .addReg(Op0, getKillRegState(Op0IsKill), Idx));
359   return ResultReg;
360 }
361
362 // TODO: Don't worry about 64-bit now, but when this is fixed remove the
363 // checks from the various callers.
364 unsigned ARMFastISel::ARMMoveToFPReg(EVT VT, unsigned SrcReg) {
365   if (VT.getSimpleVT().SimpleTy == MVT::f64) return 0;
366   
367   unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
368   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
369                           TII.get(ARM::VMOVRS), MoveReg)
370                   .addReg(SrcReg));
371   return MoveReg;
372 }
373
374 unsigned ARMFastISel::ARMMoveToIntReg(EVT VT, unsigned SrcReg) {
375   if (VT.getSimpleVT().SimpleTy == MVT::i64) return 0;
376   
377   unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
378   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
379                           TII.get(ARM::VMOVSR), MoveReg)
380                   .addReg(SrcReg));
381   return MoveReg;
382 }
383
384 // For double width floating point we need to materialize two constants
385 // (the high and the low) into integer registers then use a move to get
386 // the combined constant into an FP reg.
387 unsigned ARMFastISel::ARMMaterializeFP(const ConstantFP *CFP, EVT VT) {
388   const APFloat Val = CFP->getValueAPF();
389   bool is64bit = VT.getSimpleVT().SimpleTy == MVT::f64;
390
391   // This checks to see if we can use VFP3 instructions to materialize
392   // a constant, otherwise we have to go through the constant pool.
393   if (TLI.isFPImmLegal(Val, VT)) {
394     unsigned Opc = is64bit ? ARM::FCONSTD : ARM::FCONSTS;
395     unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
396     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
397                             DestReg)
398                     .addFPImm(CFP));
399     return DestReg;
400   }
401   
402   // Require VFP2 for loading fp constants.
403   if (!Subtarget->hasVFP2()) return false;
404   
405   // MachineConstantPool wants an explicit alignment.
406   unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
407   if (Align == 0) {
408     // TODO: Figure out if this is correct.
409     Align = TD.getTypeAllocSize(CFP->getType());
410   }
411   unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
412   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
413   unsigned Opc = is64bit ? ARM::VLDRD : ARM::VLDRS;
414   
415   // The extra reg is for addrmode5.
416   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
417                           DestReg)
418                   .addConstantPoolIndex(Idx)
419                   .addReg(0));
420   return DestReg;
421 }
422
423 unsigned ARMFastISel::ARMMaterializeInt(const Constant *C, EVT VT) {
424   
425   // For now 32-bit only.
426   if (VT.getSimpleVT().SimpleTy != MVT::i32) return false;
427   
428   // MachineConstantPool wants an explicit alignment.
429   unsigned Align = TD.getPrefTypeAlignment(C->getType());
430   if (Align == 0) {
431     // TODO: Figure out if this is correct.
432     Align = TD.getTypeAllocSize(C->getType());
433   }
434   unsigned Idx = MCP.getConstantPoolIndex(C, Align);
435   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
436   
437   if (isThumb)
438     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
439                             TII.get(ARM::t2LDRpci), DestReg)
440                     .addConstantPoolIndex(Idx));
441   else
442     // The extra reg and immediate are for addrmode2.
443     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
444                             TII.get(ARM::LDRcp), DestReg)
445                     .addConstantPoolIndex(Idx)
446                     .addReg(0).addImm(0));
447
448   return DestReg;
449 }
450
451 unsigned ARMFastISel::ARMMaterializeGV(const GlobalValue *GV, EVT VT) {
452   // For now 32-bit only.
453   if (VT.getSimpleVT().SimpleTy != MVT::i32) return 0;
454   
455   Reloc::Model RelocM = TM.getRelocationModel();
456   
457   // TODO: No external globals for now.
458   if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) return 0;
459   
460   // TODO: Need more magic for ARM PIC.
461   if (!isThumb && (RelocM == Reloc::PIC_)) return 0;
462   
463   // MachineConstantPool wants an explicit alignment.
464   unsigned Align = TD.getPrefTypeAlignment(GV->getType());
465   if (Align == 0) {
466     // TODO: Figure out if this is correct.
467     Align = TD.getTypeAllocSize(GV->getType());
468   }
469   
470   // Grab index.
471   unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb() ? 4 : 8);
472   unsigned Id = AFI->createConstPoolEntryUId();
473   ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, Id,
474                                                        ARMCP::CPValue, PCAdj);
475   unsigned Idx = MCP.getConstantPoolIndex(CPV, Align);
476   
477   // Load value.
478   MachineInstrBuilder MIB;
479   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
480   if (isThumb) {
481     unsigned Opc = (RelocM != Reloc::PIC_) ? ARM::t2LDRpci : ARM::t2LDRpci_pic;
482     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
483           .addConstantPoolIndex(Idx);
484     if (RelocM == Reloc::PIC_)
485       MIB.addImm(Id);
486   } else {
487     // The extra reg and immediate are for addrmode2.
488     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::LDRcp),
489                   DestReg)
490           .addConstantPoolIndex(Idx)
491           .addReg(0).addImm(0);
492   }
493   AddOptionalDefs(MIB);
494   return DestReg;
495 }
496
497 unsigned ARMFastISel::TargetMaterializeConstant(const Constant *C) {
498   EVT VT = TLI.getValueType(C->getType(), true);
499
500   // Only handle simple types.
501   if (!VT.isSimple()) return 0;
502
503   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
504     return ARMMaterializeFP(CFP, VT);
505   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
506     return ARMMaterializeGV(GV, VT);
507   else if (isa<ConstantInt>(C))
508     return ARMMaterializeInt(C, VT);
509   
510   return 0;
511 }
512
513 unsigned ARMFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
514   // Don't handle dynamic allocas.
515   if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
516   
517   EVT VT;
518   if (!isTypeLegal(AI->getType(), VT)) return false;
519   
520   DenseMap<const AllocaInst*, int>::iterator SI =
521     FuncInfo.StaticAllocaMap.find(AI);
522
523   // This will get lowered later into the correct offsets and registers
524   // via rewriteXFrameIndex.
525   if (SI != FuncInfo.StaticAllocaMap.end()) {
526     TargetRegisterClass* RC = TLI.getRegClassFor(VT);
527     unsigned ResultReg = createResultReg(RC);
528     unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
529     AddOptionalDefs(BuildMI(*FuncInfo.MBB, *FuncInfo.InsertPt, DL,
530                             TII.get(Opc), ResultReg)
531                             .addFrameIndex(SI->second)
532                             .addImm(0));
533     return ResultReg;
534   }
535   
536   return 0;
537 }
538
539 bool ARMFastISel::isTypeLegal(const Type *Ty, EVT &VT) {
540   VT = TLI.getValueType(Ty, true);
541
542   // Only handle simple types.
543   if (VT == MVT::Other || !VT.isSimple()) return false;
544
545   // Handle all legal types, i.e. a register that will directly hold this
546   // value.
547   return TLI.isTypeLegal(VT);
548 }
549
550 bool ARMFastISel::isLoadTypeLegal(const Type *Ty, EVT &VT) {
551   if (isTypeLegal(Ty, VT)) return true;
552
553   // If this is a type than can be sign or zero-extended to a basic operation
554   // go ahead and accept it now.
555   if (VT == MVT::i8 || VT == MVT::i16)
556     return true;
557
558   return false;
559 }
560
561 // Computes the Reg+Offset to get to an object.
562 bool ARMFastISel::ARMComputeRegOffset(const Value *Obj, unsigned &Reg,
563                                       int &Offset) {
564   // Some boilerplate from the X86 FastISel.
565   const User *U = NULL;
566   unsigned Opcode = Instruction::UserOp1;
567   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
568     // Don't walk into other basic blocks; it's possible we haven't
569     // visited them yet, so the instructions may not yet be assigned
570     // virtual registers.
571     if (FuncInfo.MBBMap[I->getParent()] != FuncInfo.MBB)
572       return false;
573     Opcode = I->getOpcode();
574     U = I;
575   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
576     Opcode = C->getOpcode();
577     U = C;
578   }
579
580   if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
581     if (Ty->getAddressSpace() > 255)
582       // Fast instruction selection doesn't support the special
583       // address spaces.
584       return false;
585
586   switch (Opcode) {
587     default:
588     break;
589     case Instruction::Alloca: {
590       assert(false && "Alloca should have been handled earlier!");
591       return false;
592     }
593   }
594
595   // FIXME: Handle global variables.
596   if (const GlobalValue *GV = dyn_cast<GlobalValue>(Obj)) {
597     (void)GV;
598     return false;
599   }
600
601   // Try to get this in a register if nothing else has worked.
602   Reg = getRegForValue(Obj);
603   if (Reg == 0) return false;
604
605   // Since the offset may be too large for the load instruction
606   // get the reg+offset into a register.
607   // TODO: Verify the additions work, otherwise we'll need to add the
608   // offset instead of 0 to the instructions and do all sorts of operand
609   // munging.
610   // TODO: Optimize this somewhat.
611   if (Offset != 0) {
612     ARMCC::CondCodes Pred = ARMCC::AL;
613     unsigned PredReg = 0;
614
615     if (!isThumb)
616       emitARMRegPlusImmediate(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
617                               Reg, Reg, Offset, Pred, PredReg,
618                               static_cast<const ARMBaseInstrInfo&>(TII));
619     else {
620       assert(AFI->isThumb2Function());
621       emitT2RegPlusImmediate(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
622                              Reg, Reg, Offset, Pred, PredReg,
623                              static_cast<const ARMBaseInstrInfo&>(TII));
624     }
625   }
626   return true;
627 }
628
629 bool ARMFastISel::ARMLoadAlloca(const Instruction *I, EVT VT) {
630   Value *Op0 = I->getOperand(0);
631
632   // Promote load/store types.
633   if (VT == MVT::i8 || VT == MVT::i16) VT = MVT::i32;
634
635   // Verify it's an alloca.
636   if (const AllocaInst *AI = dyn_cast<AllocaInst>(Op0)) {
637     DenseMap<const AllocaInst*, int>::iterator SI =
638       FuncInfo.StaticAllocaMap.find(AI);
639
640     if (SI != FuncInfo.StaticAllocaMap.end()) {
641       TargetRegisterClass* RC = TLI.getRegClassFor(VT);
642       unsigned ResultReg = createResultReg(RC);
643       TII.loadRegFromStackSlot(*FuncInfo.MBB, *FuncInfo.InsertPt,
644                                ResultReg, SI->second, RC,
645                                TM.getRegisterInfo());
646       UpdateValueMap(I, ResultReg);
647       return true;
648     }
649   }
650   return false;
651 }
652
653 bool ARMFastISel::ARMEmitLoad(EVT VT, unsigned &ResultReg,
654                               unsigned Reg, int Offset) {
655
656   assert(VT.isSimple() && "Non-simple types are invalid here!");
657   unsigned Opc;
658   TargetRegisterClass *RC;
659   bool isFloat = false;
660   switch (VT.getSimpleVT().SimpleTy) {
661     default:
662       // This is mostly going to be Neon/vector support.
663       return false;
664     case MVT::i16:
665       Opc = isThumb ? ARM::t2LDRHi8 : ARM::LDRH;
666       RC = ARM::GPRRegisterClass;
667       VT = MVT::i32;
668       break;
669     case MVT::i8:
670       Opc = isThumb ? ARM::t2LDRBi8 : ARM::LDRB;
671       RC = ARM::GPRRegisterClass;
672       VT = MVT::i32;
673       break;
674     case MVT::i32:
675       Opc = isThumb ? ARM::t2LDRi8 : ARM::LDR;
676       RC = ARM::GPRRegisterClass;
677       break;
678     case MVT::f32:
679       Opc = ARM::VLDRS;
680       RC = TLI.getRegClassFor(VT);
681       isFloat = true;
682       break;
683     case MVT::f64:
684       Opc = ARM::VLDRD;
685       RC = TLI.getRegClassFor(VT);
686       isFloat = true;
687       break;
688   }
689
690   ResultReg = createResultReg(RC);
691
692   // For now with the additions above the offset should be zero - thus we
693   // can always fit into an i8.
694   assert(Offset == 0 && "Offset not zero!");
695   
696   // The thumb and floating point instructions both take 2 operands, ARM takes
697   // another register.
698   if (isFloat || isThumb)
699     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
700                             TII.get(Opc), ResultReg)
701                     .addReg(Reg).addImm(Offset));
702   else
703     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
704                             TII.get(Opc), ResultReg)
705                     .addReg(Reg).addReg(0).addImm(Offset));
706   return true;
707 }
708
709 bool ARMFastISel::SelectLoad(const Instruction *I) {
710   // Verify we have a legal type before going any further.
711   EVT VT;
712   if (!isLoadTypeLegal(I->getType(), VT))
713     return false;
714
715   // If we're an alloca we know we have a frame index and can emit the load
716   // directly in short order.
717   if (ARMLoadAlloca(I, VT))
718     return true;
719
720   // Our register and offset with innocuous defaults.
721   unsigned Reg = 0;
722   int Offset = 0;
723
724   // See if we can handle this as Reg + Offset
725   if (!ARMComputeRegOffset(I->getOperand(0), Reg, Offset))
726     return false;
727
728   unsigned ResultReg;
729   if (!ARMEmitLoad(VT, ResultReg, Reg, Offset /* 0 */)) return false;
730
731   UpdateValueMap(I, ResultReg);
732   return true;
733 }
734
735 bool ARMFastISel::ARMStoreAlloca(const Instruction *I, unsigned SrcReg, EVT VT){
736   Value *Op1 = I->getOperand(1);
737
738   // Promote load/store types.
739   if (VT == MVT::i8 || VT == MVT::i16) VT = MVT::i32;
740
741   // Verify it's an alloca.
742   if (const AllocaInst *AI = dyn_cast<AllocaInst>(Op1)) {
743     DenseMap<const AllocaInst*, int>::iterator SI =
744       FuncInfo.StaticAllocaMap.find(AI);
745
746     if (SI != FuncInfo.StaticAllocaMap.end()) {
747       TargetRegisterClass* RC = TLI.getRegClassFor(VT);
748       assert(SrcReg != 0 && "Nothing to store!");
749       TII.storeRegToStackSlot(*FuncInfo.MBB, *FuncInfo.InsertPt,
750                               SrcReg, true /*isKill*/, SI->second, RC,
751                               TM.getRegisterInfo());
752       return true;
753     }
754   }
755   return false;
756 }
757
758 bool ARMFastISel::ARMEmitStore(EVT VT, unsigned SrcReg,
759                                unsigned DstReg, int Offset) {
760   unsigned StrOpc;
761   bool isFloat = false;
762   switch (VT.getSimpleVT().SimpleTy) {
763     default: return false;
764     case MVT::i1:
765     case MVT::i8: StrOpc = isThumb ? ARM::t2STRBi8 : ARM::STRB; break;
766     case MVT::i16: StrOpc = isThumb ? ARM::t2STRHi8 : ARM::STRH; break;
767     case MVT::i32: StrOpc = isThumb ? ARM::t2STRi8 : ARM::STR; break;
768     case MVT::f32:
769       if (!Subtarget->hasVFP2()) return false;
770       StrOpc = ARM::VSTRS;
771       isFloat = true;
772       break;
773     case MVT::f64:
774       if (!Subtarget->hasVFP2()) return false;
775       StrOpc = ARM::VSTRD;
776       isFloat = true;
777       break;
778   }
779
780   // The thumb addressing mode has operands swapped from the arm addressing
781   // mode, the floating point one only has two operands.
782   if (isFloat || isThumb)
783     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
784                             TII.get(StrOpc))
785                     .addReg(SrcReg).addReg(DstReg).addImm(Offset));
786   else
787     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
788                             TII.get(StrOpc))
789                     .addReg(SrcReg).addReg(DstReg).addReg(0).addImm(Offset));
790
791   return true;
792 }
793
794 bool ARMFastISel::SelectStore(const Instruction *I) {
795   Value *Op0 = I->getOperand(0);
796   unsigned SrcReg = 0;
797
798   // Yay type legalization
799   EVT VT;
800   if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
801     return false;
802
803   // Get the value to be stored into a register.
804   SrcReg = getRegForValue(Op0);
805   if (SrcReg == 0)
806     return false;
807
808   // If we're an alloca we know we have a frame index and can emit the store
809   // quickly.
810   if (ARMStoreAlloca(I, SrcReg, VT))
811     return true;
812
813   // Our register and offset with innocuous defaults.
814   unsigned Reg = 0;
815   int Offset = 0;
816
817   // See if we can handle this as Reg + Offset
818   if (!ARMComputeRegOffset(I->getOperand(1), Reg, Offset))
819     return false;
820
821   if (!ARMEmitStore(VT, SrcReg, Reg, Offset /* 0 */)) return false;
822
823   return true;
824 }
825
826 static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
827   switch (Pred) {
828     // Needs two compares...
829     case CmpInst::FCMP_ONE:
830     case CmpInst::FCMP_UEQ:    
831     default:
832       assert(false && "Unhandled CmpInst::Predicate!");
833       return ARMCC::AL;
834     case CmpInst::ICMP_EQ:
835     case CmpInst::FCMP_OEQ:
836       return ARMCC::EQ;
837     case CmpInst::ICMP_SGT:
838     case CmpInst::FCMP_OGT:
839       return ARMCC::GT;
840     case CmpInst::ICMP_SGE:
841     case CmpInst::FCMP_OGE:
842       return ARMCC::GE;
843     case CmpInst::ICMP_UGT:
844     case CmpInst::FCMP_UGT:
845       return ARMCC::HI;
846     case CmpInst::FCMP_OLT:
847       return ARMCC::MI;
848     case CmpInst::ICMP_ULE:
849     case CmpInst::FCMP_OLE:
850       return ARMCC::LS;
851     case CmpInst::FCMP_ORD:
852       return ARMCC::VC;
853     case CmpInst::FCMP_UNO:
854       return ARMCC::VS;
855     case CmpInst::FCMP_UGE:
856       return ARMCC::PL;
857     case CmpInst::ICMP_SLT:
858     case CmpInst::FCMP_ULT:
859       return ARMCC::LT;  
860     case CmpInst::ICMP_SLE:
861     case CmpInst::FCMP_ULE:
862       return ARMCC::LE;
863     case CmpInst::FCMP_UNE:
864     case CmpInst::ICMP_NE:
865       return ARMCC::NE;
866     case CmpInst::ICMP_UGE:
867       return ARMCC::HS;
868     case CmpInst::ICMP_ULT:
869       return ARMCC::LO;
870   }
871 }
872
873 bool ARMFastISel::SelectBranch(const Instruction *I) {
874   const BranchInst *BI = cast<BranchInst>(I);
875   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
876   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
877
878   // Simple branch support.
879   // TODO: Try to avoid the re-computation in some places.
880   unsigned CondReg = getRegForValue(BI->getCondition());
881   if (CondReg == 0) return false;
882
883   // Re-set the flags just in case.
884   unsigned CmpOpc = isThumb ? ARM::t2CMPri : ARM::CMPri;
885   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
886                   .addReg(CondReg).addImm(1));
887   
888   unsigned BrOpc = isThumb ? ARM::t2Bcc : ARM::Bcc;
889   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
890                   .addMBB(TBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
891   FastEmitBranch(FBB, DL);
892   FuncInfo.MBB->addSuccessor(TBB);
893   return true;  
894 }
895
896 bool ARMFastISel::SelectCmp(const Instruction *I) {
897   const CmpInst *CI = cast<CmpInst>(I);
898
899   EVT VT;
900   const Type *Ty = CI->getOperand(0)->getType();
901   if (!isTypeLegal(Ty, VT))
902     return false;
903
904   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
905   if (isFloat && !Subtarget->hasVFP2())
906     return false;
907
908   unsigned CmpOpc;
909   unsigned CondReg;
910   switch (VT.getSimpleVT().SimpleTy) {
911     default: return false;
912     // TODO: Verify compares.
913     case MVT::f32:
914       CmpOpc = ARM::VCMPES;
915       CondReg = ARM::FPSCR;
916       break;
917     case MVT::f64:
918       CmpOpc = ARM::VCMPED;
919       CondReg = ARM::FPSCR;
920       break;
921     case MVT::i32:
922       CmpOpc = isThumb ? ARM::t2CMPrr : ARM::CMPrr;
923       CondReg = ARM::CPSR;
924       break;
925   }
926
927   // Get the compare predicate.
928   ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
929     
930   // We may not handle every CC for now.
931   if (ARMPred == ARMCC::AL) return false;
932
933   unsigned Arg1 = getRegForValue(CI->getOperand(0));
934   if (Arg1 == 0) return false;
935
936   unsigned Arg2 = getRegForValue(CI->getOperand(1));
937   if (Arg2 == 0) return false;
938
939   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
940                   .addReg(Arg1).addReg(Arg2));
941
942   // For floating point we need to move the result to a comparison register
943   // that we can then use for branches.
944   if (isFloat)
945     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
946                             TII.get(ARM::FMSTAT)));
947
948   // Now set a register based on the comparison. Explicitly set the predicates
949   // here.
950   unsigned MovCCOpc = isThumb ? ARM::t2MOVCCi : ARM::MOVCCi;
951   TargetRegisterClass *RC = isThumb ? ARM::rGPRRegisterClass 
952                                     : ARM::GPRRegisterClass;
953   unsigned DestReg = createResultReg(RC);
954   Constant *Zero 
955     = ConstantInt::get(Type::getInt32Ty(*Context), 0);
956   unsigned ZeroReg = TargetMaterializeConstant(Zero);
957   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), DestReg)
958           .addReg(ZeroReg).addImm(1)
959           .addImm(ARMPred).addReg(CondReg);
960
961   UpdateValueMap(I, DestReg);
962   return true;
963 }
964
965 bool ARMFastISel::SelectFPExt(const Instruction *I) {
966   // Make sure we have VFP and that we're extending float to double.
967   if (!Subtarget->hasVFP2()) return false;
968
969   Value *V = I->getOperand(0);
970   if (!I->getType()->isDoubleTy() ||
971       !V->getType()->isFloatTy()) return false;
972
973   unsigned Op = getRegForValue(V);
974   if (Op == 0) return false;
975
976   unsigned Result = createResultReg(ARM::DPRRegisterClass);
977   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
978                           TII.get(ARM::VCVTDS), Result)
979                   .addReg(Op));
980   UpdateValueMap(I, Result);
981   return true;
982 }
983
984 bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
985   // Make sure we have VFP and that we're truncating double to float.
986   if (!Subtarget->hasVFP2()) return false;
987
988   Value *V = I->getOperand(0);
989   if (!(I->getType()->isFloatTy() &&
990         V->getType()->isDoubleTy())) return false;
991
992   unsigned Op = getRegForValue(V);
993   if (Op == 0) return false;
994
995   unsigned Result = createResultReg(ARM::SPRRegisterClass);
996   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
997                           TII.get(ARM::VCVTSD), Result)
998                   .addReg(Op));
999   UpdateValueMap(I, Result);
1000   return true;
1001 }
1002
1003 bool ARMFastISel::SelectSIToFP(const Instruction *I) {
1004   // Make sure we have VFP.
1005   if (!Subtarget->hasVFP2()) return false;
1006   
1007   EVT DstVT;
1008   const Type *Ty = I->getType();
1009   if (!isTypeLegal(Ty, DstVT))
1010     return false;
1011   
1012   unsigned Op = getRegForValue(I->getOperand(0));
1013   if (Op == 0) return false;
1014   
1015   // The conversion routine works on fp-reg to fp-reg and the operand above
1016   // was an integer, move it to the fp registers if possible.
1017   unsigned FP = ARMMoveToFPReg(MVT::f32, Op);
1018   if (FP == 0) return false;
1019   
1020   unsigned Opc;
1021   if (Ty->isFloatTy()) Opc = ARM::VSITOS;
1022   else if (Ty->isDoubleTy()) Opc = ARM::VSITOD;
1023   else return 0;
1024   
1025   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1026   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1027                           ResultReg)
1028                   .addReg(FP));
1029   UpdateValueMap(I, ResultReg);
1030   return true;
1031 }
1032
1033 bool ARMFastISel::SelectFPToSI(const Instruction *I) {
1034   // Make sure we have VFP.
1035   if (!Subtarget->hasVFP2()) return false;
1036   
1037   EVT DstVT;
1038   const Type *RetTy = I->getType();
1039   if (!isTypeLegal(RetTy, DstVT))
1040     return false;
1041   
1042   unsigned Op = getRegForValue(I->getOperand(0));
1043   if (Op == 0) return false;
1044   
1045   unsigned Opc;
1046   const Type *OpTy = I->getOperand(0)->getType();
1047   if (OpTy->isFloatTy()) Opc = ARM::VTOSIZS;
1048   else if (OpTy->isDoubleTy()) Opc = ARM::VTOSIZD;
1049   else return 0;
1050   
1051   // f64->s32 or f32->s32 both need an intermediate f32 reg.
1052   unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1053   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1054                           ResultReg)
1055                   .addReg(Op));
1056         
1057   // This result needs to be in an integer register, but the conversion only
1058   // takes place in fp-regs.
1059   unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1060   if (IntReg == 0) return false;
1061   
1062   UpdateValueMap(I, IntReg);
1063   return true;
1064 }
1065
1066 bool ARMFastISel::SelectSDiv(const Instruction *I) {
1067   EVT VT;
1068   const Type *Ty = I->getType();
1069   if (!isTypeLegal(Ty, VT))
1070     return false;
1071
1072   // If we have integer div support we should have selected this automagically.
1073   // In case we have a real miss go ahead and return false and we'll pick
1074   // it up later.
1075   if (Subtarget->hasDivide()) return false;  
1076   
1077   // Otherwise emit a libcall.
1078   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1079   if (VT == MVT::i16)
1080     LC = RTLIB::SDIV_I16;
1081   else if (VT == MVT::i32)
1082     LC = RTLIB::SDIV_I32;
1083   else if (VT == MVT::i64)
1084     LC = RTLIB::SDIV_I64;
1085   else if (VT == MVT::i128)
1086     LC = RTLIB::SDIV_I128;
1087   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1088     
1089   return ARMEmitLibcall(I, LC);
1090 }
1091
1092 bool ARMFastISel::SelectBinaryOp(const Instruction *I, unsigned ISDOpcode) {
1093   EVT VT  = TLI.getValueType(I->getType(), true);
1094
1095   // We can get here in the case when we want to use NEON for our fp
1096   // operations, but can't figure out how to. Just use the vfp instructions
1097   // if we have them.
1098   // FIXME: It'd be nice to use NEON instructions.
1099   const Type *Ty = I->getType();
1100   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1101   if (isFloat && !Subtarget->hasVFP2())
1102     return false;
1103
1104   unsigned Op1 = getRegForValue(I->getOperand(0));
1105   if (Op1 == 0) return false;
1106
1107   unsigned Op2 = getRegForValue(I->getOperand(1));
1108   if (Op2 == 0) return false;
1109
1110   unsigned Opc;
1111   bool is64bit = VT.getSimpleVT().SimpleTy == MVT::f64 ||
1112                  VT.getSimpleVT().SimpleTy == MVT::i64;
1113   switch (ISDOpcode) {
1114     default: return false;
1115     case ISD::FADD:
1116       Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1117       break;
1118     case ISD::FSUB:
1119       Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1120       break;
1121     case ISD::FMUL:
1122       Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1123       break;
1124   }
1125   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1126   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1127                           TII.get(Opc), ResultReg)
1128                   .addReg(Op1).addReg(Op2));
1129   UpdateValueMap(I, ResultReg);
1130   return true;
1131 }
1132
1133 // Call Handling Code
1134
1135 // This is largely taken directly from CCAssignFnForNode - we don't support
1136 // varargs in FastISel so that part has been removed.
1137 // TODO: We may not support all of this.
1138 CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC, bool Return) {
1139   switch (CC) {
1140   default:
1141     llvm_unreachable("Unsupported calling convention");
1142   case CallingConv::C:
1143   case CallingConv::Fast:
1144     // Use target triple & subtarget features to do actual dispatch.
1145     if (Subtarget->isAAPCS_ABI()) {
1146       if (Subtarget->hasVFP2() &&
1147           FloatABIType == FloatABI::Hard)
1148         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1149       else
1150         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1151     } else
1152         return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1153   case CallingConv::ARM_AAPCS_VFP:
1154     return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1155   case CallingConv::ARM_AAPCS:
1156     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1157   case CallingConv::ARM_APCS:
1158     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1159   }
1160 }
1161
1162 bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1163                                   SmallVectorImpl<unsigned> &ArgRegs,
1164                                   SmallVectorImpl<EVT> &ArgVTs,
1165                                   SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1166                                   SmallVectorImpl<unsigned> &RegArgs,
1167                                   CallingConv::ID CC,
1168                                   unsigned &NumBytes) {
1169   SmallVector<CCValAssign, 16> ArgLocs;
1170   CCState CCInfo(CC, false, TM, ArgLocs, *Context);
1171   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC, false));
1172
1173   // Get a count of how many bytes are to be pushed on the stack.
1174   NumBytes = CCInfo.getNextStackOffset();
1175
1176   // Issue CALLSEQ_START
1177   unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1178   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1179           .addImm(NumBytes);
1180
1181   // Process the args.
1182   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1183     CCValAssign &VA = ArgLocs[i];
1184     unsigned Arg = ArgRegs[VA.getValNo()];
1185     EVT ArgVT = ArgVTs[VA.getValNo()];
1186
1187     // Handle arg promotion, etc.
1188     switch (VA.getLocInfo()) {
1189       case CCValAssign::Full: break;
1190       default:
1191       // TODO: Handle arg promotion.
1192       return false;
1193     }
1194
1195     // Now copy/store arg to correct locations.
1196     if (VA.isRegLoc()) {
1197       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1198               VA.getLocReg())
1199       .addReg(Arg);
1200       RegArgs.push_back(VA.getLocReg());
1201     } else {
1202       // Need to store
1203       return false;
1204     }
1205   }
1206   
1207   return true;
1208 }
1209
1210 bool ARMFastISel::FinishCall(EVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1211                              const Instruction *I, CallingConv::ID CC,
1212                              unsigned &NumBytes) {
1213   // Issue CALLSEQ_END
1214   unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1215   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
1216           .addImm(NumBytes).addImm(0);
1217
1218   // Now the return value.
1219   if (RetVT.getSimpleVT().SimpleTy != MVT::isVoid) {
1220     SmallVector<CCValAssign, 16> RVLocs;
1221     CCState CCInfo(CC, false, TM, RVLocs, *Context);
1222     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true));
1223
1224     // Copy all of the result registers out of their specified physreg.
1225     if (RVLocs.size() == 2 && RetVT.getSimpleVT().SimpleTy == MVT::f64) {
1226       // For this move we copy into two registers and then move into the
1227       // double fp reg we want.
1228       // TODO: Are the copies necessary?
1229       TargetRegisterClass *CopyRC = TLI.getRegClassFor(MVT::i32);
1230       unsigned Copy1 = createResultReg(CopyRC);
1231       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1232               Copy1).addReg(RVLocs[0].getLocReg());
1233       UsedRegs.push_back(RVLocs[0].getLocReg());
1234       
1235       unsigned Copy2 = createResultReg(CopyRC);
1236       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1237               Copy2).addReg(RVLocs[1].getLocReg());
1238       UsedRegs.push_back(RVLocs[1].getLocReg());
1239       
1240       EVT DestVT = RVLocs[0].getValVT();
1241       TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
1242       unsigned ResultReg = createResultReg(DstRC);
1243       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1244                               TII.get(ARM::VMOVDRR), ResultReg)
1245                       .addReg(Copy1).addReg(Copy2));
1246                               
1247       // Finally update the result.        
1248       UpdateValueMap(I, ResultReg);
1249     } else {
1250       assert(RVLocs.size() == 1 && "Can't handle non-double multi-reg retvals!");
1251       EVT CopyVT = RVLocs[0].getValVT();
1252       TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1253
1254       unsigned ResultReg = createResultReg(DstRC);
1255       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1256               ResultReg).addReg(RVLocs[0].getLocReg());
1257       UsedRegs.push_back(RVLocs[0].getLocReg());
1258
1259       // Finally update the result.        
1260       UpdateValueMap(I, ResultReg);
1261     }
1262   }
1263
1264   return true;                           
1265 }
1266
1267 // A quick function that will emit a call for a named libcall in F with the
1268 // vector of passed arguments for the Instruction in I. We can assume that we
1269 // can emit a call for any libcall we can produce. This is an abridged version 
1270 // of the full call infrastructure since we won't need to worry about things 
1271 // like computed function pointers or strange arguments at call sites.
1272 // TODO: Try to unify this and the normal call bits for ARM, then try to unify
1273 // with X86.
1274 bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
1275   CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
1276     
1277   // Handle *simple* calls for now.
1278   const Type *RetTy = I->getType();
1279   EVT RetVT;
1280   if (RetTy->isVoidTy())
1281     RetVT = MVT::isVoid;
1282   else if (!isTypeLegal(RetTy, RetVT))
1283     return false;
1284   
1285   // For now we're using BLX etc on the assumption that we have v5t ops.
1286   if (!Subtarget->hasV5TOps()) return false;
1287   
1288   // Set up the argument vectors.
1289   SmallVector<Value*, 8> Args;
1290   SmallVector<unsigned, 8> ArgRegs;
1291   SmallVector<EVT, 8> ArgVTs;
1292   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1293   Args.reserve(I->getNumOperands());
1294   ArgRegs.reserve(I->getNumOperands());
1295   ArgVTs.reserve(I->getNumOperands());
1296   ArgFlags.reserve(I->getNumOperands());
1297   for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1298     Value *Op = I->getOperand(i);
1299     unsigned Arg = getRegForValue(Op);
1300     if (Arg == 0) return false;
1301     
1302     const Type *ArgTy = Op->getType();
1303     EVT ArgVT;
1304     if (!isTypeLegal(ArgTy, ArgVT)) return false;
1305     
1306     ISD::ArgFlagsTy Flags;
1307     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1308     Flags.setOrigAlign(OriginalAlignment);
1309     
1310     Args.push_back(Op);
1311     ArgRegs.push_back(Arg);
1312     ArgVTs.push_back(ArgVT);
1313     ArgFlags.push_back(Flags);
1314   }
1315   
1316   // Handle the arguments now that we've gotten them.
1317   SmallVector<unsigned, 4> RegArgs;
1318   unsigned NumBytes;
1319   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1320     return false;
1321   
1322   // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1323   // TODO: Turn this into the table of arm call ops.  
1324   MachineInstrBuilder MIB;
1325   unsigned CallOpc;
1326   if(isThumb)
1327     CallOpc = Subtarget->isTargetDarwin() ? ARM::tBLXi_r9 : ARM::tBLXi;
1328   else
1329     CallOpc = Subtarget->isTargetDarwin() ? ARM::BLr9 : ARM::BL;
1330   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1331         .addExternalSymbol(TLI.getLibcallName(Call));
1332     
1333   // Add implicit physical register uses to the call.
1334   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1335     MIB.addReg(RegArgs[i]);
1336     
1337   // Finish off the call including any return values.
1338   SmallVector<unsigned, 4> UsedRegs;  
1339   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1340   
1341   // Set all unused physreg defs as dead.
1342   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1343   
1344   return true;
1345 }
1346
1347 bool ARMFastISel::SelectCall(const Instruction *I) {
1348   const CallInst *CI = cast<CallInst>(I);
1349   const Value *Callee = CI->getCalledValue();
1350
1351   // Can't handle inline asm or worry about intrinsics yet.
1352   if (isa<InlineAsm>(Callee) || isa<IntrinsicInst>(CI)) return false;
1353
1354   // Only handle global variable Callees that are direct calls.
1355   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1356   if (!GV || Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel()))
1357     return false;
1358   
1359   // Check the calling convention.
1360   ImmutableCallSite CS(CI);
1361   CallingConv::ID CC = CS.getCallingConv();
1362   // TODO: Avoid some calling conventions?
1363   if (CC != CallingConv::C) {
1364     // errs() << "Can't handle calling convention: " << CC << "\n";
1365     return false;
1366   }
1367   
1368   // Let SDISel handle vararg functions.
1369   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1370   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1371   if (FTy->isVarArg())
1372     return false;
1373   
1374   // Handle *simple* calls for now.
1375   const Type *RetTy = I->getType();
1376   EVT RetVT;
1377   if (RetTy->isVoidTy())
1378     RetVT = MVT::isVoid;
1379   else if (!isTypeLegal(RetTy, RetVT))
1380     return false;
1381   
1382   // For now we're using BLX etc on the assumption that we have v5t ops.
1383   // TODO: Maybe?
1384   if (!Subtarget->hasV5TOps()) return false;
1385   
1386   // Set up the argument vectors.
1387   SmallVector<Value*, 8> Args;
1388   SmallVector<unsigned, 8> ArgRegs;
1389   SmallVector<EVT, 8> ArgVTs;
1390   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1391   Args.reserve(CS.arg_size());
1392   ArgRegs.reserve(CS.arg_size());
1393   ArgVTs.reserve(CS.arg_size());
1394   ArgFlags.reserve(CS.arg_size());
1395   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1396        i != e; ++i) {
1397     unsigned Arg = getRegForValue(*i);
1398     
1399     if (Arg == 0)
1400       return false;
1401     ISD::ArgFlagsTy Flags;
1402     unsigned AttrInd = i - CS.arg_begin() + 1;
1403     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1404       Flags.setSExt();
1405     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1406       Flags.setZExt();
1407
1408          // FIXME: Only handle *easy* calls for now.
1409     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1410         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1411         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1412         CS.paramHasAttr(AttrInd, Attribute::ByVal))
1413       return false;
1414
1415     const Type *ArgTy = (*i)->getType();
1416     EVT ArgVT;
1417     if (!isTypeLegal(ArgTy, ArgVT))
1418       return false;
1419     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1420     Flags.setOrigAlign(OriginalAlignment);
1421     
1422     Args.push_back(*i);
1423     ArgRegs.push_back(Arg);
1424     ArgVTs.push_back(ArgVT);
1425     ArgFlags.push_back(Flags);
1426   }
1427   
1428   // Handle the arguments now that we've gotten them.
1429   SmallVector<unsigned, 4> RegArgs;
1430   unsigned NumBytes;
1431   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1432     return false;
1433   
1434   // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1435   // TODO: Turn this into the table of arm call ops.  
1436   MachineInstrBuilder MIB;
1437   unsigned CallOpc;
1438   if(isThumb)
1439     CallOpc = Subtarget->isTargetDarwin() ? ARM::tBLXi_r9 : ARM::tBLXi;
1440   else
1441     CallOpc = Subtarget->isTargetDarwin() ? ARM::BLr9 : ARM::BL;
1442   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1443               .addGlobalAddress(GV, 0, 0);
1444     
1445   // Add implicit physical register uses to the call.
1446   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1447     MIB.addReg(RegArgs[i]);
1448     
1449   // Finish off the call including any return values.
1450   SmallVector<unsigned, 4> UsedRegs;  
1451   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1452   
1453   // Set all unused physreg defs as dead.
1454   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1455   
1456   return true;
1457   
1458 }
1459
1460 // TODO: SoftFP support.
1461 bool ARMFastISel::TargetSelectInstruction(const Instruction *I) {
1462   // No Thumb-1 for now.
1463   if (isThumb && !AFI->isThumb2Function()) return false;
1464
1465   switch (I->getOpcode()) {
1466     case Instruction::Load:
1467       return SelectLoad(I);
1468     case Instruction::Store:
1469       return SelectStore(I);
1470     case Instruction::Br:
1471       return SelectBranch(I);
1472     case Instruction::ICmp:
1473     case Instruction::FCmp:
1474       return SelectCmp(I);
1475     case Instruction::FPExt:
1476       return SelectFPExt(I);
1477     case Instruction::FPTrunc:
1478       return SelectFPTrunc(I);
1479     case Instruction::SIToFP:
1480       return SelectSIToFP(I);
1481     case Instruction::FPToSI:
1482       return SelectFPToSI(I);
1483     case Instruction::FAdd:
1484       return SelectBinaryOp(I, ISD::FADD);
1485     case Instruction::FSub:
1486       return SelectBinaryOp(I, ISD::FSUB);
1487     case Instruction::FMul:
1488       return SelectBinaryOp(I, ISD::FMUL);
1489     case Instruction::SDiv:
1490       return SelectSDiv(I);
1491     case Instruction::Call:
1492       return SelectCall(I);
1493     default: break;
1494   }
1495   return false;
1496 }
1497
1498 namespace llvm {
1499   llvm::FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo) {
1500     if (EnableARMFastISel) return new ARMFastISel(funcInfo);
1501     return 0;
1502   }
1503 }