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