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