Handle more complex GEP based loads and add a few TODOs to deal with
[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 SelectSRem(const Instruction *I);
131     virtual bool SelectCall(const Instruction *I);
132     virtual bool SelectSelect(const Instruction *I);
133
134     // Utility routines.
135   private:
136     bool isTypeLegal(const Type *Ty, EVT &VT);
137     bool isLoadTypeLegal(const Type *Ty, EVT &VT);
138     bool ARMEmitLoad(EVT VT, unsigned &ResultReg, unsigned Reg, int Offset);
139     bool ARMEmitStore(EVT VT, unsigned SrcReg, unsigned Reg, int Offset);
140     bool ARMComputeRegOffset(const Value *Obj, unsigned &Reg, int &Offset);
141     unsigned ARMSimplifyRegOffset(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::BitCast: {
591       // Look through bitcasts.
592       return ARMComputeRegOffset(U->getOperand(0), Reg, Offset);
593     }
594     case Instruction::IntToPtr: {
595       // Look past no-op inttoptrs.
596       if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
597         return ARMComputeRegOffset(U->getOperand(0), Reg, Offset);
598       break;
599     }
600     case Instruction::PtrToInt: {
601       // Look past no-op ptrtoints.
602       if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
603         return ARMComputeRegOffset(U->getOperand(0), Reg, Offset);
604       break;
605     }
606     case Instruction::GetElementPtr: {
607       int SavedOffset = Offset;
608       int TmpOffset = Offset;
609       
610       // Iterate through the GEP folding the constants into offsets where
611       // we can.
612       gep_type_iterator GTI = gep_type_begin(U);
613       for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
614            i != e; ++i, ++GTI) {
615         const Value *Op = *i;
616         if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
617           const StructLayout *SL = TD.getStructLayout(STy);
618           unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
619           TmpOffset += SL->getElementOffset(Idx);
620         } else {
621           goto unsupported_gep;
622         }
623       }
624       
625       Offset = TmpOffset;
626       if (ARMComputeRegOffset(U->getOperand(0), Reg, Offset)) return true;
627       
628       Offset = SavedOffset;
629       break;
630       
631       unsupported_gep:
632       // errs() << "GEP: " << *U << "\n";
633       break;
634     }
635     case Instruction::Alloca: {
636       // TODO: Fix this to do intermediate loads, etc.
637       if (Offset != 0) return false;
638       
639       const AllocaInst *AI = cast<AllocaInst>(Obj);
640       DenseMap<const AllocaInst*, int>::iterator SI =
641         FuncInfo.StaticAllocaMap.find(AI);
642       if (SI != FuncInfo.StaticAllocaMap.end()) {
643         Reg = ARM::SP;
644         Offset = SI->second;
645         return true;
646       }
647       // Don't handle dynamic allocas.
648       assert(!FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Obj)) &&
649              "Alloca should have been handled earlier!");
650       return false;
651     }
652   }
653
654   // Materialize the global variable's address into a reg which can
655   // then be used later to load the variable.
656   if (const GlobalValue *GV = dyn_cast<GlobalValue>(Obj)) {
657     unsigned Tmp = ARMMaterializeGV(GV, TLI.getValueType(Obj->getType()));
658     if (Tmp == 0) return false;
659     
660     Reg = Tmp;
661     return true;
662   }
663
664   // Try to get this in a register if nothing else has worked.
665   if (Reg == 0) Reg = getRegForValue(Obj);
666   
667   return Reg != 0;
668 }
669
670 unsigned ARMFastISel::ARMSimplifyRegOffset(unsigned Reg, int &Offset) {
671
672   // Since the offset may be too large for the load instruction
673   // get the reg+offset into a register.
674   if (Reg != ARM::SP && Offset != 0) {
675     ARMCC::CondCodes Pred = ARMCC::AL;
676     unsigned PredReg = 0;
677
678     if (!isThumb)
679       emitARMRegPlusImmediate(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
680                               Reg, Reg, Offset, Pred, PredReg,
681                               static_cast<const ARMBaseInstrInfo&>(TII));
682     else {
683       assert(AFI->isThumb2Function());
684       emitT2RegPlusImmediate(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
685                              Reg, Reg, Offset, Pred, PredReg,
686                              static_cast<const ARMBaseInstrInfo&>(TII));
687     }
688     
689     Offset = 0;
690   }
691   
692   return Reg;
693 }
694
695 bool ARMFastISel::ARMEmitLoad(EVT VT, unsigned &ResultReg,
696                               unsigned Reg, int Offset) {
697
698   assert(VT.isSimple() && "Non-simple types are invalid here!");
699   unsigned Opc;
700   TargetRegisterClass *RC;
701   bool isFloat = false;
702   switch (VT.getSimpleVT().SimpleTy) {
703     default:
704       // This is mostly going to be Neon/vector support.
705       return false;
706     case MVT::i16:
707       Opc = isThumb ? ARM::t2LDRHi8 : ARM::LDRH;
708       RC = ARM::GPRRegisterClass;
709       VT = MVT::i32;
710       break;
711     case MVT::i8:
712       Opc = isThumb ? ARM::t2LDRBi8 : ARM::LDRB;
713       RC = ARM::GPRRegisterClass;
714       VT = MVT::i32;
715       break;
716     case MVT::i32:
717       Opc = isThumb ? ARM::t2LDRi8 : ARM::LDR;
718       RC = ARM::GPRRegisterClass;
719       break;
720     case MVT::f32:
721       Opc = ARM::VLDRS;
722       RC = TLI.getRegClassFor(VT);
723       isFloat = true;
724       break;
725     case MVT::f64:
726       Opc = ARM::VLDRD;
727       RC = TLI.getRegClassFor(VT);
728       isFloat = true;
729       break;
730   }
731
732   ResultReg = createResultReg(RC);
733
734   // For now with the additions above the offset should be zero - thus we
735   // can always fit into an i8.
736   assert((Reg == ARM::SP || Offset == 0) &&
737           "Offset not zero and not a stack load!");
738
739   if (Reg == ARM::SP)
740     TII.loadRegFromStackSlot(*FuncInfo.MBB, *FuncInfo.InsertPt,
741                              ResultReg, Offset, RC,
742                              TM.getRegisterInfo());
743   // The thumb and floating point instructions both take 2 operands, ARM takes
744   // another register.
745   else if (isFloat || isThumb)
746     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
747                             TII.get(Opc), ResultReg)
748                     .addReg(Reg).addImm(Offset));
749   else
750     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
751                             TII.get(Opc), ResultReg)
752                     .addReg(Reg).addReg(0).addImm(Offset));
753   return true;
754 }
755
756 bool ARMFastISel::SelectLoad(const Instruction *I) {
757   // Verify we have a legal type before going any further.
758   EVT VT;
759   if (!isLoadTypeLegal(I->getType(), VT))
760     return false;
761
762   // Our register and offset with innocuous defaults.
763   unsigned Reg = 0;
764   int Offset = 0;
765
766   // See if we can handle this as Reg + Offset
767   if (!ARMComputeRegOffset(I->getOperand(0), Reg, Offset))
768     return false;
769
770   unsigned BaseReg = ARMSimplifyRegOffset(Reg, Offset);
771
772   unsigned ResultReg;
773   if (!ARMEmitLoad(VT, ResultReg, BaseReg, Offset)) return false;
774
775   UpdateValueMap(I, ResultReg);
776   return true;
777 }
778
779 bool ARMFastISel::ARMEmitStore(EVT VT, unsigned SrcReg,
780                                unsigned DstReg, int Offset) {
781   unsigned StrOpc;
782   bool isFloat = false;
783   // VT is set here only for use in the alloca stores below - those are promoted
784   // to reg size always.
785   switch (VT.getSimpleVT().SimpleTy) {
786     default: return false;
787     case MVT::i1:
788     case MVT::i8: 
789       VT = MVT::i32;
790       StrOpc = isThumb ? ARM::t2STRBi8 : ARM::STRB;
791       break;
792     case MVT::i16:
793       VT = MVT::i32;
794       StrOpc = isThumb ? ARM::t2STRHi8 : ARM::STRH;
795       break;
796     case MVT::i32: StrOpc = isThumb ? ARM::t2STRi8 : ARM::STR; break;
797     case MVT::f32:
798       if (!Subtarget->hasVFP2()) return false;
799       StrOpc = ARM::VSTRS;
800       isFloat = true;
801       break;
802     case MVT::f64:
803       if (!Subtarget->hasVFP2()) return false;
804       StrOpc = ARM::VSTRD;
805       isFloat = true;
806       break;
807   }
808
809   if (DstReg == ARM::SP)
810     TII.storeRegToStackSlot(*FuncInfo.MBB, *FuncInfo.InsertPt,
811                             SrcReg, true /*isKill*/, Offset,
812                             TLI.getRegClassFor(VT), TM.getRegisterInfo());
813   // The thumb addressing mode has operands swapped from the arm addressing
814   // mode, the floating point one only has two operands.
815   if (isFloat || isThumb)
816     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
817                             TII.get(StrOpc))
818                     .addReg(SrcReg).addReg(DstReg).addImm(Offset));
819   else
820     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
821                             TII.get(StrOpc))
822                     .addReg(SrcReg).addReg(DstReg).addReg(0).addImm(Offset));
823
824   return true;
825 }
826
827 bool ARMFastISel::SelectStore(const Instruction *I) {
828   Value *Op0 = I->getOperand(0);
829   unsigned SrcReg = 0;
830
831   // Yay type legalization
832   EVT VT;
833   if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
834     return false;
835
836   // Get the value to be stored into a register.
837   SrcReg = getRegForValue(Op0);
838   if (SrcReg == 0)
839     return false;
840
841   // Our register and offset with innocuous defaults.
842   unsigned Reg = 0;
843   int Offset = 0;
844
845   // See if we can handle this as Reg + Offset
846   if (!ARMComputeRegOffset(I->getOperand(1), Reg, Offset))
847     return false;
848
849   unsigned BaseReg = ARMSimplifyRegOffset(Reg, Offset);
850
851   if (!ARMEmitStore(VT, SrcReg, BaseReg, Offset)) return false;
852
853   return true;
854 }
855
856 static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
857   switch (Pred) {
858     // Needs two compares...
859     case CmpInst::FCMP_ONE:
860     case CmpInst::FCMP_UEQ:
861     default:
862       assert(false && "Unhandled CmpInst::Predicate!");
863       return ARMCC::AL;
864     case CmpInst::ICMP_EQ:
865     case CmpInst::FCMP_OEQ:
866       return ARMCC::EQ;
867     case CmpInst::ICMP_SGT:
868     case CmpInst::FCMP_OGT:
869       return ARMCC::GT;
870     case CmpInst::ICMP_SGE:
871     case CmpInst::FCMP_OGE:
872       return ARMCC::GE;
873     case CmpInst::ICMP_UGT:
874     case CmpInst::FCMP_UGT:
875       return ARMCC::HI;
876     case CmpInst::FCMP_OLT:
877       return ARMCC::MI;
878     case CmpInst::ICMP_ULE:
879     case CmpInst::FCMP_OLE:
880       return ARMCC::LS;
881     case CmpInst::FCMP_ORD:
882       return ARMCC::VC;
883     case CmpInst::FCMP_UNO:
884       return ARMCC::VS;
885     case CmpInst::FCMP_UGE:
886       return ARMCC::PL;
887     case CmpInst::ICMP_SLT:
888     case CmpInst::FCMP_ULT:
889       return ARMCC::LT;
890     case CmpInst::ICMP_SLE:
891     case CmpInst::FCMP_ULE:
892       return ARMCC::LE;
893     case CmpInst::FCMP_UNE:
894     case CmpInst::ICMP_NE:
895       return ARMCC::NE;
896     case CmpInst::ICMP_UGE:
897       return ARMCC::HS;
898     case CmpInst::ICMP_ULT:
899       return ARMCC::LO;
900   }
901 }
902
903 bool ARMFastISel::SelectBranch(const Instruction *I) {
904   const BranchInst *BI = cast<BranchInst>(I);
905   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
906   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
907
908   // Simple branch support.
909   // TODO: Try to avoid the re-computation in some places.
910   unsigned CondReg = getRegForValue(BI->getCondition());
911   if (CondReg == 0) return false;
912
913   // Re-set the flags just in case.
914   unsigned CmpOpc = isThumb ? ARM::t2CMPri : ARM::CMPri;
915   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
916                   .addReg(CondReg).addImm(1));
917
918   unsigned BrOpc = isThumb ? ARM::t2Bcc : ARM::Bcc;
919   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
920                   .addMBB(TBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
921   FastEmitBranch(FBB, DL);
922   FuncInfo.MBB->addSuccessor(TBB);
923   return true;
924 }
925
926 bool ARMFastISel::SelectCmp(const Instruction *I) {
927   const CmpInst *CI = cast<CmpInst>(I);
928
929   EVT VT;
930   const Type *Ty = CI->getOperand(0)->getType();
931   if (!isTypeLegal(Ty, VT))
932     return false;
933
934   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
935   if (isFloat && !Subtarget->hasVFP2())
936     return false;
937
938   unsigned CmpOpc;
939   unsigned CondReg;
940   switch (VT.getSimpleVT().SimpleTy) {
941     default: return false;
942     // TODO: Verify compares.
943     case MVT::f32:
944       CmpOpc = ARM::VCMPES;
945       CondReg = ARM::FPSCR;
946       break;
947     case MVT::f64:
948       CmpOpc = ARM::VCMPED;
949       CondReg = ARM::FPSCR;
950       break;
951     case MVT::i32:
952       CmpOpc = isThumb ? ARM::t2CMPrr : ARM::CMPrr;
953       CondReg = ARM::CPSR;
954       break;
955   }
956
957   // Get the compare predicate.
958   ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
959
960   // We may not handle every CC for now.
961   if (ARMPred == ARMCC::AL) return false;
962
963   unsigned Arg1 = getRegForValue(CI->getOperand(0));
964   if (Arg1 == 0) return false;
965
966   unsigned Arg2 = getRegForValue(CI->getOperand(1));
967   if (Arg2 == 0) return false;
968
969   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
970                   .addReg(Arg1).addReg(Arg2));
971
972   // For floating point we need to move the result to a comparison register
973   // that we can then use for branches.
974   if (isFloat)
975     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
976                             TII.get(ARM::FMSTAT)));
977
978   // Now set a register based on the comparison. Explicitly set the predicates
979   // here.
980   unsigned MovCCOpc = isThumb ? ARM::t2MOVCCi : ARM::MOVCCi;
981   TargetRegisterClass *RC = isThumb ? ARM::rGPRRegisterClass
982                                     : ARM::GPRRegisterClass;
983   unsigned DestReg = createResultReg(RC);
984   Constant *Zero
985     = ConstantInt::get(Type::getInt32Ty(*Context), 0);
986   unsigned ZeroReg = TargetMaterializeConstant(Zero);
987   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), DestReg)
988           .addReg(ZeroReg).addImm(1)
989           .addImm(ARMPred).addReg(CondReg);
990
991   UpdateValueMap(I, DestReg);
992   return true;
993 }
994
995 bool ARMFastISel::SelectFPExt(const Instruction *I) {
996   // Make sure we have VFP and that we're extending float to double.
997   if (!Subtarget->hasVFP2()) return false;
998
999   Value *V = I->getOperand(0);
1000   if (!I->getType()->isDoubleTy() ||
1001       !V->getType()->isFloatTy()) return false;
1002
1003   unsigned Op = getRegForValue(V);
1004   if (Op == 0) return false;
1005
1006   unsigned Result = createResultReg(ARM::DPRRegisterClass);
1007   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1008                           TII.get(ARM::VCVTDS), Result)
1009                   .addReg(Op));
1010   UpdateValueMap(I, Result);
1011   return true;
1012 }
1013
1014 bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
1015   // Make sure we have VFP and that we're truncating double to float.
1016   if (!Subtarget->hasVFP2()) return false;
1017
1018   Value *V = I->getOperand(0);
1019   if (!(I->getType()->isFloatTy() &&
1020         V->getType()->isDoubleTy())) return false;
1021
1022   unsigned Op = getRegForValue(V);
1023   if (Op == 0) return false;
1024
1025   unsigned Result = createResultReg(ARM::SPRRegisterClass);
1026   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1027                           TII.get(ARM::VCVTSD), Result)
1028                   .addReg(Op));
1029   UpdateValueMap(I, Result);
1030   return true;
1031 }
1032
1033 bool ARMFastISel::SelectSIToFP(const Instruction *I) {
1034   // Make sure we have VFP.
1035   if (!Subtarget->hasVFP2()) return false;
1036
1037   EVT DstVT;
1038   const Type *Ty = I->getType();
1039   if (!isTypeLegal(Ty, DstVT))
1040     return false;
1041
1042   unsigned Op = getRegForValue(I->getOperand(0));
1043   if (Op == 0) return false;
1044
1045   // The conversion routine works on fp-reg to fp-reg and the operand above
1046   // was an integer, move it to the fp registers if possible.
1047   unsigned FP = ARMMoveToFPReg(MVT::f32, Op);
1048   if (FP == 0) return false;
1049
1050   unsigned Opc;
1051   if (Ty->isFloatTy()) Opc = ARM::VSITOS;
1052   else if (Ty->isDoubleTy()) Opc = ARM::VSITOD;
1053   else return 0;
1054
1055   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1056   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1057                           ResultReg)
1058                   .addReg(FP));
1059   UpdateValueMap(I, ResultReg);
1060   return true;
1061 }
1062
1063 bool ARMFastISel::SelectFPToSI(const Instruction *I) {
1064   // Make sure we have VFP.
1065   if (!Subtarget->hasVFP2()) return false;
1066
1067   EVT DstVT;
1068   const Type *RetTy = I->getType();
1069   if (!isTypeLegal(RetTy, DstVT))
1070     return false;
1071
1072   unsigned Op = getRegForValue(I->getOperand(0));
1073   if (Op == 0) return false;
1074
1075   unsigned Opc;
1076   const Type *OpTy = I->getOperand(0)->getType();
1077   if (OpTy->isFloatTy()) Opc = ARM::VTOSIZS;
1078   else if (OpTy->isDoubleTy()) Opc = ARM::VTOSIZD;
1079   else return 0;
1080
1081   // f64->s32 or f32->s32 both need an intermediate f32 reg.
1082   unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1083   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1084                           ResultReg)
1085                   .addReg(Op));
1086
1087   // This result needs to be in an integer register, but the conversion only
1088   // takes place in fp-regs.
1089   unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1090   if (IntReg == 0) return false;
1091
1092   UpdateValueMap(I, IntReg);
1093   return true;
1094 }
1095
1096 bool ARMFastISel::SelectSelect(const Instruction *I) {
1097   EVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
1098   if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
1099     return false;
1100
1101   // Things need to be register sized for register moves.
1102   if (VT.getSimpleVT().SimpleTy != MVT::i32) return false;
1103   const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
1104
1105   unsigned CondReg = getRegForValue(I->getOperand(0));
1106   if (CondReg == 0) return false;
1107   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1108   if (Op1Reg == 0) return false;
1109   unsigned Op2Reg = getRegForValue(I->getOperand(2));
1110   if (Op2Reg == 0) return false;
1111
1112   unsigned CmpOpc = isThumb ? ARM::t2TSTri : ARM::TSTri;
1113   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1114                   .addReg(CondReg).addImm(1));
1115   unsigned ResultReg = createResultReg(RC);
1116   unsigned MovCCOpc = isThumb ? ARM::t2MOVCCr : ARM::MOVCCr;
1117   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1118     .addReg(Op1Reg).addReg(Op2Reg)
1119     .addImm(ARMCC::EQ).addReg(ARM::CPSR);
1120   UpdateValueMap(I, ResultReg);
1121   return true;
1122 }
1123
1124 bool ARMFastISel::SelectSDiv(const Instruction *I) {
1125   EVT VT;
1126   const Type *Ty = I->getType();
1127   if (!isTypeLegal(Ty, VT))
1128     return false;
1129
1130   // If we have integer div support we should have selected this automagically.
1131   // In case we have a real miss go ahead and return false and we'll pick
1132   // it up later.
1133   if (Subtarget->hasDivide()) return false;
1134
1135   // Otherwise emit a libcall.
1136   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1137   if (VT == MVT::i8)
1138     LC = RTLIB::SDIV_I8;
1139   else if (VT == MVT::i16)
1140     LC = RTLIB::SDIV_I16;
1141   else if (VT == MVT::i32)
1142     LC = RTLIB::SDIV_I32;
1143   else if (VT == MVT::i64)
1144     LC = RTLIB::SDIV_I64;
1145   else if (VT == MVT::i128)
1146     LC = RTLIB::SDIV_I128;
1147   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1148
1149   return ARMEmitLibcall(I, LC);
1150 }
1151
1152 bool ARMFastISel::SelectSRem(const Instruction *I) {
1153   EVT VT;
1154   const Type *Ty = I->getType();
1155   if (!isTypeLegal(Ty, VT))
1156     return false;
1157
1158   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1159   if (VT == MVT::i8)
1160     LC = RTLIB::SREM_I8;
1161   else if (VT == MVT::i16)
1162     LC = RTLIB::SREM_I16;
1163   else if (VT == MVT::i32)
1164     LC = RTLIB::SREM_I32;
1165   else if (VT == MVT::i64)
1166     LC = RTLIB::SREM_I64;
1167   else if (VT == MVT::i128)
1168     LC = RTLIB::SREM_I128;
1169   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1170     
1171   return ARMEmitLibcall(I, LC);
1172 }
1173
1174 bool ARMFastISel::SelectBinaryOp(const Instruction *I, unsigned ISDOpcode) {
1175   EVT VT  = TLI.getValueType(I->getType(), true);
1176
1177   // We can get here in the case when we want to use NEON for our fp
1178   // operations, but can't figure out how to. Just use the vfp instructions
1179   // if we have them.
1180   // FIXME: It'd be nice to use NEON instructions.
1181   const Type *Ty = I->getType();
1182   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1183   if (isFloat && !Subtarget->hasVFP2())
1184     return false;
1185
1186   unsigned Op1 = getRegForValue(I->getOperand(0));
1187   if (Op1 == 0) return false;
1188
1189   unsigned Op2 = getRegForValue(I->getOperand(1));
1190   if (Op2 == 0) return false;
1191
1192   unsigned Opc;
1193   bool is64bit = VT.getSimpleVT().SimpleTy == MVT::f64 ||
1194                  VT.getSimpleVT().SimpleTy == MVT::i64;
1195   switch (ISDOpcode) {
1196     default: return false;
1197     case ISD::FADD:
1198       Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1199       break;
1200     case ISD::FSUB:
1201       Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1202       break;
1203     case ISD::FMUL:
1204       Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1205       break;
1206   }
1207   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1208   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1209                           TII.get(Opc), ResultReg)
1210                   .addReg(Op1).addReg(Op2));
1211   UpdateValueMap(I, ResultReg);
1212   return true;
1213 }
1214
1215 // Call Handling Code
1216
1217 // This is largely taken directly from CCAssignFnForNode - we don't support
1218 // varargs in FastISel so that part has been removed.
1219 // TODO: We may not support all of this.
1220 CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC, bool Return) {
1221   switch (CC) {
1222   default:
1223     llvm_unreachable("Unsupported calling convention");
1224   case CallingConv::C:
1225   case CallingConv::Fast:
1226     // Use target triple & subtarget features to do actual dispatch.
1227     if (Subtarget->isAAPCS_ABI()) {
1228       if (Subtarget->hasVFP2() &&
1229           FloatABIType == FloatABI::Hard)
1230         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1231       else
1232         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1233     } else
1234         return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1235   case CallingConv::ARM_AAPCS_VFP:
1236     return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1237   case CallingConv::ARM_AAPCS:
1238     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1239   case CallingConv::ARM_APCS:
1240     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1241   }
1242 }
1243
1244 bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1245                                   SmallVectorImpl<unsigned> &ArgRegs,
1246                                   SmallVectorImpl<EVT> &ArgVTs,
1247                                   SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1248                                   SmallVectorImpl<unsigned> &RegArgs,
1249                                   CallingConv::ID CC,
1250                                   unsigned &NumBytes) {
1251   SmallVector<CCValAssign, 16> ArgLocs;
1252   CCState CCInfo(CC, false, TM, ArgLocs, *Context);
1253   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC, false));
1254
1255   // Get a count of how many bytes are to be pushed on the stack.
1256   NumBytes = CCInfo.getNextStackOffset();
1257
1258   // Issue CALLSEQ_START
1259   unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1260   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1261                           TII.get(AdjStackDown))
1262                   .addImm(NumBytes));
1263
1264   // Process the args.
1265   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1266     CCValAssign &VA = ArgLocs[i];
1267     unsigned Arg = ArgRegs[VA.getValNo()];
1268     EVT ArgVT = ArgVTs[VA.getValNo()];
1269
1270     // Handle arg promotion, etc.
1271     switch (VA.getLocInfo()) {
1272       case CCValAssign::Full: break;
1273       default:
1274       // TODO: Handle arg promotion.
1275       return false;
1276     }
1277
1278     // Now copy/store arg to correct locations.
1279     // TODO: We need custom lowering for f64 args.
1280     if (VA.isRegLoc() && !VA.needsCustom()) {
1281       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1282               VA.getLocReg())
1283       .addReg(Arg);
1284       RegArgs.push_back(VA.getLocReg());
1285     } else {
1286       // Need to store
1287       return false;
1288     }
1289   }
1290
1291   return true;
1292 }
1293
1294 bool ARMFastISel::FinishCall(EVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1295                              const Instruction *I, CallingConv::ID CC,
1296                              unsigned &NumBytes) {
1297   // Issue CALLSEQ_END
1298   unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1299   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1300                           TII.get(AdjStackUp))
1301                   .addImm(NumBytes).addImm(0));
1302
1303   // Now the return value.
1304   if (RetVT.getSimpleVT().SimpleTy != MVT::isVoid) {
1305     SmallVector<CCValAssign, 16> RVLocs;
1306     CCState CCInfo(CC, false, TM, RVLocs, *Context);
1307     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true));
1308
1309     // Copy all of the result registers out of their specified physreg.
1310     if (RVLocs.size() == 2 && RetVT.getSimpleVT().SimpleTy == MVT::f64) {
1311       // For this move we copy into two registers and then move into the
1312       // double fp reg we want.
1313       // TODO: Are the copies necessary?
1314       TargetRegisterClass *CopyRC = TLI.getRegClassFor(MVT::i32);
1315       unsigned Copy1 = createResultReg(CopyRC);
1316       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1317               Copy1).addReg(RVLocs[0].getLocReg());
1318       UsedRegs.push_back(RVLocs[0].getLocReg());
1319
1320       unsigned Copy2 = createResultReg(CopyRC);
1321       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1322               Copy2).addReg(RVLocs[1].getLocReg());
1323       UsedRegs.push_back(RVLocs[1].getLocReg());
1324
1325       EVT DestVT = RVLocs[0].getValVT();
1326       TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
1327       unsigned ResultReg = createResultReg(DstRC);
1328       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1329                               TII.get(ARM::VMOVDRR), ResultReg)
1330                       .addReg(Copy1).addReg(Copy2));
1331
1332       // Finally update the result.
1333       UpdateValueMap(I, ResultReg);
1334     } else {
1335       assert(RVLocs.size() == 1 &&"Can't handle non-double multi-reg retvals!");
1336       EVT CopyVT = RVLocs[0].getValVT();
1337       TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1338
1339       unsigned ResultReg = createResultReg(DstRC);
1340       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1341               ResultReg).addReg(RVLocs[0].getLocReg());
1342       UsedRegs.push_back(RVLocs[0].getLocReg());
1343
1344       // Finally update the result.
1345       UpdateValueMap(I, ResultReg);
1346     }
1347   }
1348
1349   return true;
1350 }
1351
1352 // A quick function that will emit a call for a named libcall in F with the
1353 // vector of passed arguments for the Instruction in I. We can assume that we
1354 // can emit a call for any libcall we can produce. This is an abridged version
1355 // of the full call infrastructure since we won't need to worry about things
1356 // like computed function pointers or strange arguments at call sites.
1357 // TODO: Try to unify this and the normal call bits for ARM, then try to unify
1358 // with X86.
1359 bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
1360   CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
1361
1362   // Handle *simple* calls for now.
1363   const Type *RetTy = I->getType();
1364   EVT RetVT;
1365   if (RetTy->isVoidTy())
1366     RetVT = MVT::isVoid;
1367   else if (!isTypeLegal(RetTy, RetVT))
1368     return false;
1369
1370   // For now we're using BLX etc on the assumption that we have v5t ops.
1371   if (!Subtarget->hasV5TOps()) return false;
1372
1373   // Set up the argument vectors.
1374   SmallVector<Value*, 8> Args;
1375   SmallVector<unsigned, 8> ArgRegs;
1376   SmallVector<EVT, 8> ArgVTs;
1377   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1378   Args.reserve(I->getNumOperands());
1379   ArgRegs.reserve(I->getNumOperands());
1380   ArgVTs.reserve(I->getNumOperands());
1381   ArgFlags.reserve(I->getNumOperands());
1382   for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1383     Value *Op = I->getOperand(i);
1384     unsigned Arg = getRegForValue(Op);
1385     if (Arg == 0) return false;
1386
1387     const Type *ArgTy = Op->getType();
1388     EVT ArgVT;
1389     if (!isTypeLegal(ArgTy, ArgVT)) return false;
1390
1391     ISD::ArgFlagsTy Flags;
1392     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1393     Flags.setOrigAlign(OriginalAlignment);
1394
1395     Args.push_back(Op);
1396     ArgRegs.push_back(Arg);
1397     ArgVTs.push_back(ArgVT);
1398     ArgFlags.push_back(Flags);
1399   }
1400
1401   // Handle the arguments now that we've gotten them.
1402   SmallVector<unsigned, 4> RegArgs;
1403   unsigned NumBytes;
1404   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1405     return false;
1406
1407   // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1408   // TODO: Turn this into the table of arm call ops.
1409   MachineInstrBuilder MIB;
1410   unsigned CallOpc;
1411   if(isThumb)
1412     CallOpc = Subtarget->isTargetDarwin() ? ARM::tBLXi_r9 : ARM::tBLXi;
1413   else
1414     CallOpc = Subtarget->isTargetDarwin() ? ARM::BLr9 : ARM::BL;
1415   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1416         .addExternalSymbol(TLI.getLibcallName(Call));
1417
1418   // Add implicit physical register uses to the call.
1419   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1420     MIB.addReg(RegArgs[i]);
1421
1422   // Finish off the call including any return values.
1423   SmallVector<unsigned, 4> UsedRegs;
1424   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1425
1426   // Set all unused physreg defs as dead.
1427   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1428
1429   return true;
1430 }
1431
1432 bool ARMFastISel::SelectCall(const Instruction *I) {
1433   const CallInst *CI = cast<CallInst>(I);
1434   const Value *Callee = CI->getCalledValue();
1435
1436   // Can't handle inline asm or worry about intrinsics yet.
1437   if (isa<InlineAsm>(Callee) || isa<IntrinsicInst>(CI)) return false;
1438
1439   // Only handle global variable Callees that are direct calls.
1440   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1441   if (!GV || Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel()))
1442     return false;
1443
1444   // Check the calling convention.
1445   ImmutableCallSite CS(CI);
1446   CallingConv::ID CC = CS.getCallingConv();
1447   // TODO: Avoid some calling conventions?
1448   if (CC != CallingConv::C) {
1449     // errs() << "Can't handle calling convention: " << CC << "\n";
1450     return false;
1451   }
1452
1453   // Let SDISel handle vararg functions.
1454   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1455   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1456   if (FTy->isVarArg())
1457     return false;
1458
1459   // Handle *simple* calls for now.
1460   const Type *RetTy = I->getType();
1461   EVT RetVT;
1462   if (RetTy->isVoidTy())
1463     RetVT = MVT::isVoid;
1464   else if (!isTypeLegal(RetTy, RetVT))
1465     return false;
1466
1467   // For now we're using BLX etc on the assumption that we have v5t ops.
1468   // TODO: Maybe?
1469   if (!Subtarget->hasV5TOps()) return false;
1470
1471   // Set up the argument vectors.
1472   SmallVector<Value*, 8> Args;
1473   SmallVector<unsigned, 8> ArgRegs;
1474   SmallVector<EVT, 8> ArgVTs;
1475   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1476   Args.reserve(CS.arg_size());
1477   ArgRegs.reserve(CS.arg_size());
1478   ArgVTs.reserve(CS.arg_size());
1479   ArgFlags.reserve(CS.arg_size());
1480   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1481        i != e; ++i) {
1482     unsigned Arg = getRegForValue(*i);
1483
1484     if (Arg == 0)
1485       return false;
1486     ISD::ArgFlagsTy Flags;
1487     unsigned AttrInd = i - CS.arg_begin() + 1;
1488     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1489       Flags.setSExt();
1490     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1491       Flags.setZExt();
1492
1493          // FIXME: Only handle *easy* calls for now.
1494     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1495         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1496         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1497         CS.paramHasAttr(AttrInd, Attribute::ByVal))
1498       return false;
1499
1500     const Type *ArgTy = (*i)->getType();
1501     EVT ArgVT;
1502     if (!isTypeLegal(ArgTy, ArgVT))
1503       return false;
1504     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1505     Flags.setOrigAlign(OriginalAlignment);
1506
1507     Args.push_back(*i);
1508     ArgRegs.push_back(Arg);
1509     ArgVTs.push_back(ArgVT);
1510     ArgFlags.push_back(Flags);
1511   }
1512
1513   // Handle the arguments now that we've gotten them.
1514   SmallVector<unsigned, 4> RegArgs;
1515   unsigned NumBytes;
1516   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1517     return false;
1518
1519   // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1520   // TODO: Turn this into the table of arm call ops.
1521   MachineInstrBuilder MIB;
1522   unsigned CallOpc;
1523   if(isThumb)
1524     CallOpc = Subtarget->isTargetDarwin() ? ARM::tBLXi_r9 : ARM::tBLXi;
1525   else
1526     CallOpc = Subtarget->isTargetDarwin() ? ARM::BLr9 : ARM::BL;
1527   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1528               .addGlobalAddress(GV, 0, 0);
1529
1530   // Add implicit physical register uses to the call.
1531   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1532     MIB.addReg(RegArgs[i]);
1533
1534   // Finish off the call including any return values.
1535   SmallVector<unsigned, 4> UsedRegs;
1536   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1537
1538   // Set all unused physreg defs as dead.
1539   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1540
1541   return true;
1542
1543 }
1544
1545 // TODO: SoftFP support.
1546 bool ARMFastISel::TargetSelectInstruction(const Instruction *I) {
1547   // No Thumb-1 for now.
1548   if (isThumb && !AFI->isThumb2Function()) return false;
1549
1550   switch (I->getOpcode()) {
1551     case Instruction::Load:
1552       return SelectLoad(I);
1553     case Instruction::Store:
1554       return SelectStore(I);
1555     case Instruction::Br:
1556       return SelectBranch(I);
1557     case Instruction::ICmp:
1558     case Instruction::FCmp:
1559       return SelectCmp(I);
1560     case Instruction::FPExt:
1561       return SelectFPExt(I);
1562     case Instruction::FPTrunc:
1563       return SelectFPTrunc(I);
1564     case Instruction::SIToFP:
1565       return SelectSIToFP(I);
1566     case Instruction::FPToSI:
1567       return SelectFPToSI(I);
1568     case Instruction::FAdd:
1569       return SelectBinaryOp(I, ISD::FADD);
1570     case Instruction::FSub:
1571       return SelectBinaryOp(I, ISD::FSUB);
1572     case Instruction::FMul:
1573       return SelectBinaryOp(I, ISD::FMUL);
1574     case Instruction::SDiv:
1575       return SelectSDiv(I);
1576     case Instruction::SRem:
1577       return SelectSRem(I);
1578     case Instruction::Call:
1579       return SelectCall(I);
1580     case Instruction::Select:
1581       return SelectSelect(I);
1582     default: break;
1583   }
1584   return false;
1585 }
1586
1587 namespace llvm {
1588   llvm::FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo) {
1589     // Completely untested on non-darwin.
1590     const TargetMachine &TM = funcInfo.MF->getTarget();
1591     const ARMSubtarget *Subtarget = &TM.getSubtarget<ARMSubtarget>();
1592     if (Subtarget->isTargetDarwin() && EnableARMFastISel)
1593       return new ARMFastISel(funcInfo);
1594     return 0;
1595   }
1596 }