Convert assert(0) to llvm_unreachable
[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 "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/IntrinsicInst.h"
29 #include "llvm/Module.h"
30 #include "llvm/Operator.h"
31 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/CodeGen/FastISel.h"
33 #include "llvm/CodeGen/FunctionLoweringInfo.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineConstantPool.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/Support/CallSite.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/GetElementPtrTypeIterator.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 using namespace llvm;
50
51 static cl::opt<bool>
52 DisableARMFastISel("disable-arm-fast-isel",
53                     cl::desc("Turn off experimental ARM fast-isel support"),
54                     cl::init(false), cl::Hidden);
55
56 extern cl::opt<bool> EnableARMLongCalls;
57
58 namespace {
59
60   // All possible address modes, plus some.
61   typedef struct Address {
62     enum {
63       RegBase,
64       FrameIndexBase
65     } BaseType;
66
67     union {
68       unsigned Reg;
69       int FI;
70     } Base;
71
72     int Offset;
73
74     // Innocuous defaults for our address.
75     Address()
76      : BaseType(RegBase), Offset(0) {
77        Base.Reg = 0;
78      }
79   } Address;
80
81 class ARMFastISel : public FastISel {
82
83   /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
84   /// make the right decision when generating code for different targets.
85   const ARMSubtarget *Subtarget;
86   const TargetMachine &TM;
87   const TargetInstrInfo &TII;
88   const TargetLowering &TLI;
89   ARMFunctionInfo *AFI;
90
91   // Convenience variables to avoid some queries.
92   bool isThumb2;
93   LLVMContext *Context;
94
95   public:
96     explicit ARMFastISel(FunctionLoweringInfo &funcInfo)
97     : FastISel(funcInfo),
98       TM(funcInfo.MF->getTarget()),
99       TII(*TM.getInstrInfo()),
100       TLI(*TM.getTargetLowering()) {
101       Subtarget = &TM.getSubtarget<ARMSubtarget>();
102       AFI = funcInfo.MF->getInfo<ARMFunctionInfo>();
103       isThumb2 = AFI->isThumbFunction();
104       Context = &funcInfo.Fn->getContext();
105     }
106
107     // Code from FastISel.cpp.
108     virtual unsigned FastEmitInst_(unsigned MachineInstOpcode,
109                                    const TargetRegisterClass *RC);
110     virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
111                                     const TargetRegisterClass *RC,
112                                     unsigned Op0, bool Op0IsKill);
113     virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
114                                      const TargetRegisterClass *RC,
115                                      unsigned Op0, bool Op0IsKill,
116                                      unsigned Op1, bool Op1IsKill);
117     virtual unsigned FastEmitInst_rrr(unsigned MachineInstOpcode,
118                                       const TargetRegisterClass *RC,
119                                       unsigned Op0, bool Op0IsKill,
120                                       unsigned Op1, bool Op1IsKill,
121                                       unsigned Op2, bool Op2IsKill);
122     virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
123                                      const TargetRegisterClass *RC,
124                                      unsigned Op0, bool Op0IsKill,
125                                      uint64_t Imm);
126     virtual unsigned FastEmitInst_rf(unsigned MachineInstOpcode,
127                                      const TargetRegisterClass *RC,
128                                      unsigned Op0, bool Op0IsKill,
129                                      const ConstantFP *FPImm);
130     virtual unsigned FastEmitInst_rri(unsigned MachineInstOpcode,
131                                       const TargetRegisterClass *RC,
132                                       unsigned Op0, bool Op0IsKill,
133                                       unsigned Op1, bool Op1IsKill,
134                                       uint64_t Imm);
135     virtual unsigned FastEmitInst_i(unsigned MachineInstOpcode,
136                                     const TargetRegisterClass *RC,
137                                     uint64_t Imm);
138     virtual unsigned FastEmitInst_ii(unsigned MachineInstOpcode,
139                                      const TargetRegisterClass *RC,
140                                      uint64_t Imm1, uint64_t Imm2);
141
142     virtual unsigned FastEmitInst_extractsubreg(MVT RetVT,
143                                                 unsigned Op0, bool Op0IsKill,
144                                                 uint32_t Idx);
145
146     // Backend specific FastISel code.
147     virtual bool TargetSelectInstruction(const Instruction *I);
148     virtual unsigned TargetMaterializeConstant(const Constant *C);
149     virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
150     virtual bool TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
151                                const LoadInst *LI);
152
153   #include "ARMGenFastISel.inc"
154
155     // Instruction selection routines.
156   private:
157     bool SelectLoad(const Instruction *I);
158     bool SelectStore(const Instruction *I);
159     bool SelectBranch(const Instruction *I);
160     bool SelectCmp(const Instruction *I);
161     bool SelectFPExt(const Instruction *I);
162     bool SelectFPTrunc(const Instruction *I);
163     bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
164     bool SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode);
165     bool SelectIToFP(const Instruction *I, bool isSigned);
166     bool SelectFPToI(const Instruction *I, bool isSigned);
167     bool SelectDiv(const Instruction *I, bool isSigned);
168     bool SelectRem(const Instruction *I, bool isSigned);
169     bool SelectCall(const Instruction *I, const char *IntrMemName);
170     bool SelectIntrinsicCall(const IntrinsicInst &I);
171     bool SelectSelect(const Instruction *I);
172     bool SelectRet(const Instruction *I);
173     bool SelectTrunc(const Instruction *I);
174     bool SelectIntExt(const Instruction *I);
175
176     // Utility routines.
177   private:
178     bool isTypeLegal(Type *Ty, MVT &VT);
179     bool isLoadTypeLegal(Type *Ty, MVT &VT);
180     bool ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
181                     bool isZExt);
182     bool ARMEmitLoad(EVT VT, unsigned &ResultReg, Address &Addr,
183                      unsigned Alignment = 0, bool isZExt = true,
184                      bool allocReg = true);
185                      
186     bool ARMEmitStore(EVT VT, unsigned SrcReg, Address &Addr,
187                       unsigned Alignment = 0);
188     bool ARMComputeAddress(const Value *Obj, Address &Addr);
189     void ARMSimplifyAddress(Address &Addr, EVT VT, bool useAM3);
190     bool ARMIsMemCpySmall(uint64_t Len);
191     bool ARMTryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len);
192     unsigned ARMEmitIntExt(EVT SrcVT, unsigned SrcReg, EVT DestVT, bool isZExt);
193     unsigned ARMMaterializeFP(const ConstantFP *CFP, EVT VT);
194     unsigned ARMMaterializeInt(const Constant *C, EVT VT);
195     unsigned ARMMaterializeGV(const GlobalValue *GV, EVT VT);
196     unsigned ARMMoveToFPReg(EVT VT, unsigned SrcReg);
197     unsigned ARMMoveToIntReg(EVT VT, unsigned SrcReg);
198     unsigned ARMSelectCallOp(const GlobalValue *GV);
199
200     // Call handling routines.
201   private:
202     CCAssignFn *CCAssignFnForCall(CallingConv::ID CC, bool Return);
203     bool ProcessCallArgs(SmallVectorImpl<Value*> &Args,
204                          SmallVectorImpl<unsigned> &ArgRegs,
205                          SmallVectorImpl<MVT> &ArgVTs,
206                          SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
207                          SmallVectorImpl<unsigned> &RegArgs,
208                          CallingConv::ID CC,
209                          unsigned &NumBytes);
210     bool FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
211                     const Instruction *I, CallingConv::ID CC,
212                     unsigned &NumBytes);
213     bool ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call);
214
215     // OptionalDef handling routines.
216   private:
217     bool isARMNEONPred(const MachineInstr *MI);
218     bool DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR);
219     const MachineInstrBuilder &AddOptionalDefs(const MachineInstrBuilder &MIB);
220     void AddLoadStoreOperands(EVT VT, Address &Addr,
221                               const MachineInstrBuilder &MIB,
222                               unsigned Flags, bool useAM3);
223 };
224
225 } // end anonymous namespace
226
227 #include "ARMGenCallingConv.inc"
228
229 // DefinesOptionalPredicate - This is different from DefinesPredicate in that
230 // we don't care about implicit defs here, just places we'll need to add a
231 // default CCReg argument. Sets CPSR if we're setting CPSR instead of CCR.
232 bool ARMFastISel::DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR) {
233   if (!MI->hasOptionalDef())
234     return false;
235
236   // Look to see if our OptionalDef is defining CPSR or CCR.
237   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
238     const MachineOperand &MO = MI->getOperand(i);
239     if (!MO.isReg() || !MO.isDef()) continue;
240     if (MO.getReg() == ARM::CPSR)
241       *CPSR = true;
242   }
243   return true;
244 }
245
246 bool ARMFastISel::isARMNEONPred(const MachineInstr *MI) {
247   const MCInstrDesc &MCID = MI->getDesc();
248
249   // If we're a thumb2 or not NEON function we were handled via isPredicable.
250   if ((MCID.TSFlags & ARMII::DomainMask) != ARMII::DomainNEON ||
251        AFI->isThumb2Function())
252     return false;
253
254   for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i)
255     if (MCID.OpInfo[i].isPredicate())
256       return true;
257
258   return false;
259 }
260
261 // If the machine is predicable go ahead and add the predicate operands, if
262 // it needs default CC operands add those.
263 // TODO: If we want to support thumb1 then we'll need to deal with optional
264 // CPSR defs that need to be added before the remaining operands. See s_cc_out
265 // for descriptions why.
266 const MachineInstrBuilder &
267 ARMFastISel::AddOptionalDefs(const MachineInstrBuilder &MIB) {
268   MachineInstr *MI = &*MIB;
269
270   // Do we use a predicate? or...
271   // Are we NEON in ARM mode and have a predicate operand? If so, I know
272   // we're not predicable but add it anyways.
273   if (TII.isPredicable(MI) || isARMNEONPred(MI))
274     AddDefaultPred(MIB);
275
276   // Do we optionally set a predicate?  Preds is size > 0 iff the predicate
277   // defines CPSR. All other OptionalDefines in ARM are the CCR register.
278   bool CPSR = false;
279   if (DefinesOptionalPredicate(MI, &CPSR)) {
280     if (CPSR)
281       AddDefaultT1CC(MIB);
282     else
283       AddDefaultCC(MIB);
284   }
285   return MIB;
286 }
287
288 unsigned ARMFastISel::FastEmitInst_(unsigned MachineInstOpcode,
289                                     const TargetRegisterClass* RC) {
290   unsigned ResultReg = createResultReg(RC);
291   const MCInstrDesc &II = TII.get(MachineInstOpcode);
292
293   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg));
294   return ResultReg;
295 }
296
297 unsigned ARMFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
298                                      const TargetRegisterClass *RC,
299                                      unsigned Op0, bool Op0IsKill) {
300   unsigned ResultReg = createResultReg(RC);
301   const MCInstrDesc &II = TII.get(MachineInstOpcode);
302
303   if (II.getNumDefs() >= 1)
304     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
305                    .addReg(Op0, Op0IsKill * RegState::Kill));
306   else {
307     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
308                    .addReg(Op0, Op0IsKill * RegState::Kill));
309     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
310                    TII.get(TargetOpcode::COPY), ResultReg)
311                    .addReg(II.ImplicitDefs[0]));
312   }
313   return ResultReg;
314 }
315
316 unsigned ARMFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
317                                       const TargetRegisterClass *RC,
318                                       unsigned Op0, bool Op0IsKill,
319                                       unsigned Op1, bool Op1IsKill) {
320   unsigned ResultReg = createResultReg(RC);
321   const MCInstrDesc &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   else {
328     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
329                    .addReg(Op0, Op0IsKill * RegState::Kill)
330                    .addReg(Op1, Op1IsKill * RegState::Kill));
331     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
332                            TII.get(TargetOpcode::COPY), ResultReg)
333                    .addReg(II.ImplicitDefs[0]));
334   }
335   return ResultReg;
336 }
337
338 unsigned ARMFastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
339                                        const TargetRegisterClass *RC,
340                                        unsigned Op0, bool Op0IsKill,
341                                        unsigned Op1, bool Op1IsKill,
342                                        unsigned Op2, bool Op2IsKill) {
343   unsigned ResultReg = createResultReg(RC);
344   const MCInstrDesc &II = TII.get(MachineInstOpcode);
345
346   if (II.getNumDefs() >= 1)
347     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
348                    .addReg(Op0, Op0IsKill * RegState::Kill)
349                    .addReg(Op1, Op1IsKill * RegState::Kill)
350                    .addReg(Op2, Op2IsKill * RegState::Kill));
351   else {
352     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
353                    .addReg(Op0, Op0IsKill * RegState::Kill)
354                    .addReg(Op1, Op1IsKill * RegState::Kill)
355                    .addReg(Op2, Op2IsKill * RegState::Kill));
356     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
357                            TII.get(TargetOpcode::COPY), ResultReg)
358                    .addReg(II.ImplicitDefs[0]));
359   }
360   return ResultReg;
361 }
362
363 unsigned ARMFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
364                                       const TargetRegisterClass *RC,
365                                       unsigned Op0, bool Op0IsKill,
366                                       uint64_t Imm) {
367   unsigned ResultReg = createResultReg(RC);
368   const MCInstrDesc &II = TII.get(MachineInstOpcode);
369
370   if (II.getNumDefs() >= 1)
371     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
372                    .addReg(Op0, Op0IsKill * RegState::Kill)
373                    .addImm(Imm));
374   else {
375     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
376                    .addReg(Op0, Op0IsKill * RegState::Kill)
377                    .addImm(Imm));
378     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
379                            TII.get(TargetOpcode::COPY), ResultReg)
380                    .addReg(II.ImplicitDefs[0]));
381   }
382   return ResultReg;
383 }
384
385 unsigned ARMFastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
386                                       const TargetRegisterClass *RC,
387                                       unsigned Op0, bool Op0IsKill,
388                                       const ConstantFP *FPImm) {
389   unsigned ResultReg = createResultReg(RC);
390   const MCInstrDesc &II = TII.get(MachineInstOpcode);
391
392   if (II.getNumDefs() >= 1)
393     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
394                    .addReg(Op0, Op0IsKill * RegState::Kill)
395                    .addFPImm(FPImm));
396   else {
397     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
398                    .addReg(Op0, Op0IsKill * RegState::Kill)
399                    .addFPImm(FPImm));
400     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
401                            TII.get(TargetOpcode::COPY), ResultReg)
402                    .addReg(II.ImplicitDefs[0]));
403   }
404   return ResultReg;
405 }
406
407 unsigned ARMFastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
408                                        const TargetRegisterClass *RC,
409                                        unsigned Op0, bool Op0IsKill,
410                                        unsigned Op1, bool Op1IsKill,
411                                        uint64_t Imm) {
412   unsigned ResultReg = createResultReg(RC);
413   const MCInstrDesc &II = TII.get(MachineInstOpcode);
414
415   if (II.getNumDefs() >= 1)
416     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
417                    .addReg(Op0, Op0IsKill * RegState::Kill)
418                    .addReg(Op1, Op1IsKill * RegState::Kill)
419                    .addImm(Imm));
420   else {
421     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
422                    .addReg(Op0, Op0IsKill * RegState::Kill)
423                    .addReg(Op1, Op1IsKill * RegState::Kill)
424                    .addImm(Imm));
425     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
426                            TII.get(TargetOpcode::COPY), ResultReg)
427                    .addReg(II.ImplicitDefs[0]));
428   }
429   return ResultReg;
430 }
431
432 unsigned ARMFastISel::FastEmitInst_i(unsigned MachineInstOpcode,
433                                      const TargetRegisterClass *RC,
434                                      uint64_t Imm) {
435   unsigned ResultReg = createResultReg(RC);
436   const MCInstrDesc &II = TII.get(MachineInstOpcode);
437
438   if (II.getNumDefs() >= 1)
439     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
440                    .addImm(Imm));
441   else {
442     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
443                    .addImm(Imm));
444     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
445                            TII.get(TargetOpcode::COPY), ResultReg)
446                    .addReg(II.ImplicitDefs[0]));
447   }
448   return ResultReg;
449 }
450
451 unsigned ARMFastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
452                                       const TargetRegisterClass *RC,
453                                       uint64_t Imm1, uint64_t Imm2) {
454   unsigned ResultReg = createResultReg(RC);
455   const MCInstrDesc &II = TII.get(MachineInstOpcode);
456
457   if (II.getNumDefs() >= 1)
458     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
459                     .addImm(Imm1).addImm(Imm2));
460   else {
461     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
462                     .addImm(Imm1).addImm(Imm2));
463     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
464                             TII.get(TargetOpcode::COPY),
465                             ResultReg)
466                     .addReg(II.ImplicitDefs[0]));
467   }
468   return ResultReg;
469 }
470
471 unsigned ARMFastISel::FastEmitInst_extractsubreg(MVT RetVT,
472                                                  unsigned Op0, bool Op0IsKill,
473                                                  uint32_t Idx) {
474   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
475   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
476          "Cannot yet extract from physregs");
477   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
478                          DL, TII.get(TargetOpcode::COPY), ResultReg)
479                  .addReg(Op0, getKillRegState(Op0IsKill), Idx));
480   return ResultReg;
481 }
482
483 // TODO: Don't worry about 64-bit now, but when this is fixed remove the
484 // checks from the various callers.
485 unsigned ARMFastISel::ARMMoveToFPReg(EVT VT, unsigned SrcReg) {
486   if (VT == MVT::f64) return 0;
487
488   unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
489   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
490                           TII.get(ARM::VMOVRS), MoveReg)
491                   .addReg(SrcReg));
492   return MoveReg;
493 }
494
495 unsigned ARMFastISel::ARMMoveToIntReg(EVT VT, unsigned SrcReg) {
496   if (VT == MVT::i64) return 0;
497
498   unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
499   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
500                           TII.get(ARM::VMOVSR), MoveReg)
501                   .addReg(SrcReg));
502   return MoveReg;
503 }
504
505 // For double width floating point we need to materialize two constants
506 // (the high and the low) into integer registers then use a move to get
507 // the combined constant into an FP reg.
508 unsigned ARMFastISel::ARMMaterializeFP(const ConstantFP *CFP, EVT VT) {
509   const APFloat Val = CFP->getValueAPF();
510   bool is64bit = VT == MVT::f64;
511
512   // This checks to see if we can use VFP3 instructions to materialize
513   // a constant, otherwise we have to go through the constant pool.
514   if (TLI.isFPImmLegal(Val, VT)) {
515     int Imm;
516     unsigned Opc;
517     if (is64bit) {
518       Imm = ARM_AM::getFP64Imm(Val);
519       Opc = ARM::FCONSTD;
520     } else {
521       Imm = ARM_AM::getFP32Imm(Val);
522       Opc = ARM::FCONSTS;
523     }
524     unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
525     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
526                             DestReg)
527                     .addImm(Imm));
528     return DestReg;
529   }
530
531   // Require VFP2 for loading fp constants.
532   if (!Subtarget->hasVFP2()) return false;
533
534   // MachineConstantPool wants an explicit alignment.
535   unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
536   if (Align == 0) {
537     // TODO: Figure out if this is correct.
538     Align = TD.getTypeAllocSize(CFP->getType());
539   }
540   unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
541   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
542   unsigned Opc = is64bit ? ARM::VLDRD : ARM::VLDRS;
543
544   // The extra reg is for addrmode5.
545   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
546                           DestReg)
547                   .addConstantPoolIndex(Idx)
548                   .addReg(0));
549   return DestReg;
550 }
551
552 unsigned ARMFastISel::ARMMaterializeInt(const Constant *C, EVT VT) {
553
554   if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8 && VT != MVT::i1)
555     return false;
556
557   // If we can do this in a single instruction without a constant pool entry
558   // do so now.
559   const ConstantInt *CI = cast<ConstantInt>(C);
560   if (Subtarget->hasV6T2Ops() && isUInt<16>(CI->getZExtValue())) {
561     unsigned Opc = isThumb2 ? ARM::t2MOVi16 : ARM::MOVi16;
562     unsigned ImmReg = createResultReg(TLI.getRegClassFor(MVT::i32));
563     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
564                             TII.get(Opc), ImmReg)
565                     .addImm(CI->getZExtValue()));
566     return ImmReg;
567   }
568
569   // Use MVN to emit negative constants.
570   if (VT == MVT::i32 && Subtarget->hasV6T2Ops() && CI->isNegative()) {
571     unsigned Imm = (unsigned)~(CI->getSExtValue());
572     bool UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
573       (ARM_AM::getSOImmVal(Imm) != -1);
574     if (UseImm) {
575       unsigned Opc = isThumb2 ? ARM::t2MVNi : ARM::MVNi;
576       unsigned ImmReg = createResultReg(TLI.getRegClassFor(MVT::i32));
577       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
578                               TII.get(Opc), ImmReg)
579                       .addImm(Imm));
580       return ImmReg;
581     }
582   }
583
584   // Load from constant pool.  For now 32-bit only.
585   if (VT != MVT::i32)
586     return false;
587
588   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
589
590   // MachineConstantPool wants an explicit alignment.
591   unsigned Align = TD.getPrefTypeAlignment(C->getType());
592   if (Align == 0) {
593     // TODO: Figure out if this is correct.
594     Align = TD.getTypeAllocSize(C->getType());
595   }
596   unsigned Idx = MCP.getConstantPoolIndex(C, Align);
597
598   if (isThumb2)
599     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
600                             TII.get(ARM::t2LDRpci), DestReg)
601                     .addConstantPoolIndex(Idx));
602   else
603     // The extra immediate is for addrmode2.
604     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
605                             TII.get(ARM::LDRcp), DestReg)
606                     .addConstantPoolIndex(Idx)
607                     .addImm(0));
608
609   return DestReg;
610 }
611
612 unsigned ARMFastISel::ARMMaterializeGV(const GlobalValue *GV, EVT VT) {
613   // For now 32-bit only.
614   if (VT != MVT::i32) return 0;
615
616   Reloc::Model RelocM = TM.getRelocationModel();
617
618   // TODO: Need more magic for ARM PIC.
619   if (!isThumb2 && (RelocM == Reloc::PIC_)) return 0;
620
621   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
622
623   // Use movw+movt when possible, it avoids constant pool entries.
624   // Darwin targets don't support movt with Reloc::Static, see
625   // ARMTargetLowering::LowerGlobalAddressDarwin.  Other targets only support
626   // static movt relocations.
627   if (Subtarget->useMovt() &&
628       Subtarget->isTargetDarwin() == (RelocM != Reloc::Static)) {
629     unsigned Opc;
630     switch (RelocM) {
631     case Reloc::PIC_:
632       Opc = isThumb2 ? ARM::t2MOV_ga_pcrel : ARM::MOV_ga_pcrel;
633       break;
634     case Reloc::DynamicNoPIC:
635       Opc = isThumb2 ? ARM::t2MOV_ga_dyn : ARM::MOV_ga_dyn;
636       break;
637     default:
638       Opc = isThumb2 ? ARM::t2MOVi32imm : ARM::MOVi32imm;
639       break;
640     }
641     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
642                             DestReg).addGlobalAddress(GV));
643   } else {
644     // MachineConstantPool wants an explicit alignment.
645     unsigned Align = TD.getPrefTypeAlignment(GV->getType());
646     if (Align == 0) {
647       // TODO: Figure out if this is correct.
648       Align = TD.getTypeAllocSize(GV->getType());
649     }
650
651     // Grab index.
652     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 :
653       (Subtarget->isThumb() ? 4 : 8);
654     unsigned Id = AFI->createPICLabelUId();
655     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(GV, Id,
656                                                                 ARMCP::CPValue,
657                                                                 PCAdj);
658     unsigned Idx = MCP.getConstantPoolIndex(CPV, Align);
659
660     // Load value.
661     MachineInstrBuilder MIB;
662     if (isThumb2) {
663       unsigned Opc = (RelocM!=Reloc::PIC_) ? ARM::t2LDRpci : ARM::t2LDRpci_pic;
664       MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
665         .addConstantPoolIndex(Idx);
666       if (RelocM == Reloc::PIC_)
667         MIB.addImm(Id);
668     } else {
669       // The extra immediate is for addrmode2.
670       MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::LDRcp),
671                     DestReg)
672         .addConstantPoolIndex(Idx)
673         .addImm(0);
674     }
675     AddOptionalDefs(MIB);
676   }
677
678   if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) {
679     MachineInstrBuilder MIB;
680     unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
681     if (isThumb2)
682       MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
683                     TII.get(ARM::t2LDRi12), NewDestReg)
684             .addReg(DestReg)
685             .addImm(0);
686     else
687       MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::LDRi12),
688                     NewDestReg)
689             .addReg(DestReg)
690             .addImm(0);
691     DestReg = NewDestReg;
692     AddOptionalDefs(MIB);
693   }
694
695   return DestReg;
696 }
697
698 unsigned ARMFastISel::TargetMaterializeConstant(const Constant *C) {
699   EVT VT = TLI.getValueType(C->getType(), true);
700
701   // Only handle simple types.
702   if (!VT.isSimple()) return 0;
703
704   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
705     return ARMMaterializeFP(CFP, VT);
706   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
707     return ARMMaterializeGV(GV, VT);
708   else if (isa<ConstantInt>(C))
709     return ARMMaterializeInt(C, VT);
710
711   return 0;
712 }
713
714 // TODO: unsigned ARMFastISel::TargetMaterializeFloatZero(const ConstantFP *CF);
715
716 unsigned ARMFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
717   // Don't handle dynamic allocas.
718   if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
719
720   MVT VT;
721   if (!isLoadTypeLegal(AI->getType(), VT)) return false;
722
723   DenseMap<const AllocaInst*, int>::iterator SI =
724     FuncInfo.StaticAllocaMap.find(AI);
725
726   // This will get lowered later into the correct offsets and registers
727   // via rewriteXFrameIndex.
728   if (SI != FuncInfo.StaticAllocaMap.end()) {
729     TargetRegisterClass* RC = TLI.getRegClassFor(VT);
730     unsigned ResultReg = createResultReg(RC);
731     unsigned Opc = isThumb2 ? ARM::t2ADDri : ARM::ADDri;
732     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
733                             TII.get(Opc), ResultReg)
734                             .addFrameIndex(SI->second)
735                             .addImm(0));
736     return ResultReg;
737   }
738
739   return 0;
740 }
741
742 bool ARMFastISel::isTypeLegal(Type *Ty, MVT &VT) {
743   EVT evt = TLI.getValueType(Ty, true);
744
745   // Only handle simple types.
746   if (evt == MVT::Other || !evt.isSimple()) return false;
747   VT = evt.getSimpleVT();
748
749   // Handle all legal types, i.e. a register that will directly hold this
750   // value.
751   return TLI.isTypeLegal(VT);
752 }
753
754 bool ARMFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
755   if (isTypeLegal(Ty, VT)) return true;
756
757   // If this is a type than can be sign or zero-extended to a basic operation
758   // go ahead and accept it now.
759   if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
760     return true;
761
762   return false;
763 }
764
765 // Computes the address to get to an object.
766 bool ARMFastISel::ARMComputeAddress(const Value *Obj, Address &Addr) {
767   // Some boilerplate from the X86 FastISel.
768   const User *U = NULL;
769   unsigned Opcode = Instruction::UserOp1;
770   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
771     // Don't walk into other basic blocks unless the object is an alloca from
772     // another block, otherwise it may not have a virtual register assigned.
773     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
774         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
775       Opcode = I->getOpcode();
776       U = I;
777     }
778   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
779     Opcode = C->getOpcode();
780     U = C;
781   }
782
783   if (PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
784     if (Ty->getAddressSpace() > 255)
785       // Fast instruction selection doesn't support the special
786       // address spaces.
787       return false;
788
789   switch (Opcode) {
790     default:
791     break;
792     case Instruction::BitCast: {
793       // Look through bitcasts.
794       return ARMComputeAddress(U->getOperand(0), Addr);
795     }
796     case Instruction::IntToPtr: {
797       // Look past no-op inttoptrs.
798       if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
799         return ARMComputeAddress(U->getOperand(0), Addr);
800       break;
801     }
802     case Instruction::PtrToInt: {
803       // Look past no-op ptrtoints.
804       if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
805         return ARMComputeAddress(U->getOperand(0), Addr);
806       break;
807     }
808     case Instruction::GetElementPtr: {
809       Address SavedAddr = Addr;
810       int TmpOffset = Addr.Offset;
811
812       // Iterate through the GEP folding the constants into offsets where
813       // we can.
814       gep_type_iterator GTI = gep_type_begin(U);
815       for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
816            i != e; ++i, ++GTI) {
817         const Value *Op = *i;
818         if (StructType *STy = dyn_cast<StructType>(*GTI)) {
819           const StructLayout *SL = TD.getStructLayout(STy);
820           unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
821           TmpOffset += SL->getElementOffset(Idx);
822         } else {
823           uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
824           for (;;) {
825             if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
826               // Constant-offset addressing.
827               TmpOffset += CI->getSExtValue() * S;
828               break;
829             }
830             if (isa<AddOperator>(Op) &&
831                 (!isa<Instruction>(Op) ||
832                  FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
833                  == FuncInfo.MBB) &&
834                 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
835               // An add (in the same block) with a constant operand. Fold the
836               // constant.
837               ConstantInt *CI =
838               cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
839               TmpOffset += CI->getSExtValue() * S;
840               // Iterate on the other operand.
841               Op = cast<AddOperator>(Op)->getOperand(0);
842               continue;
843             }
844             // Unsupported
845             goto unsupported_gep;
846           }
847         }
848       }
849
850       // Try to grab the base operand now.
851       Addr.Offset = TmpOffset;
852       if (ARMComputeAddress(U->getOperand(0), Addr)) return true;
853
854       // We failed, restore everything and try the other options.
855       Addr = SavedAddr;
856
857       unsupported_gep:
858       break;
859     }
860     case Instruction::Alloca: {
861       const AllocaInst *AI = cast<AllocaInst>(Obj);
862       DenseMap<const AllocaInst*, int>::iterator SI =
863         FuncInfo.StaticAllocaMap.find(AI);
864       if (SI != FuncInfo.StaticAllocaMap.end()) {
865         Addr.BaseType = Address::FrameIndexBase;
866         Addr.Base.FI = SI->second;
867         return true;
868       }
869       break;
870     }
871   }
872
873   // Try to get this in a register if nothing else has worked.
874   if (Addr.Base.Reg == 0) Addr.Base.Reg = getRegForValue(Obj);
875   return Addr.Base.Reg != 0;
876 }
877
878 void ARMFastISel::ARMSimplifyAddress(Address &Addr, EVT VT, bool useAM3) {
879
880   assert(VT.isSimple() && "Non-simple types are invalid here!");
881
882   bool needsLowering = false;
883   switch (VT.getSimpleVT().SimpleTy) {
884     default: llvm_unreachable("Unhandled load/store type!");
885     case MVT::i1:
886     case MVT::i8:
887     case MVT::i16:
888     case MVT::i32:
889       if (!useAM3) {
890         // Integer loads/stores handle 12-bit offsets.
891         needsLowering = ((Addr.Offset & 0xfff) != Addr.Offset);
892         // Handle negative offsets.
893         if (needsLowering && isThumb2)
894           needsLowering = !(Subtarget->hasV6T2Ops() && Addr.Offset < 0 &&
895                             Addr.Offset > -256);
896       } else {
897         // ARM halfword load/stores and signed byte loads use +/-imm8 offsets.
898         needsLowering = (Addr.Offset > 255 || Addr.Offset < -255);
899       }
900       break;
901     case MVT::f32:
902     case MVT::f64:
903       // Floating point operands handle 8-bit offsets.
904       needsLowering = ((Addr.Offset & 0xff) != Addr.Offset);
905       break;
906   }
907
908   // If this is a stack pointer and the offset needs to be simplified then
909   // put the alloca address into a register, set the base type back to
910   // register and continue. This should almost never happen.
911   if (needsLowering && Addr.BaseType == Address::FrameIndexBase) {
912     TargetRegisterClass *RC = isThumb2 ? ARM::tGPRRegisterClass :
913                               ARM::GPRRegisterClass;
914     unsigned ResultReg = createResultReg(RC);
915     unsigned Opc = isThumb2 ? ARM::t2ADDri : ARM::ADDri;
916     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
917                             TII.get(Opc), ResultReg)
918                             .addFrameIndex(Addr.Base.FI)
919                             .addImm(0));
920     Addr.Base.Reg = ResultReg;
921     Addr.BaseType = Address::RegBase;
922   }
923
924   // Since the offset is too large for the load/store instruction
925   // get the reg+offset into a register.
926   if (needsLowering) {
927     Addr.Base.Reg = FastEmit_ri_(MVT::i32, ISD::ADD, Addr.Base.Reg,
928                                  /*Op0IsKill*/false, Addr.Offset, MVT::i32);
929     Addr.Offset = 0;
930   }
931 }
932
933 void ARMFastISel::AddLoadStoreOperands(EVT VT, Address &Addr,
934                                        const MachineInstrBuilder &MIB,
935                                        unsigned Flags, bool useAM3) {
936   // addrmode5 output depends on the selection dag addressing dividing the
937   // offset by 4 that it then later multiplies. Do this here as well.
938   if (VT.getSimpleVT().SimpleTy == MVT::f32 ||
939       VT.getSimpleVT().SimpleTy == MVT::f64)
940     Addr.Offset /= 4;
941
942   // Frame base works a bit differently. Handle it separately.
943   if (Addr.BaseType == Address::FrameIndexBase) {
944     int FI = Addr.Base.FI;
945     int Offset = Addr.Offset;
946     MachineMemOperand *MMO =
947           FuncInfo.MF->getMachineMemOperand(
948                                   MachinePointerInfo::getFixedStack(FI, Offset),
949                                   Flags,
950                                   MFI.getObjectSize(FI),
951                                   MFI.getObjectAlignment(FI));
952     // Now add the rest of the operands.
953     MIB.addFrameIndex(FI);
954
955     // ARM halfword load/stores and signed byte loads need an additional
956     // operand.
957     if (useAM3) {
958       signed Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
959       MIB.addReg(0);
960       MIB.addImm(Imm);
961     } else {
962       MIB.addImm(Addr.Offset);
963     }
964     MIB.addMemOperand(MMO);
965   } else {
966     // Now add the rest of the operands.
967     MIB.addReg(Addr.Base.Reg);
968
969     // ARM halfword load/stores and signed byte loads need an additional
970     // operand.
971     if (useAM3) {
972       signed Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
973       MIB.addReg(0);
974       MIB.addImm(Imm);
975     } else {
976       MIB.addImm(Addr.Offset);
977     }
978   }
979   AddOptionalDefs(MIB);
980 }
981
982 bool ARMFastISel::ARMEmitLoad(EVT VT, unsigned &ResultReg, Address &Addr,
983                               unsigned Alignment, bool isZExt, bool allocReg) {
984   assert(VT.isSimple() && "Non-simple types are invalid here!");
985   unsigned Opc;
986   bool useAM3 = false;
987   bool needVMOV = false;
988   TargetRegisterClass *RC;  
989   switch (VT.getSimpleVT().SimpleTy) {
990     // This is mostly going to be Neon/vector support.
991     default: return false;
992     case MVT::i1:
993     case MVT::i8:
994       if (isThumb2) {
995         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
996           Opc = isZExt ? ARM::t2LDRBi8 : ARM::t2LDRSBi8;
997         else
998           Opc = isZExt ? ARM::t2LDRBi12 : ARM::t2LDRSBi12;
999       } else {
1000         if (isZExt) {
1001           Opc = ARM::LDRBi12;
1002         } else {
1003           Opc = ARM::LDRSB;
1004           useAM3 = true;
1005         }
1006       }
1007       RC = ARM::GPRRegisterClass;
1008       break;
1009     case MVT::i16:
1010       if (isThumb2) {
1011         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1012           Opc = isZExt ? ARM::t2LDRHi8 : ARM::t2LDRSHi8;
1013         else
1014           Opc = isZExt ? ARM::t2LDRHi12 : ARM::t2LDRSHi12;
1015       } else {
1016         Opc = isZExt ? ARM::LDRH : ARM::LDRSH;
1017         useAM3 = true;
1018       }
1019       RC = ARM::GPRRegisterClass;
1020       break;
1021     case MVT::i32:
1022       if (isThumb2) {
1023         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1024           Opc = ARM::t2LDRi8;
1025         else
1026           Opc = ARM::t2LDRi12;
1027       } else {
1028         Opc = ARM::LDRi12;
1029       }
1030       RC = ARM::GPRRegisterClass;
1031       break;
1032     case MVT::f32:
1033       if (!Subtarget->hasVFP2()) return false;
1034       // Unaligned loads need special handling. Floats require word-alignment.
1035       if (Alignment && Alignment < 4) {
1036         needVMOV = true;
1037         VT = MVT::i32;
1038         Opc = isThumb2 ? ARM::t2LDRi12 : ARM::LDRi12;
1039         RC = ARM::GPRRegisterClass;
1040       } else {
1041         Opc = ARM::VLDRS;
1042         RC = TLI.getRegClassFor(VT);
1043       }
1044       break;
1045     case MVT::f64:
1046       if (!Subtarget->hasVFP2()) return false;
1047       // FIXME: Unaligned loads need special handling.  Doublewords require
1048       // word-alignment.
1049       if (Alignment && Alignment < 4)
1050         return false;
1051
1052       Opc = ARM::VLDRD;
1053       RC = TLI.getRegClassFor(VT);
1054       break;
1055   }
1056   // Simplify this down to something we can handle.
1057   ARMSimplifyAddress(Addr, VT, useAM3);
1058
1059   // Create the base instruction, then add the operands.
1060   if (allocReg)
1061     ResultReg = createResultReg(RC);
1062   assert (ResultReg > 255 && "Expected an allocated virtual register.");
1063   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1064                                     TII.get(Opc), ResultReg);
1065   AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOLoad, useAM3);
1066
1067   // If we had an unaligned load of a float we've converted it to an regular
1068   // load.  Now we must move from the GRP to the FP register.
1069   if (needVMOV) {
1070     unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1071     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1072                             TII.get(ARM::VMOVSR), MoveReg)
1073                     .addReg(ResultReg));
1074     ResultReg = MoveReg;
1075   }
1076   return true;
1077 }
1078
1079 bool ARMFastISel::SelectLoad(const Instruction *I) {
1080   // Atomic loads need special handling.
1081   if (cast<LoadInst>(I)->isAtomic())
1082     return false;
1083
1084   // Verify we have a legal type before going any further.
1085   MVT VT;
1086   if (!isLoadTypeLegal(I->getType(), VT))
1087     return false;
1088
1089   // See if we can handle this address.
1090   Address Addr;
1091   if (!ARMComputeAddress(I->getOperand(0), Addr)) return false;
1092
1093   unsigned ResultReg;
1094   if (!ARMEmitLoad(VT, ResultReg, Addr, cast<LoadInst>(I)->getAlignment()))
1095     return false;
1096   UpdateValueMap(I, ResultReg);
1097   return true;
1098 }
1099
1100 bool ARMFastISel::ARMEmitStore(EVT VT, unsigned SrcReg, Address &Addr,
1101                                unsigned Alignment) {
1102   unsigned StrOpc;
1103   bool useAM3 = false;
1104   switch (VT.getSimpleVT().SimpleTy) {
1105     // This is mostly going to be Neon/vector support.
1106     default: return false;
1107     case MVT::i1: {
1108       unsigned Res = createResultReg(isThumb2 ? ARM::tGPRRegisterClass :
1109                                                ARM::GPRRegisterClass);
1110       unsigned Opc = isThumb2 ? ARM::t2ANDri : ARM::ANDri;
1111       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1112                               TII.get(Opc), Res)
1113                       .addReg(SrcReg).addImm(1));
1114       SrcReg = Res;
1115     } // Fallthrough here.
1116     case MVT::i8:
1117       if (isThumb2) {
1118         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1119           StrOpc = ARM::t2STRBi8;
1120         else
1121           StrOpc = ARM::t2STRBi12;
1122       } else {
1123         StrOpc = ARM::STRBi12;
1124       }
1125       break;
1126     case MVT::i16:
1127       if (isThumb2) {
1128         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1129           StrOpc = ARM::t2STRHi8;
1130         else
1131           StrOpc = ARM::t2STRHi12;
1132       } else {
1133         StrOpc = ARM::STRH;
1134         useAM3 = true;
1135       }
1136       break;
1137     case MVT::i32:
1138       if (isThumb2) {
1139         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1140           StrOpc = ARM::t2STRi8;
1141         else
1142           StrOpc = ARM::t2STRi12;
1143       } else {
1144         StrOpc = ARM::STRi12;
1145       }
1146       break;
1147     case MVT::f32:
1148       if (!Subtarget->hasVFP2()) return false;
1149       // Unaligned stores need special handling. Floats require word-alignment.
1150       if (Alignment && Alignment < 4) {
1151         unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::i32));
1152         AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1153                                 TII.get(ARM::VMOVRS), MoveReg)
1154                         .addReg(SrcReg));
1155         SrcReg = MoveReg;
1156         VT = MVT::i32;
1157         StrOpc = isThumb2 ? ARM::t2STRi12 : ARM::STRi12;
1158       } else {
1159         StrOpc = ARM::VSTRS;
1160       }
1161       break;
1162     case MVT::f64:
1163       if (!Subtarget->hasVFP2()) return false;
1164       // FIXME: Unaligned stores need special handling.  Doublewords require
1165       // word-alignment.
1166       if (Alignment && Alignment < 4)
1167           return false;
1168
1169       StrOpc = ARM::VSTRD;
1170       break;
1171   }
1172   // Simplify this down to something we can handle.
1173   ARMSimplifyAddress(Addr, VT, useAM3);
1174
1175   // Create the base instruction, then add the operands.
1176   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1177                                     TII.get(StrOpc))
1178                             .addReg(SrcReg);
1179   AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOStore, useAM3);
1180   return true;
1181 }
1182
1183 bool ARMFastISel::SelectStore(const Instruction *I) {
1184   Value *Op0 = I->getOperand(0);
1185   unsigned SrcReg = 0;
1186
1187   // Atomic stores need special handling.
1188   if (cast<StoreInst>(I)->isAtomic())
1189     return false;
1190
1191   // Verify we have a legal type before going any further.
1192   MVT VT;
1193   if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
1194     return false;
1195
1196   // Get the value to be stored into a register.
1197   SrcReg = getRegForValue(Op0);
1198   if (SrcReg == 0) return false;
1199
1200   // See if we can handle this address.
1201   Address Addr;
1202   if (!ARMComputeAddress(I->getOperand(1), Addr))
1203     return false;
1204
1205   if (!ARMEmitStore(VT, SrcReg, Addr, cast<StoreInst>(I)->getAlignment()))
1206     return false;
1207   return true;
1208 }
1209
1210 static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
1211   switch (Pred) {
1212     // Needs two compares...
1213     case CmpInst::FCMP_ONE:
1214     case CmpInst::FCMP_UEQ:
1215     default:
1216       // AL is our "false" for now. The other two need more compares.
1217       return ARMCC::AL;
1218     case CmpInst::ICMP_EQ:
1219     case CmpInst::FCMP_OEQ:
1220       return ARMCC::EQ;
1221     case CmpInst::ICMP_SGT:
1222     case CmpInst::FCMP_OGT:
1223       return ARMCC::GT;
1224     case CmpInst::ICMP_SGE:
1225     case CmpInst::FCMP_OGE:
1226       return ARMCC::GE;
1227     case CmpInst::ICMP_UGT:
1228     case CmpInst::FCMP_UGT:
1229       return ARMCC::HI;
1230     case CmpInst::FCMP_OLT:
1231       return ARMCC::MI;
1232     case CmpInst::ICMP_ULE:
1233     case CmpInst::FCMP_OLE:
1234       return ARMCC::LS;
1235     case CmpInst::FCMP_ORD:
1236       return ARMCC::VC;
1237     case CmpInst::FCMP_UNO:
1238       return ARMCC::VS;
1239     case CmpInst::FCMP_UGE:
1240       return ARMCC::PL;
1241     case CmpInst::ICMP_SLT:
1242     case CmpInst::FCMP_ULT:
1243       return ARMCC::LT;
1244     case CmpInst::ICMP_SLE:
1245     case CmpInst::FCMP_ULE:
1246       return ARMCC::LE;
1247     case CmpInst::FCMP_UNE:
1248     case CmpInst::ICMP_NE:
1249       return ARMCC::NE;
1250     case CmpInst::ICMP_UGE:
1251       return ARMCC::HS;
1252     case CmpInst::ICMP_ULT:
1253       return ARMCC::LO;
1254   }
1255 }
1256
1257 bool ARMFastISel::SelectBranch(const Instruction *I) {
1258   const BranchInst *BI = cast<BranchInst>(I);
1259   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1260   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1261
1262   // Simple branch support.
1263
1264   // If we can, avoid recomputing the compare - redoing it could lead to wonky
1265   // behavior.
1266   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1267     if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
1268
1269       // Get the compare predicate.
1270       // Try to take advantage of fallthrough opportunities.
1271       CmpInst::Predicate Predicate = CI->getPredicate();
1272       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1273         std::swap(TBB, FBB);
1274         Predicate = CmpInst::getInversePredicate(Predicate);
1275       }
1276
1277       ARMCC::CondCodes ARMPred = getComparePred(Predicate);
1278
1279       // We may not handle every CC for now.
1280       if (ARMPred == ARMCC::AL) return false;
1281
1282       // Emit the compare.
1283       if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1284         return false;
1285
1286       unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1287       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1288       .addMBB(TBB).addImm(ARMPred).addReg(ARM::CPSR);
1289       FastEmitBranch(FBB, DL);
1290       FuncInfo.MBB->addSuccessor(TBB);
1291       return true;
1292     }
1293   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1294     MVT SourceVT;
1295     if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1296         (isLoadTypeLegal(TI->getOperand(0)->getType(), SourceVT))) {
1297       unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1298       unsigned OpReg = getRegForValue(TI->getOperand(0));
1299       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1300                               TII.get(TstOpc))
1301                       .addReg(OpReg).addImm(1));
1302
1303       unsigned CCMode = ARMCC::NE;
1304       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1305         std::swap(TBB, FBB);
1306         CCMode = ARMCC::EQ;
1307       }
1308
1309       unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1310       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1311       .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1312
1313       FastEmitBranch(FBB, DL);
1314       FuncInfo.MBB->addSuccessor(TBB);
1315       return true;
1316     }
1317   } else if (const ConstantInt *CI =
1318              dyn_cast<ConstantInt>(BI->getCondition())) {
1319     uint64_t Imm = CI->getZExtValue();
1320     MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
1321     FastEmitBranch(Target, DL);
1322     return true;
1323   }
1324
1325   unsigned CmpReg = getRegForValue(BI->getCondition());
1326   if (CmpReg == 0) return false;
1327
1328   // We've been divorced from our compare!  Our block was split, and
1329   // now our compare lives in a predecessor block.  We musn't
1330   // re-compare here, as the children of the compare aren't guaranteed
1331   // live across the block boundary (we *could* check for this).
1332   // Regardless, the compare has been done in the predecessor block,
1333   // and it left a value for us in a virtual register.  Ergo, we test
1334   // the one-bit value left in the virtual register.
1335   unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1336   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TstOpc))
1337                   .addReg(CmpReg).addImm(1));
1338
1339   unsigned CCMode = ARMCC::NE;
1340   if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1341     std::swap(TBB, FBB);
1342     CCMode = ARMCC::EQ;
1343   }
1344
1345   unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1346   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1347                   .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1348   FastEmitBranch(FBB, DL);
1349   FuncInfo.MBB->addSuccessor(TBB);
1350   return true;
1351 }
1352
1353 bool ARMFastISel::ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
1354                              bool isZExt) {
1355   Type *Ty = Src1Value->getType();
1356   EVT SrcVT = TLI.getValueType(Ty, true);
1357   if (!SrcVT.isSimple()) return false;
1358
1359   bool isFloat = (Ty->isFloatTy() || Ty->isDoubleTy());
1360   if (isFloat && !Subtarget->hasVFP2())
1361     return false;
1362
1363   // Check to see if the 2nd operand is a constant that we can encode directly
1364   // in the compare.
1365   int Imm = 0;
1366   bool UseImm = false;
1367   bool isNegativeImm = false;
1368   // FIXME: At -O0 we don't have anything that canonicalizes operand order.
1369   // Thus, Src1Value may be a ConstantInt, but we're missing it.
1370   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
1371     if (SrcVT == MVT::i32 || SrcVT == MVT::i16 || SrcVT == MVT::i8 ||
1372         SrcVT == MVT::i1) {
1373       const APInt &CIVal = ConstInt->getValue();
1374       Imm = (isZExt) ? (int)CIVal.getZExtValue() : (int)CIVal.getSExtValue();
1375       if (Imm < 0) {
1376         isNegativeImm = true;
1377         Imm = -Imm;
1378       }
1379       UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1380         (ARM_AM::getSOImmVal(Imm) != -1);
1381     }
1382   } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
1383     if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
1384       if (ConstFP->isZero() && !ConstFP->isNegative())
1385         UseImm = true;
1386   }
1387
1388   unsigned CmpOpc;
1389   bool isICmp = true;
1390   bool needsExt = false;
1391   switch (SrcVT.getSimpleVT().SimpleTy) {
1392     default: return false;
1393     // TODO: Verify compares.
1394     case MVT::f32:
1395       isICmp = false;
1396       CmpOpc = UseImm ? ARM::VCMPEZS : ARM::VCMPES;
1397       break;
1398     case MVT::f64:
1399       isICmp = false;
1400       CmpOpc = UseImm ? ARM::VCMPEZD : ARM::VCMPED;
1401       break;
1402     case MVT::i1:
1403     case MVT::i8:
1404     case MVT::i16:
1405       needsExt = true;
1406     // Intentional fall-through.
1407     case MVT::i32:
1408       if (isThumb2) {
1409         if (!UseImm)
1410           CmpOpc = ARM::t2CMPrr;
1411         else
1412           CmpOpc = isNegativeImm ? ARM::t2CMNzri : ARM::t2CMPri;
1413       } else {
1414         if (!UseImm)
1415           CmpOpc = ARM::CMPrr;
1416         else
1417           CmpOpc = isNegativeImm ? ARM::CMNzri : ARM::CMPri;
1418       }
1419       break;
1420   }
1421
1422   unsigned SrcReg1 = getRegForValue(Src1Value);
1423   if (SrcReg1 == 0) return false;
1424
1425   unsigned SrcReg2 = 0;
1426   if (!UseImm) {
1427     SrcReg2 = getRegForValue(Src2Value);
1428     if (SrcReg2 == 0) return false;
1429   }
1430
1431   // We have i1, i8, or i16, we need to either zero extend or sign extend.
1432   if (needsExt) {
1433     unsigned ResultReg;
1434     ResultReg = ARMEmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
1435     if (ResultReg == 0) return false;
1436     SrcReg1 = ResultReg;
1437     if (!UseImm) {
1438       ResultReg = ARMEmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
1439       if (ResultReg == 0) return false;
1440       SrcReg2 = ResultReg;
1441     }
1442   }
1443
1444   if (!UseImm) {
1445     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1446                             TII.get(CmpOpc))
1447                     .addReg(SrcReg1).addReg(SrcReg2));
1448   } else {
1449     MachineInstrBuilder MIB;
1450     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1451       .addReg(SrcReg1);
1452
1453     // Only add immediate for icmp as the immediate for fcmp is an implicit 0.0.
1454     if (isICmp)
1455       MIB.addImm(Imm);
1456     AddOptionalDefs(MIB);
1457   }
1458
1459   // For floating point we need to move the result to a comparison register
1460   // that we can then use for branches.
1461   if (Ty->isFloatTy() || Ty->isDoubleTy())
1462     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1463                             TII.get(ARM::FMSTAT)));
1464   return true;
1465 }
1466
1467 bool ARMFastISel::SelectCmp(const Instruction *I) {
1468   const CmpInst *CI = cast<CmpInst>(I);
1469   Type *Ty = CI->getOperand(0)->getType();
1470
1471   // Get the compare predicate.
1472   ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
1473
1474   // We may not handle every CC for now.
1475   if (ARMPred == ARMCC::AL) return false;
1476
1477   // Emit the compare.
1478   if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1479     return false;
1480
1481   // Now set a register based on the comparison. Explicitly set the predicates
1482   // here.
1483   unsigned MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1484   TargetRegisterClass *RC = isThumb2 ? ARM::rGPRRegisterClass
1485                                     : ARM::GPRRegisterClass;
1486   unsigned DestReg = createResultReg(RC);
1487   Constant *Zero = ConstantInt::get(Type::getInt32Ty(*Context), 0);
1488   unsigned ZeroReg = TargetMaterializeConstant(Zero);
1489   bool isFloat = (Ty->isFloatTy() || Ty->isDoubleTy());
1490   unsigned CondReg = isFloat ? ARM::FPSCR : ARM::CPSR;
1491   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), DestReg)
1492           .addReg(ZeroReg).addImm(1)
1493           .addImm(ARMPred).addReg(CondReg);
1494
1495   UpdateValueMap(I, DestReg);
1496   return true;
1497 }
1498
1499 bool ARMFastISel::SelectFPExt(const Instruction *I) {
1500   // Make sure we have VFP and that we're extending float to double.
1501   if (!Subtarget->hasVFP2()) return false;
1502
1503   Value *V = I->getOperand(0);
1504   if (!I->getType()->isDoubleTy() ||
1505       !V->getType()->isFloatTy()) return false;
1506
1507   unsigned Op = getRegForValue(V);
1508   if (Op == 0) return false;
1509
1510   unsigned Result = createResultReg(ARM::DPRRegisterClass);
1511   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1512                           TII.get(ARM::VCVTDS), Result)
1513                   .addReg(Op));
1514   UpdateValueMap(I, Result);
1515   return true;
1516 }
1517
1518 bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
1519   // Make sure we have VFP and that we're truncating double to float.
1520   if (!Subtarget->hasVFP2()) return false;
1521
1522   Value *V = I->getOperand(0);
1523   if (!(I->getType()->isFloatTy() &&
1524         V->getType()->isDoubleTy())) return false;
1525
1526   unsigned Op = getRegForValue(V);
1527   if (Op == 0) return false;
1528
1529   unsigned Result = createResultReg(ARM::SPRRegisterClass);
1530   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1531                           TII.get(ARM::VCVTSD), Result)
1532                   .addReg(Op));
1533   UpdateValueMap(I, Result);
1534   return true;
1535 }
1536
1537 bool ARMFastISel::SelectIToFP(const Instruction *I, bool isSigned) {
1538   // Make sure we have VFP.
1539   if (!Subtarget->hasVFP2()) return false;
1540
1541   MVT DstVT;
1542   Type *Ty = I->getType();
1543   if (!isTypeLegal(Ty, DstVT))
1544     return false;
1545
1546   Value *Src = I->getOperand(0);
1547   EVT SrcVT = TLI.getValueType(Src->getType(), true);
1548   if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
1549     return false;
1550
1551   unsigned SrcReg = getRegForValue(Src);
1552   if (SrcReg == 0) return false;
1553
1554   // Handle sign-extension.
1555   if (SrcVT == MVT::i16 || SrcVT == MVT::i8) {
1556     EVT DestVT = MVT::i32;
1557     unsigned ResultReg = ARMEmitIntExt(SrcVT, SrcReg, DestVT,
1558                                        /*isZExt*/!isSigned);
1559     if (ResultReg == 0) return false;
1560     SrcReg = ResultReg;
1561   }
1562
1563   // The conversion routine works on fp-reg to fp-reg and the operand above
1564   // was an integer, move it to the fp registers if possible.
1565   unsigned FP = ARMMoveToFPReg(MVT::f32, SrcReg);
1566   if (FP == 0) return false;
1567
1568   unsigned Opc;
1569   if (Ty->isFloatTy()) Opc = isSigned ? ARM::VSITOS : ARM::VUITOS;
1570   else if (Ty->isDoubleTy()) Opc = isSigned ? ARM::VSITOD : ARM::VUITOD;
1571   else return false;
1572
1573   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1574   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1575                           ResultReg)
1576                   .addReg(FP));
1577   UpdateValueMap(I, ResultReg);
1578   return true;
1579 }
1580
1581 bool ARMFastISel::SelectFPToI(const Instruction *I, bool isSigned) {
1582   // Make sure we have VFP.
1583   if (!Subtarget->hasVFP2()) return false;
1584
1585   MVT DstVT;
1586   Type *RetTy = I->getType();
1587   if (!isTypeLegal(RetTy, DstVT))
1588     return false;
1589
1590   unsigned Op = getRegForValue(I->getOperand(0));
1591   if (Op == 0) return false;
1592
1593   unsigned Opc;
1594   Type *OpTy = I->getOperand(0)->getType();
1595   if (OpTy->isFloatTy()) Opc = isSigned ? ARM::VTOSIZS : ARM::VTOUIZS;
1596   else if (OpTy->isDoubleTy()) Opc = isSigned ? ARM::VTOSIZD : ARM::VTOUIZD;
1597   else return false;
1598
1599   // f64->s32/u32 or f32->s32/u32 both need an intermediate f32 reg.
1600   unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1601   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1602                           ResultReg)
1603                   .addReg(Op));
1604
1605   // This result needs to be in an integer register, but the conversion only
1606   // takes place in fp-regs.
1607   unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1608   if (IntReg == 0) return false;
1609
1610   UpdateValueMap(I, IntReg);
1611   return true;
1612 }
1613
1614 bool ARMFastISel::SelectSelect(const Instruction *I) {
1615   MVT VT;
1616   if (!isTypeLegal(I->getType(), VT))
1617     return false;
1618
1619   // Things need to be register sized for register moves.
1620   if (VT != MVT::i32) return false;
1621   const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
1622
1623   unsigned CondReg = getRegForValue(I->getOperand(0));
1624   if (CondReg == 0) return false;
1625   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1626   if (Op1Reg == 0) return false;
1627
1628   // Check to see if we can use an immediate in the conditional move.
1629   int Imm = 0;
1630   bool UseImm = false;
1631   bool isNegativeImm = false;
1632   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(2))) {
1633     assert (VT == MVT::i32 && "Expecting an i32.");
1634     Imm = (int)ConstInt->getValue().getZExtValue();
1635     if (Imm < 0) {
1636       isNegativeImm = true;
1637       Imm = ~Imm;
1638     }
1639     UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1640       (ARM_AM::getSOImmVal(Imm) != -1);
1641   }
1642
1643   unsigned Op2Reg = 0;
1644   if (!UseImm) {
1645     Op2Reg = getRegForValue(I->getOperand(2));
1646     if (Op2Reg == 0) return false;
1647   }
1648
1649   unsigned CmpOpc = isThumb2 ? ARM::t2CMPri : ARM::CMPri;
1650   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1651                   .addReg(CondReg).addImm(0));
1652
1653   unsigned MovCCOpc;
1654   if (!UseImm) {
1655     MovCCOpc = isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr;
1656   } else {
1657     if (!isNegativeImm) {
1658       MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1659     } else {
1660       MovCCOpc = isThumb2 ? ARM::t2MVNCCi : ARM::MVNCCi;
1661     }
1662   }
1663   unsigned ResultReg = createResultReg(RC);
1664   if (!UseImm)
1665     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1666     .addReg(Op2Reg).addReg(Op1Reg).addImm(ARMCC::NE).addReg(ARM::CPSR);
1667   else
1668     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1669     .addReg(Op1Reg).addImm(Imm).addImm(ARMCC::EQ).addReg(ARM::CPSR);
1670   UpdateValueMap(I, ResultReg);
1671   return true;
1672 }
1673
1674 bool ARMFastISel::SelectDiv(const Instruction *I, bool isSigned) {
1675   MVT VT;
1676   Type *Ty = I->getType();
1677   if (!isTypeLegal(Ty, VT))
1678     return false;
1679
1680   // If we have integer div support we should have selected this automagically.
1681   // In case we have a real miss go ahead and return false and we'll pick
1682   // it up later.
1683   if (Subtarget->hasDivide()) return false;
1684
1685   // Otherwise emit a libcall.
1686   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1687   if (VT == MVT::i8)
1688     LC = isSigned ? RTLIB::SDIV_I8 : RTLIB::UDIV_I8;
1689   else if (VT == MVT::i16)
1690     LC = isSigned ? RTLIB::SDIV_I16 : RTLIB::UDIV_I16;
1691   else if (VT == MVT::i32)
1692     LC = isSigned ? RTLIB::SDIV_I32 : RTLIB::UDIV_I32;
1693   else if (VT == MVT::i64)
1694     LC = isSigned ? RTLIB::SDIV_I64 : RTLIB::UDIV_I64;
1695   else if (VT == MVT::i128)
1696     LC = isSigned ? RTLIB::SDIV_I128 : RTLIB::UDIV_I128;
1697   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1698
1699   return ARMEmitLibcall(I, LC);
1700 }
1701
1702 bool ARMFastISel::SelectRem(const Instruction *I, bool isSigned) {
1703   MVT VT;
1704   Type *Ty = I->getType();
1705   if (!isTypeLegal(Ty, VT))
1706     return false;
1707
1708   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1709   if (VT == MVT::i8)
1710     LC = isSigned ? RTLIB::SREM_I8 : RTLIB::UREM_I8;
1711   else if (VT == MVT::i16)
1712     LC = isSigned ? RTLIB::SREM_I16 : RTLIB::UREM_I16;
1713   else if (VT == MVT::i32)
1714     LC = isSigned ? RTLIB::SREM_I32 : RTLIB::UREM_I32;
1715   else if (VT == MVT::i64)
1716     LC = isSigned ? RTLIB::SREM_I64 : RTLIB::UREM_I64;
1717   else if (VT == MVT::i128)
1718     LC = isSigned ? RTLIB::SREM_I128 : RTLIB::UREM_I128;
1719   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1720
1721   return ARMEmitLibcall(I, LC);
1722 }
1723
1724 bool ARMFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1725   assert (ISDOpcode == ISD::ADD && "Expected an add.");
1726   EVT DestVT  = TLI.getValueType(I->getType(), true);
1727
1728   // We can get here in the case when we have a binary operation on a non-legal
1729   // type and the target independent selector doesn't know how to handle it.
1730   if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
1731     return false;
1732   
1733   unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1734   if (SrcReg1 == 0) return false;
1735
1736   // TODO: Often the 2nd operand is an immediate, which can be encoded directly
1737   // in the instruction, rather then materializing the value in a register.
1738   unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1739   if (SrcReg2 == 0) return false;
1740
1741   unsigned Opc = isThumb2 ? ARM::t2ADDrr : ARM::ADDrr;
1742   unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::i32));
1743   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1744                           TII.get(Opc), ResultReg)
1745                   .addReg(SrcReg1).addReg(SrcReg2));
1746   UpdateValueMap(I, ResultReg);
1747   return true;
1748 }
1749
1750 bool ARMFastISel::SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode) {
1751   EVT VT  = TLI.getValueType(I->getType(), true);
1752
1753   // We can get here in the case when we want to use NEON for our fp
1754   // operations, but can't figure out how to. Just use the vfp instructions
1755   // if we have them.
1756   // FIXME: It'd be nice to use NEON instructions.
1757   Type *Ty = I->getType();
1758   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1759   if (isFloat && !Subtarget->hasVFP2())
1760     return false;
1761
1762   unsigned Opc;
1763   bool is64bit = VT == MVT::f64 || VT == MVT::i64;
1764   switch (ISDOpcode) {
1765     default: return false;
1766     case ISD::FADD:
1767       Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1768       break;
1769     case ISD::FSUB:
1770       Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1771       break;
1772     case ISD::FMUL:
1773       Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1774       break;
1775   }
1776   unsigned Op1 = getRegForValue(I->getOperand(0));
1777   if (Op1 == 0) return false;
1778
1779   unsigned Op2 = getRegForValue(I->getOperand(1));
1780   if (Op2 == 0) return false;
1781
1782   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1783   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1784                           TII.get(Opc), ResultReg)
1785                   .addReg(Op1).addReg(Op2));
1786   UpdateValueMap(I, ResultReg);
1787   return true;
1788 }
1789
1790 // Call Handling Code
1791
1792 // This is largely taken directly from CCAssignFnForNode - we don't support
1793 // varargs in FastISel so that part has been removed.
1794 // TODO: We may not support all of this.
1795 CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC, bool Return) {
1796   switch (CC) {
1797   default:
1798     llvm_unreachable("Unsupported calling convention");
1799   case CallingConv::Fast:
1800     // Ignore fastcc. Silence compiler warnings.
1801     (void)RetFastCC_ARM_APCS;
1802     (void)FastCC_ARM_APCS;
1803     // Fallthrough
1804   case CallingConv::C:
1805     // Use target triple & subtarget features to do actual dispatch.
1806     if (Subtarget->isAAPCS_ABI()) {
1807       if (Subtarget->hasVFP2() &&
1808           TM.Options.FloatABIType == FloatABI::Hard)
1809         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1810       else
1811         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1812     } else
1813         return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1814   case CallingConv::ARM_AAPCS_VFP:
1815     return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1816   case CallingConv::ARM_AAPCS:
1817     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1818   case CallingConv::ARM_APCS:
1819     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1820   }
1821 }
1822
1823 bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1824                                   SmallVectorImpl<unsigned> &ArgRegs,
1825                                   SmallVectorImpl<MVT> &ArgVTs,
1826                                   SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1827                                   SmallVectorImpl<unsigned> &RegArgs,
1828                                   CallingConv::ID CC,
1829                                   unsigned &NumBytes) {
1830   SmallVector<CCValAssign, 16> ArgLocs;
1831   CCState CCInfo(CC, false, *FuncInfo.MF, TM, ArgLocs, *Context);
1832   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC, false));
1833
1834   // Get a count of how many bytes are to be pushed on the stack.
1835   NumBytes = CCInfo.getNextStackOffset();
1836
1837   // Issue CALLSEQ_START
1838   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1839   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1840                           TII.get(AdjStackDown))
1841                   .addImm(NumBytes));
1842
1843   // Process the args.
1844   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1845     CCValAssign &VA = ArgLocs[i];
1846     unsigned Arg = ArgRegs[VA.getValNo()];
1847     MVT ArgVT = ArgVTs[VA.getValNo()];
1848
1849     // We don't handle NEON/vector parameters yet.
1850     if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64)
1851       return false;
1852
1853     // Handle arg promotion, etc.
1854     switch (VA.getLocInfo()) {
1855       case CCValAssign::Full: break;
1856       case CCValAssign::SExt: {
1857         MVT DestVT = VA.getLocVT();
1858         unsigned ResultReg = ARMEmitIntExt(ArgVT, Arg, DestVT,
1859                                            /*isZExt*/false);
1860         assert (ResultReg != 0 && "Failed to emit a sext");
1861         Arg = ResultReg;
1862         ArgVT = DestVT;
1863         break;
1864       }
1865       case CCValAssign::AExt:
1866         // Intentional fall-through.  Handle AExt and ZExt.
1867       case CCValAssign::ZExt: {
1868         MVT DestVT = VA.getLocVT();
1869         unsigned ResultReg = ARMEmitIntExt(ArgVT, Arg, DestVT,
1870                                            /*isZExt*/true);
1871         assert (ResultReg != 0 && "Failed to emit a sext");
1872         Arg = ResultReg;
1873         ArgVT = DestVT;
1874         break;
1875       }
1876       case CCValAssign::BCvt: {
1877         unsigned BC = FastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, Arg,
1878                                  /*TODO: Kill=*/false);
1879         assert(BC != 0 && "Failed to emit a bitcast!");
1880         Arg = BC;
1881         ArgVT = VA.getLocVT();
1882         break;
1883       }
1884       default: llvm_unreachable("Unknown arg promotion!");
1885     }
1886
1887     // Now copy/store arg to correct locations.
1888     if (VA.isRegLoc() && !VA.needsCustom()) {
1889       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1890               VA.getLocReg())
1891         .addReg(Arg);
1892       RegArgs.push_back(VA.getLocReg());
1893     } else if (VA.needsCustom()) {
1894       // TODO: We need custom lowering for vector (v2f64) args.
1895       if (VA.getLocVT() != MVT::f64) return false;
1896
1897       CCValAssign &NextVA = ArgLocs[++i];
1898
1899       // TODO: Only handle register args for now.
1900       if(!(VA.isRegLoc() && NextVA.isRegLoc())) return false;
1901
1902       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1903                               TII.get(ARM::VMOVRRD), VA.getLocReg())
1904                       .addReg(NextVA.getLocReg(), RegState::Define)
1905                       .addReg(Arg));
1906       RegArgs.push_back(VA.getLocReg());
1907       RegArgs.push_back(NextVA.getLocReg());
1908     } else {
1909       assert(VA.isMemLoc());
1910       // Need to store on the stack.
1911       Address Addr;
1912       Addr.BaseType = Address::RegBase;
1913       Addr.Base.Reg = ARM::SP;
1914       Addr.Offset = VA.getLocMemOffset();
1915
1916       if (!ARMEmitStore(ArgVT, Arg, Addr)) return false;
1917     }
1918   }
1919   return true;
1920 }
1921
1922 bool ARMFastISel::FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1923                              const Instruction *I, CallingConv::ID CC,
1924                              unsigned &NumBytes) {
1925   // Issue CALLSEQ_END
1926   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1927   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1928                           TII.get(AdjStackUp))
1929                   .addImm(NumBytes).addImm(0));
1930
1931   // Now the return value.
1932   if (RetVT != MVT::isVoid) {
1933     SmallVector<CCValAssign, 16> RVLocs;
1934     CCState CCInfo(CC, false, *FuncInfo.MF, TM, RVLocs, *Context);
1935     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true));
1936
1937     // Copy all of the result registers out of their specified physreg.
1938     if (RVLocs.size() == 2 && RetVT == MVT::f64) {
1939       // For this move we copy into two registers and then move into the
1940       // double fp reg we want.
1941       EVT DestVT = RVLocs[0].getValVT();
1942       TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
1943       unsigned ResultReg = createResultReg(DstRC);
1944       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1945                               TII.get(ARM::VMOVDRR), ResultReg)
1946                       .addReg(RVLocs[0].getLocReg())
1947                       .addReg(RVLocs[1].getLocReg()));
1948
1949       UsedRegs.push_back(RVLocs[0].getLocReg());
1950       UsedRegs.push_back(RVLocs[1].getLocReg());
1951
1952       // Finally update the result.
1953       UpdateValueMap(I, ResultReg);
1954     } else {
1955       assert(RVLocs.size() == 1 &&"Can't handle non-double multi-reg retvals!");
1956       EVT CopyVT = RVLocs[0].getValVT();
1957
1958       // Special handling for extended integers.
1959       if (RetVT == MVT::i1 || RetVT == MVT::i8 || RetVT == MVT::i16)
1960         CopyVT = MVT::i32;
1961
1962       TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1963
1964       unsigned ResultReg = createResultReg(DstRC);
1965       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1966               ResultReg).addReg(RVLocs[0].getLocReg());
1967       UsedRegs.push_back(RVLocs[0].getLocReg());
1968
1969       // Finally update the result.
1970       UpdateValueMap(I, ResultReg);
1971     }
1972   }
1973
1974   return true;
1975 }
1976
1977 bool ARMFastISel::SelectRet(const Instruction *I) {
1978   const ReturnInst *Ret = cast<ReturnInst>(I);
1979   const Function &F = *I->getParent()->getParent();
1980
1981   if (!FuncInfo.CanLowerReturn)
1982     return false;
1983
1984   if (F.isVarArg())
1985     return false;
1986
1987   CallingConv::ID CC = F.getCallingConv();
1988   if (Ret->getNumOperands() > 0) {
1989     SmallVector<ISD::OutputArg, 4> Outs;
1990     GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
1991                   Outs, TLI);
1992
1993     // Analyze operands of the call, assigning locations to each operand.
1994     SmallVector<CCValAssign, 16> ValLocs;
1995     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,I->getContext());
1996     CCInfo.AnalyzeReturn(Outs, CCAssignFnForCall(CC, true /* is Ret */));
1997
1998     const Value *RV = Ret->getOperand(0);
1999     unsigned Reg = getRegForValue(RV);
2000     if (Reg == 0)
2001       return false;
2002
2003     // Only handle a single return value for now.
2004     if (ValLocs.size() != 1)
2005       return false;
2006
2007     CCValAssign &VA = ValLocs[0];
2008
2009     // Don't bother handling odd stuff for now.
2010     if (VA.getLocInfo() != CCValAssign::Full)
2011       return false;
2012     // Only handle register returns for now.
2013     if (!VA.isRegLoc())
2014       return false;
2015
2016     unsigned SrcReg = Reg + VA.getValNo();
2017     EVT RVVT = TLI.getValueType(RV->getType());
2018     EVT DestVT = VA.getValVT();
2019     // Special handling for extended integers.
2020     if (RVVT != DestVT) {
2021       if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
2022         return false;
2023
2024       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
2025         return false;
2026
2027       assert(DestVT == MVT::i32 && "ARM should always ext to i32");
2028
2029       bool isZExt = Outs[0].Flags.isZExt();
2030       unsigned ResultReg = ARMEmitIntExt(RVVT, SrcReg, DestVT, isZExt);
2031       if (ResultReg == 0) return false;
2032       SrcReg = ResultReg;
2033     }
2034
2035     // Make the copy.
2036     unsigned DstReg = VA.getLocReg();
2037     const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
2038     // Avoid a cross-class copy. This is very unlikely.
2039     if (!SrcRC->contains(DstReg))
2040       return false;
2041     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2042             DstReg).addReg(SrcReg);
2043
2044     // Mark the register as live out of the function.
2045     MRI.addLiveOut(VA.getLocReg());
2046   }
2047
2048   unsigned RetOpc = isThumb2 ? ARM::tBX_RET : ARM::BX_RET;
2049   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2050                           TII.get(RetOpc)));
2051   return true;
2052 }
2053
2054 unsigned ARMFastISel::ARMSelectCallOp(const GlobalValue *GV) {
2055
2056   // iOS needs the r9 versions of the opcodes.
2057   bool isiOS = Subtarget->isTargetIOS();
2058   if (isThumb2) {
2059     return isiOS ? ARM::tBLr9 : ARM::tBL;
2060   } else  {
2061     return isiOS ? ARM::BLr9 : ARM::BL;
2062   }
2063 }
2064
2065 // A quick function that will emit a call for a named libcall in F with the
2066 // vector of passed arguments for the Instruction in I. We can assume that we
2067 // can emit a call for any libcall we can produce. This is an abridged version
2068 // of the full call infrastructure since we won't need to worry about things
2069 // like computed function pointers or strange arguments at call sites.
2070 // TODO: Try to unify this and the normal call bits for ARM, then try to unify
2071 // with X86.
2072 bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
2073   CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
2074
2075   // Handle *simple* calls for now.
2076   Type *RetTy = I->getType();
2077   MVT RetVT;
2078   if (RetTy->isVoidTy())
2079     RetVT = MVT::isVoid;
2080   else if (!isTypeLegal(RetTy, RetVT))
2081     return false;
2082
2083   // TODO: For now if we have long calls specified we don't handle the call.
2084   if (EnableARMLongCalls) return false;
2085
2086   // Set up the argument vectors.
2087   SmallVector<Value*, 8> Args;
2088   SmallVector<unsigned, 8> ArgRegs;
2089   SmallVector<MVT, 8> ArgVTs;
2090   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2091   Args.reserve(I->getNumOperands());
2092   ArgRegs.reserve(I->getNumOperands());
2093   ArgVTs.reserve(I->getNumOperands());
2094   ArgFlags.reserve(I->getNumOperands());
2095   for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2096     Value *Op = I->getOperand(i);
2097     unsigned Arg = getRegForValue(Op);
2098     if (Arg == 0) return false;
2099
2100     Type *ArgTy = Op->getType();
2101     MVT ArgVT;
2102     if (!isTypeLegal(ArgTy, ArgVT)) return false;
2103
2104     ISD::ArgFlagsTy Flags;
2105     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
2106     Flags.setOrigAlign(OriginalAlignment);
2107
2108     Args.push_back(Op);
2109     ArgRegs.push_back(Arg);
2110     ArgVTs.push_back(ArgVT);
2111     ArgFlags.push_back(Flags);
2112   }
2113
2114   // Handle the arguments now that we've gotten them.
2115   SmallVector<unsigned, 4> RegArgs;
2116   unsigned NumBytes;
2117   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
2118     return false;
2119
2120   // Issue the call, BLr9 for iOS, BL otherwise.
2121   // TODO: Turn this into the table of arm call ops.
2122   MachineInstrBuilder MIB;
2123   unsigned CallOpc = ARMSelectCallOp(NULL);
2124   if(isThumb2)
2125     // Explicitly adding the predicate here.
2126     MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2127                          TII.get(CallOpc)))
2128                          .addExternalSymbol(TLI.getLibcallName(Call));
2129   else
2130     // Explicitly adding the predicate here.
2131     MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2132                          TII.get(CallOpc))
2133           .addExternalSymbol(TLI.getLibcallName(Call)));
2134
2135   // Add implicit physical register uses to the call.
2136   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2137     MIB.addReg(RegArgs[i]);
2138
2139   // Finish off the call including any return values.
2140   SmallVector<unsigned, 4> UsedRegs;
2141   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
2142
2143   // Set all unused physreg defs as dead.
2144   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2145
2146   return true;
2147 }
2148
2149 bool ARMFastISel::SelectCall(const Instruction *I,
2150                              const char *IntrMemName = 0) {
2151   const CallInst *CI = cast<CallInst>(I);
2152   const Value *Callee = CI->getCalledValue();
2153
2154   // Can't handle inline asm.
2155   if (isa<InlineAsm>(Callee)) return false;
2156
2157   // Only handle global variable Callees.
2158   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
2159   if (!GV)
2160     return false;
2161
2162   // Check the calling convention.
2163   ImmutableCallSite CS(CI);
2164   CallingConv::ID CC = CS.getCallingConv();
2165
2166   // TODO: Avoid some calling conventions?
2167
2168   // Let SDISel handle vararg functions.
2169   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2170   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2171   if (FTy->isVarArg())
2172     return false;
2173
2174   // Handle *simple* calls for now.
2175   Type *RetTy = I->getType();
2176   MVT RetVT;
2177   if (RetTy->isVoidTy())
2178     RetVT = MVT::isVoid;
2179   else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
2180            RetVT != MVT::i8  && RetVT != MVT::i1)
2181     return false;
2182
2183   // TODO: For now if we have long calls specified we don't handle the call.
2184   if (EnableARMLongCalls) return false;
2185
2186   // Set up the argument vectors.
2187   SmallVector<Value*, 8> Args;
2188   SmallVector<unsigned, 8> ArgRegs;
2189   SmallVector<MVT, 8> ArgVTs;
2190   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2191   Args.reserve(CS.arg_size());
2192   ArgRegs.reserve(CS.arg_size());
2193   ArgVTs.reserve(CS.arg_size());
2194   ArgFlags.reserve(CS.arg_size());
2195   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2196        i != e; ++i) {
2197     // If we're lowering a memory intrinsic instead of a regular call, skip the
2198     // last two arguments, which shouldn't be passed to the underlying function.
2199     if (IntrMemName && e-i <= 2)
2200       break;
2201
2202     ISD::ArgFlagsTy Flags;
2203     unsigned AttrInd = i - CS.arg_begin() + 1;
2204     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2205       Flags.setSExt();
2206     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2207       Flags.setZExt();
2208
2209     // FIXME: Only handle *easy* calls for now.
2210     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
2211         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
2212         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
2213         CS.paramHasAttr(AttrInd, Attribute::ByVal))
2214       return false;
2215
2216     Type *ArgTy = (*i)->getType();
2217     MVT ArgVT;
2218     if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8 &&
2219         ArgVT != MVT::i1)
2220       return false;
2221
2222     unsigned Arg = getRegForValue(*i);
2223     if (Arg == 0)
2224       return false;
2225
2226     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
2227     Flags.setOrigAlign(OriginalAlignment);
2228
2229     Args.push_back(*i);
2230     ArgRegs.push_back(Arg);
2231     ArgVTs.push_back(ArgVT);
2232     ArgFlags.push_back(Flags);
2233   }
2234
2235   // Handle the arguments now that we've gotten them.
2236   SmallVector<unsigned, 4> RegArgs;
2237   unsigned NumBytes;
2238   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
2239     return false;
2240
2241   // Issue the call, BLr9 for iOS, BL otherwise.
2242   // TODO: Turn this into the table of arm call ops.
2243   MachineInstrBuilder MIB;
2244   unsigned CallOpc = ARMSelectCallOp(GV);
2245   // Explicitly adding the predicate here.
2246   if(isThumb2) {
2247     // Explicitly adding the predicate here.
2248     MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2249                                  TII.get(CallOpc)));
2250     if (!IntrMemName)
2251       MIB.addGlobalAddress(GV, 0, 0);
2252     else 
2253       MIB.addExternalSymbol(IntrMemName, 0);
2254   } else {
2255     if (!IntrMemName)
2256       // Explicitly adding the predicate here.
2257       MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2258                                    TII.get(CallOpc))
2259             .addGlobalAddress(GV, 0, 0));
2260     else
2261       MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2262                                    TII.get(CallOpc))
2263             .addExternalSymbol(IntrMemName, 0));
2264   }
2265   
2266   // Add implicit physical register uses to the call.
2267   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2268     MIB.addReg(RegArgs[i]);
2269
2270   // Finish off the call including any return values.
2271   SmallVector<unsigned, 4> UsedRegs;
2272   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
2273
2274   // Set all unused physreg defs as dead.
2275   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2276
2277   return true;
2278 }
2279
2280 bool ARMFastISel::ARMIsMemCpySmall(uint64_t Len) {
2281   return Len <= 16;
2282 }
2283
2284 bool ARMFastISel::ARMTryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len) {
2285   // Make sure we don't bloat code by inlining very large memcpy's.
2286   if (!ARMIsMemCpySmall(Len))
2287     return false;
2288
2289   // We don't care about alignment here since we just emit integer accesses.
2290   while (Len) {
2291     MVT VT;
2292     if (Len >= 4)
2293       VT = MVT::i32;
2294     else if (Len >= 2)
2295       VT = MVT::i16;
2296     else {
2297       assert(Len == 1);
2298       VT = MVT::i8;
2299     }
2300
2301     bool RV;
2302     unsigned ResultReg;
2303     RV = ARMEmitLoad(VT, ResultReg, Src);
2304     assert (RV == true && "Should be able to handle this load.");
2305     RV = ARMEmitStore(VT, ResultReg, Dest);
2306     assert (RV == true && "Should be able to handle this store.");
2307     (void)RV;
2308
2309     unsigned Size = VT.getSizeInBits()/8;
2310     Len -= Size;
2311     Dest.Offset += Size;
2312     Src.Offset += Size;
2313   }
2314
2315   return true;
2316 }
2317
2318 bool ARMFastISel::SelectIntrinsicCall(const IntrinsicInst &I) {
2319   // FIXME: Handle more intrinsics.
2320   switch (I.getIntrinsicID()) {
2321   default: return false;
2322   case Intrinsic::memcpy:
2323   case Intrinsic::memmove: {
2324     const MemTransferInst &MTI = cast<MemTransferInst>(I);
2325     // Don't handle volatile.
2326     if (MTI.isVolatile())
2327       return false;
2328
2329     // Disable inlining for memmove before calls to ComputeAddress.  Otherwise,
2330     // we would emit dead code because we don't currently handle memmoves.
2331     bool isMemCpy = (I.getIntrinsicID() == Intrinsic::memcpy);
2332     if (isa<ConstantInt>(MTI.getLength()) && isMemCpy) {
2333       // Small memcpy's are common enough that we want to do them without a call
2334       // if possible.
2335       uint64_t Len = cast<ConstantInt>(MTI.getLength())->getZExtValue();
2336       if (ARMIsMemCpySmall(Len)) {
2337         Address Dest, Src;
2338         if (!ARMComputeAddress(MTI.getRawDest(), Dest) ||
2339             !ARMComputeAddress(MTI.getRawSource(), Src))
2340           return false;
2341         if (ARMTryEmitSmallMemCpy(Dest, Src, Len))
2342           return true;
2343       }
2344     }
2345     
2346     if (!MTI.getLength()->getType()->isIntegerTy(32))
2347       return false;
2348     
2349     if (MTI.getSourceAddressSpace() > 255 || MTI.getDestAddressSpace() > 255)
2350       return false;
2351
2352     const char *IntrMemName = isa<MemCpyInst>(I) ? "memcpy" : "memmove";
2353     return SelectCall(&I, IntrMemName);
2354   }
2355   case Intrinsic::memset: {
2356     const MemSetInst &MSI = cast<MemSetInst>(I);
2357     // Don't handle volatile.
2358     if (MSI.isVolatile())
2359       return false;
2360     
2361     if (!MSI.getLength()->getType()->isIntegerTy(32))
2362       return false;
2363     
2364     if (MSI.getDestAddressSpace() > 255)
2365       return false;
2366     
2367     return SelectCall(&I, "memset");
2368   }
2369   }
2370 }
2371
2372 bool ARMFastISel::SelectTrunc(const Instruction *I) {
2373   // The high bits for a type smaller than the register size are assumed to be 
2374   // undefined.
2375   Value *Op = I->getOperand(0);
2376
2377   EVT SrcVT, DestVT;
2378   SrcVT = TLI.getValueType(Op->getType(), true);
2379   DestVT = TLI.getValueType(I->getType(), true);
2380
2381   if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
2382     return false;
2383   if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
2384     return false;
2385
2386   unsigned SrcReg = getRegForValue(Op);
2387   if (!SrcReg) return false;
2388
2389   // Because the high bits are undefined, a truncate doesn't generate
2390   // any code.
2391   UpdateValueMap(I, SrcReg);
2392   return true;
2393 }
2394
2395 unsigned ARMFastISel::ARMEmitIntExt(EVT SrcVT, unsigned SrcReg, EVT DestVT,
2396                                     bool isZExt) {
2397   if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
2398     return 0;
2399
2400   unsigned Opc;
2401   bool isBoolZext = false;
2402   if (!SrcVT.isSimple()) return 0;
2403   switch (SrcVT.getSimpleVT().SimpleTy) {
2404   default: return 0;
2405   case MVT::i16:
2406     if (!Subtarget->hasV6Ops()) return 0;
2407     if (isZExt)
2408       Opc = isThumb2 ? ARM::t2UXTH : ARM::UXTH;
2409     else
2410       Opc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
2411     break;
2412   case MVT::i8:
2413     if (!Subtarget->hasV6Ops()) return 0;
2414     if (isZExt)
2415       Opc = isThumb2 ? ARM::t2UXTB : ARM::UXTB;
2416     else
2417       Opc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
2418     break;
2419   case MVT::i1:
2420     if (isZExt) {
2421       Opc = isThumb2 ? ARM::t2ANDri : ARM::ANDri;
2422       isBoolZext = true;
2423       break;
2424     }
2425     return 0;
2426   }
2427
2428   unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::i32));
2429   MachineInstrBuilder MIB;
2430   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
2431         .addReg(SrcReg);
2432   if (isBoolZext)
2433     MIB.addImm(1);
2434   else
2435     MIB.addImm(0);
2436   AddOptionalDefs(MIB);
2437   return ResultReg;
2438 }
2439
2440 bool ARMFastISel::SelectIntExt(const Instruction *I) {
2441   // On ARM, in general, integer casts don't involve legal types; this code
2442   // handles promotable integers.
2443   Type *DestTy = I->getType();
2444   Value *Src = I->getOperand(0);
2445   Type *SrcTy = Src->getType();
2446
2447   EVT SrcVT, DestVT;
2448   SrcVT = TLI.getValueType(SrcTy, true);
2449   DestVT = TLI.getValueType(DestTy, true);
2450
2451   bool isZExt = isa<ZExtInst>(I);
2452   unsigned SrcReg = getRegForValue(Src);
2453   if (!SrcReg) return false;
2454
2455   unsigned ResultReg = ARMEmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
2456   if (ResultReg == 0) return false;
2457   UpdateValueMap(I, ResultReg);
2458   return true;
2459 }
2460
2461 // TODO: SoftFP support.
2462 bool ARMFastISel::TargetSelectInstruction(const Instruction *I) {
2463
2464   switch (I->getOpcode()) {
2465     case Instruction::Load:
2466       return SelectLoad(I);
2467     case Instruction::Store:
2468       return SelectStore(I);
2469     case Instruction::Br:
2470       return SelectBranch(I);
2471     case Instruction::ICmp:
2472     case Instruction::FCmp:
2473       return SelectCmp(I);
2474     case Instruction::FPExt:
2475       return SelectFPExt(I);
2476     case Instruction::FPTrunc:
2477       return SelectFPTrunc(I);
2478     case Instruction::SIToFP:
2479       return SelectIToFP(I, /*isSigned*/ true);
2480     case Instruction::UIToFP:
2481       return SelectIToFP(I, /*isSigned*/ false);
2482     case Instruction::FPToSI:
2483       return SelectFPToI(I, /*isSigned*/ true);
2484     case Instruction::FPToUI:
2485       return SelectFPToI(I, /*isSigned*/ false);
2486     case Instruction::Add:
2487       return SelectBinaryIntOp(I, ISD::ADD);
2488     case Instruction::FAdd:
2489       return SelectBinaryFPOp(I, ISD::FADD);
2490     case Instruction::FSub:
2491       return SelectBinaryFPOp(I, ISD::FSUB);
2492     case Instruction::FMul:
2493       return SelectBinaryFPOp(I, ISD::FMUL);
2494     case Instruction::SDiv:
2495       return SelectDiv(I, /*isSigned*/ true);
2496     case Instruction::UDiv:
2497       return SelectDiv(I, /*isSigned*/ false);
2498     case Instruction::SRem:
2499       return SelectRem(I, /*isSigned*/ true);
2500     case Instruction::URem:
2501       return SelectRem(I, /*isSigned*/ false);
2502     case Instruction::Call:
2503       if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2504         return SelectIntrinsicCall(*II);
2505       return SelectCall(I);
2506     case Instruction::Select:
2507       return SelectSelect(I);
2508     case Instruction::Ret:
2509       return SelectRet(I);
2510     case Instruction::Trunc:
2511       return SelectTrunc(I);
2512     case Instruction::ZExt:
2513     case Instruction::SExt:
2514       return SelectIntExt(I);
2515     default: break;
2516   }
2517   return false;
2518 }
2519
2520 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
2521 /// vreg is being provided by the specified load instruction.  If possible,
2522 /// try to fold the load as an operand to the instruction, returning true if
2523 /// successful.
2524 bool ARMFastISel::TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
2525                                 const LoadInst *LI) {
2526   // Verify we have a legal type before going any further.
2527   MVT VT;
2528   if (!isLoadTypeLegal(LI->getType(), VT))
2529     return false;
2530
2531   // Combine load followed by zero- or sign-extend.
2532   // ldrb r1, [r0]       ldrb r1, [r0]
2533   // uxtb r2, r1     =>
2534   // mov  r3, r2         mov  r3, r1
2535   bool isZExt = true;
2536   switch(MI->getOpcode()) {
2537     default: return false;
2538     case ARM::SXTH:
2539     case ARM::t2SXTH:
2540       isZExt = false;
2541     case ARM::UXTH:
2542     case ARM::t2UXTH:
2543       if (VT != MVT::i16)
2544         return false;
2545     break;
2546     case ARM::SXTB:
2547     case ARM::t2SXTB:
2548       isZExt = false;
2549     case ARM::UXTB:
2550     case ARM::t2UXTB:
2551       if (VT != MVT::i8)
2552         return false;
2553     break;
2554   }
2555   // See if we can handle this address.
2556   Address Addr;
2557   if (!ARMComputeAddress(LI->getOperand(0), Addr)) return false;
2558   
2559   unsigned ResultReg = MI->getOperand(0).getReg();
2560   if (!ARMEmitLoad(VT, ResultReg, Addr, LI->getAlignment(), isZExt, false))
2561     return false;
2562   MI->eraseFromParent();
2563   return true;
2564 }
2565
2566 namespace llvm {
2567   llvm::FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo) {
2568     // Completely untested on non-iOS.
2569     const TargetMachine &TM = funcInfo.MF->getTarget();
2570
2571     // Darwin and thumb1 only for now.
2572     const ARMSubtarget *Subtarget = &TM.getSubtarget<ARMSubtarget>();
2573     if (Subtarget->isTargetIOS() && !Subtarget->isThumb1Only() &&
2574         !DisableARMFastISel)
2575       return new ARMFastISel(funcInfo);
2576     return 0;
2577   }
2578 }