129130355336c7e1848e350f2564227f09e95b71
[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:
885       assert(false && "Unhandled load/store type!");
886       break;
887     case MVT::i1:
888     case MVT::i8:
889     case MVT::i16:
890     case MVT::i32:
891       if (!useAM3) {
892         // Integer loads/stores handle 12-bit offsets.
893         needsLowering = ((Addr.Offset & 0xfff) != Addr.Offset);
894         // Handle negative offsets.
895         if (needsLowering && isThumb2)
896           needsLowering = !(Subtarget->hasV6T2Ops() && Addr.Offset < 0 &&
897                             Addr.Offset > -256);
898       } else {
899         // ARM halfword load/stores and signed byte loads use +/-imm8 offsets.
900         needsLowering = (Addr.Offset > 255 || Addr.Offset < -255);
901       }
902       break;
903     case MVT::f32:
904     case MVT::f64:
905       // Floating point operands handle 8-bit offsets.
906       needsLowering = ((Addr.Offset & 0xff) != Addr.Offset);
907       break;
908   }
909
910   // If this is a stack pointer and the offset needs to be simplified then
911   // put the alloca address into a register, set the base type back to
912   // register and continue. This should almost never happen.
913   if (needsLowering && Addr.BaseType == Address::FrameIndexBase) {
914     TargetRegisterClass *RC = isThumb2 ? ARM::tGPRRegisterClass :
915                               ARM::GPRRegisterClass;
916     unsigned ResultReg = createResultReg(RC);
917     unsigned Opc = isThumb2 ? ARM::t2ADDri : ARM::ADDri;
918     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
919                             TII.get(Opc), ResultReg)
920                             .addFrameIndex(Addr.Base.FI)
921                             .addImm(0));
922     Addr.Base.Reg = ResultReg;
923     Addr.BaseType = Address::RegBase;
924   }
925
926   // Since the offset is too large for the load/store instruction
927   // get the reg+offset into a register.
928   if (needsLowering) {
929     Addr.Base.Reg = FastEmit_ri_(MVT::i32, ISD::ADD, Addr.Base.Reg,
930                                  /*Op0IsKill*/false, Addr.Offset, MVT::i32);
931     Addr.Offset = 0;
932   }
933 }
934
935 void ARMFastISel::AddLoadStoreOperands(EVT VT, Address &Addr,
936                                        const MachineInstrBuilder &MIB,
937                                        unsigned Flags, bool useAM3) {
938   // addrmode5 output depends on the selection dag addressing dividing the
939   // offset by 4 that it then later multiplies. Do this here as well.
940   if (VT.getSimpleVT().SimpleTy == MVT::f32 ||
941       VT.getSimpleVT().SimpleTy == MVT::f64)
942     Addr.Offset /= 4;
943
944   // Frame base works a bit differently. Handle it separately.
945   if (Addr.BaseType == Address::FrameIndexBase) {
946     int FI = Addr.Base.FI;
947     int Offset = Addr.Offset;
948     MachineMemOperand *MMO =
949           FuncInfo.MF->getMachineMemOperand(
950                                   MachinePointerInfo::getFixedStack(FI, Offset),
951                                   Flags,
952                                   MFI.getObjectSize(FI),
953                                   MFI.getObjectAlignment(FI));
954     // Now add the rest of the operands.
955     MIB.addFrameIndex(FI);
956
957     // ARM halfword load/stores and signed byte loads need an additional
958     // operand.
959     if (useAM3) {
960       signed Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
961       MIB.addReg(0);
962       MIB.addImm(Imm);
963     } else {
964       MIB.addImm(Addr.Offset);
965     }
966     MIB.addMemOperand(MMO);
967   } else {
968     // Now add the rest of the operands.
969     MIB.addReg(Addr.Base.Reg);
970
971     // ARM halfword load/stores and signed byte loads need an additional
972     // operand.
973     if (useAM3) {
974       signed Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
975       MIB.addReg(0);
976       MIB.addImm(Imm);
977     } else {
978       MIB.addImm(Addr.Offset);
979     }
980   }
981   AddOptionalDefs(MIB);
982 }
983
984 bool ARMFastISel::ARMEmitLoad(EVT VT, unsigned &ResultReg, Address &Addr,
985                               unsigned Alignment, bool isZExt, bool allocReg) {
986   assert(VT.isSimple() && "Non-simple types are invalid here!");
987   unsigned Opc;
988   bool useAM3 = false;
989   bool needVMOV = false;
990   TargetRegisterClass *RC;  
991   switch (VT.getSimpleVT().SimpleTy) {
992     // This is mostly going to be Neon/vector support.
993     default: return false;
994     case MVT::i1:
995     case MVT::i8:
996       if (isThumb2) {
997         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
998           Opc = isZExt ? ARM::t2LDRBi8 : ARM::t2LDRSBi8;
999         else
1000           Opc = isZExt ? ARM::t2LDRBi12 : ARM::t2LDRSBi12;
1001       } else {
1002         if (isZExt) {
1003           Opc = ARM::LDRBi12;
1004         } else {
1005           Opc = ARM::LDRSB;
1006           useAM3 = true;
1007         }
1008       }
1009       RC = ARM::GPRRegisterClass;
1010       break;
1011     case MVT::i16:
1012       if (isThumb2) {
1013         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1014           Opc = isZExt ? ARM::t2LDRHi8 : ARM::t2LDRSHi8;
1015         else
1016           Opc = isZExt ? ARM::t2LDRHi12 : ARM::t2LDRSHi12;
1017       } else {
1018         Opc = isZExt ? ARM::LDRH : ARM::LDRSH;
1019         useAM3 = true;
1020       }
1021       RC = ARM::GPRRegisterClass;
1022       break;
1023     case MVT::i32:
1024       if (isThumb2) {
1025         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1026           Opc = ARM::t2LDRi8;
1027         else
1028           Opc = ARM::t2LDRi12;
1029       } else {
1030         Opc = ARM::LDRi12;
1031       }
1032       RC = ARM::GPRRegisterClass;
1033       break;
1034     case MVT::f32:
1035       if (!Subtarget->hasVFP2()) return false;
1036       // Unaligned loads need special handling. Floats require word-alignment.
1037       if (Alignment && Alignment < 4) {
1038         needVMOV = true;
1039         VT = MVT::i32;
1040         Opc = isThumb2 ? ARM::t2LDRi12 : ARM::LDRi12;
1041         RC = ARM::GPRRegisterClass;
1042       } else {
1043         Opc = ARM::VLDRS;
1044         RC = TLI.getRegClassFor(VT);
1045       }
1046       break;
1047     case MVT::f64:
1048       if (!Subtarget->hasVFP2()) return false;
1049       // FIXME: Unaligned loads need special handling.  Doublewords require
1050       // word-alignment.
1051       if (Alignment && Alignment < 4)
1052         return false;
1053
1054       Opc = ARM::VLDRD;
1055       RC = TLI.getRegClassFor(VT);
1056       break;
1057   }
1058   // Simplify this down to something we can handle.
1059   ARMSimplifyAddress(Addr, VT, useAM3);
1060
1061   // Create the base instruction, then add the operands.
1062   if (allocReg)
1063     ResultReg = createResultReg(RC);
1064   assert (ResultReg > 255 && "Expected an allocated virtual register.");
1065   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1066                                     TII.get(Opc), ResultReg);
1067   AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOLoad, useAM3);
1068
1069   // If we had an unaligned load of a float we've converted it to an regular
1070   // load.  Now we must move from the GRP to the FP register.
1071   if (needVMOV) {
1072     unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1073     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1074                             TII.get(ARM::VMOVSR), MoveReg)
1075                     .addReg(ResultReg));
1076     ResultReg = MoveReg;
1077   }
1078   return true;
1079 }
1080
1081 bool ARMFastISel::SelectLoad(const Instruction *I) {
1082   // Atomic loads need special handling.
1083   if (cast<LoadInst>(I)->isAtomic())
1084     return false;
1085
1086   // Verify we have a legal type before going any further.
1087   MVT VT;
1088   if (!isLoadTypeLegal(I->getType(), VT))
1089     return false;
1090
1091   // See if we can handle this address.
1092   Address Addr;
1093   if (!ARMComputeAddress(I->getOperand(0), Addr)) return false;
1094
1095   unsigned ResultReg;
1096   if (!ARMEmitLoad(VT, ResultReg, Addr, cast<LoadInst>(I)->getAlignment()))
1097     return false;
1098   UpdateValueMap(I, ResultReg);
1099   return true;
1100 }
1101
1102 bool ARMFastISel::ARMEmitStore(EVT VT, unsigned SrcReg, Address &Addr,
1103                                unsigned Alignment) {
1104   unsigned StrOpc;
1105   bool useAM3 = false;
1106   switch (VT.getSimpleVT().SimpleTy) {
1107     // This is mostly going to be Neon/vector support.
1108     default: return false;
1109     case MVT::i1: {
1110       unsigned Res = createResultReg(isThumb2 ? ARM::tGPRRegisterClass :
1111                                                ARM::GPRRegisterClass);
1112       unsigned Opc = isThumb2 ? ARM::t2ANDri : ARM::ANDri;
1113       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1114                               TII.get(Opc), Res)
1115                       .addReg(SrcReg).addImm(1));
1116       SrcReg = Res;
1117     } // Fallthrough here.
1118     case MVT::i8:
1119       if (isThumb2) {
1120         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1121           StrOpc = ARM::t2STRBi8;
1122         else
1123           StrOpc = ARM::t2STRBi12;
1124       } else {
1125         StrOpc = ARM::STRBi12;
1126       }
1127       break;
1128     case MVT::i16:
1129       if (isThumb2) {
1130         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1131           StrOpc = ARM::t2STRHi8;
1132         else
1133           StrOpc = ARM::t2STRHi12;
1134       } else {
1135         StrOpc = ARM::STRH;
1136         useAM3 = true;
1137       }
1138       break;
1139     case MVT::i32:
1140       if (isThumb2) {
1141         if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1142           StrOpc = ARM::t2STRi8;
1143         else
1144           StrOpc = ARM::t2STRi12;
1145       } else {
1146         StrOpc = ARM::STRi12;
1147       }
1148       break;
1149     case MVT::f32:
1150       if (!Subtarget->hasVFP2()) return false;
1151       // Unaligned stores need special handling. Floats require word-alignment.
1152       if (Alignment && Alignment < 4) {
1153         unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::i32));
1154         AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1155                                 TII.get(ARM::VMOVRS), MoveReg)
1156                         .addReg(SrcReg));
1157         SrcReg = MoveReg;
1158         VT = MVT::i32;
1159         StrOpc = isThumb2 ? ARM::t2STRi12 : ARM::STRi12;
1160       } else {
1161         StrOpc = ARM::VSTRS;
1162       }
1163       break;
1164     case MVT::f64:
1165       if (!Subtarget->hasVFP2()) return false;
1166       // FIXME: Unaligned stores need special handling.  Doublewords require
1167       // word-alignment.
1168       if (Alignment && Alignment < 4)
1169           return false;
1170
1171       StrOpc = ARM::VSTRD;
1172       break;
1173   }
1174   // Simplify this down to something we can handle.
1175   ARMSimplifyAddress(Addr, VT, useAM3);
1176
1177   // Create the base instruction, then add the operands.
1178   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1179                                     TII.get(StrOpc))
1180                             .addReg(SrcReg);
1181   AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOStore, useAM3);
1182   return true;
1183 }
1184
1185 bool ARMFastISel::SelectStore(const Instruction *I) {
1186   Value *Op0 = I->getOperand(0);
1187   unsigned SrcReg = 0;
1188
1189   // Atomic stores need special handling.
1190   if (cast<StoreInst>(I)->isAtomic())
1191     return false;
1192
1193   // Verify we have a legal type before going any further.
1194   MVT VT;
1195   if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
1196     return false;
1197
1198   // Get the value to be stored into a register.
1199   SrcReg = getRegForValue(Op0);
1200   if (SrcReg == 0) return false;
1201
1202   // See if we can handle this address.
1203   Address Addr;
1204   if (!ARMComputeAddress(I->getOperand(1), Addr))
1205     return false;
1206
1207   if (!ARMEmitStore(VT, SrcReg, Addr, cast<StoreInst>(I)->getAlignment()))
1208     return false;
1209   return true;
1210 }
1211
1212 static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
1213   switch (Pred) {
1214     // Needs two compares...
1215     case CmpInst::FCMP_ONE:
1216     case CmpInst::FCMP_UEQ:
1217     default:
1218       // AL is our "false" for now. The other two need more compares.
1219       return ARMCC::AL;
1220     case CmpInst::ICMP_EQ:
1221     case CmpInst::FCMP_OEQ:
1222       return ARMCC::EQ;
1223     case CmpInst::ICMP_SGT:
1224     case CmpInst::FCMP_OGT:
1225       return ARMCC::GT;
1226     case CmpInst::ICMP_SGE:
1227     case CmpInst::FCMP_OGE:
1228       return ARMCC::GE;
1229     case CmpInst::ICMP_UGT:
1230     case CmpInst::FCMP_UGT:
1231       return ARMCC::HI;
1232     case CmpInst::FCMP_OLT:
1233       return ARMCC::MI;
1234     case CmpInst::ICMP_ULE:
1235     case CmpInst::FCMP_OLE:
1236       return ARMCC::LS;
1237     case CmpInst::FCMP_ORD:
1238       return ARMCC::VC;
1239     case CmpInst::FCMP_UNO:
1240       return ARMCC::VS;
1241     case CmpInst::FCMP_UGE:
1242       return ARMCC::PL;
1243     case CmpInst::ICMP_SLT:
1244     case CmpInst::FCMP_ULT:
1245       return ARMCC::LT;
1246     case CmpInst::ICMP_SLE:
1247     case CmpInst::FCMP_ULE:
1248       return ARMCC::LE;
1249     case CmpInst::FCMP_UNE:
1250     case CmpInst::ICMP_NE:
1251       return ARMCC::NE;
1252     case CmpInst::ICMP_UGE:
1253       return ARMCC::HS;
1254     case CmpInst::ICMP_ULT:
1255       return ARMCC::LO;
1256   }
1257 }
1258
1259 bool ARMFastISel::SelectBranch(const Instruction *I) {
1260   const BranchInst *BI = cast<BranchInst>(I);
1261   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1262   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1263
1264   // Simple branch support.
1265
1266   // If we can, avoid recomputing the compare - redoing it could lead to wonky
1267   // behavior.
1268   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1269     if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
1270
1271       // Get the compare predicate.
1272       // Try to take advantage of fallthrough opportunities.
1273       CmpInst::Predicate Predicate = CI->getPredicate();
1274       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1275         std::swap(TBB, FBB);
1276         Predicate = CmpInst::getInversePredicate(Predicate);
1277       }
1278
1279       ARMCC::CondCodes ARMPred = getComparePred(Predicate);
1280
1281       // We may not handle every CC for now.
1282       if (ARMPred == ARMCC::AL) return false;
1283
1284       // Emit the compare.
1285       if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1286         return false;
1287
1288       unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1289       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1290       .addMBB(TBB).addImm(ARMPred).addReg(ARM::CPSR);
1291       FastEmitBranch(FBB, DL);
1292       FuncInfo.MBB->addSuccessor(TBB);
1293       return true;
1294     }
1295   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1296     MVT SourceVT;
1297     if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1298         (isLoadTypeLegal(TI->getOperand(0)->getType(), SourceVT))) {
1299       unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1300       unsigned OpReg = getRegForValue(TI->getOperand(0));
1301       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1302                               TII.get(TstOpc))
1303                       .addReg(OpReg).addImm(1));
1304
1305       unsigned CCMode = ARMCC::NE;
1306       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1307         std::swap(TBB, FBB);
1308         CCMode = ARMCC::EQ;
1309       }
1310
1311       unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1312       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1313       .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1314
1315       FastEmitBranch(FBB, DL);
1316       FuncInfo.MBB->addSuccessor(TBB);
1317       return true;
1318     }
1319   } else if (const ConstantInt *CI =
1320              dyn_cast<ConstantInt>(BI->getCondition())) {
1321     uint64_t Imm = CI->getZExtValue();
1322     MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
1323     FastEmitBranch(Target, DL);
1324     return true;
1325   }
1326
1327   unsigned CmpReg = getRegForValue(BI->getCondition());
1328   if (CmpReg == 0) return false;
1329
1330   // We've been divorced from our compare!  Our block was split, and
1331   // now our compare lives in a predecessor block.  We musn't
1332   // re-compare here, as the children of the compare aren't guaranteed
1333   // live across the block boundary (we *could* check for this).
1334   // Regardless, the compare has been done in the predecessor block,
1335   // and it left a value for us in a virtual register.  Ergo, we test
1336   // the one-bit value left in the virtual register.
1337   unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1338   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TstOpc))
1339                   .addReg(CmpReg).addImm(1));
1340
1341   unsigned CCMode = ARMCC::NE;
1342   if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1343     std::swap(TBB, FBB);
1344     CCMode = ARMCC::EQ;
1345   }
1346
1347   unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1348   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1349                   .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1350   FastEmitBranch(FBB, DL);
1351   FuncInfo.MBB->addSuccessor(TBB);
1352   return true;
1353 }
1354
1355 bool ARMFastISel::ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
1356                              bool isZExt) {
1357   Type *Ty = Src1Value->getType();
1358   EVT SrcVT = TLI.getValueType(Ty, true);
1359   if (!SrcVT.isSimple()) return false;
1360
1361   bool isFloat = (Ty->isFloatTy() || Ty->isDoubleTy());
1362   if (isFloat && !Subtarget->hasVFP2())
1363     return false;
1364
1365   // Check to see if the 2nd operand is a constant that we can encode directly
1366   // in the compare.
1367   int Imm = 0;
1368   bool UseImm = false;
1369   bool isNegativeImm = false;
1370   // FIXME: At -O0 we don't have anything that canonicalizes operand order.
1371   // Thus, Src1Value may be a ConstantInt, but we're missing it.
1372   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
1373     if (SrcVT == MVT::i32 || SrcVT == MVT::i16 || SrcVT == MVT::i8 ||
1374         SrcVT == MVT::i1) {
1375       const APInt &CIVal = ConstInt->getValue();
1376       Imm = (isZExt) ? (int)CIVal.getZExtValue() : (int)CIVal.getSExtValue();
1377       if (Imm < 0) {
1378         isNegativeImm = true;
1379         Imm = -Imm;
1380       }
1381       UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1382         (ARM_AM::getSOImmVal(Imm) != -1);
1383     }
1384   } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
1385     if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
1386       if (ConstFP->isZero() && !ConstFP->isNegative())
1387         UseImm = true;
1388   }
1389
1390   unsigned CmpOpc;
1391   bool isICmp = true;
1392   bool needsExt = false;
1393   switch (SrcVT.getSimpleVT().SimpleTy) {
1394     default: return false;
1395     // TODO: Verify compares.
1396     case MVT::f32:
1397       isICmp = false;
1398       CmpOpc = UseImm ? ARM::VCMPEZS : ARM::VCMPES;
1399       break;
1400     case MVT::f64:
1401       isICmp = false;
1402       CmpOpc = UseImm ? ARM::VCMPEZD : ARM::VCMPED;
1403       break;
1404     case MVT::i1:
1405     case MVT::i8:
1406     case MVT::i16:
1407       needsExt = true;
1408     // Intentional fall-through.
1409     case MVT::i32:
1410       if (isThumb2) {
1411         if (!UseImm)
1412           CmpOpc = ARM::t2CMPrr;
1413         else
1414           CmpOpc = isNegativeImm ? ARM::t2CMNzri : ARM::t2CMPri;
1415       } else {
1416         if (!UseImm)
1417           CmpOpc = ARM::CMPrr;
1418         else
1419           CmpOpc = isNegativeImm ? ARM::CMNzri : ARM::CMPri;
1420       }
1421       break;
1422   }
1423
1424   unsigned SrcReg1 = getRegForValue(Src1Value);
1425   if (SrcReg1 == 0) return false;
1426
1427   unsigned SrcReg2 = 0;
1428   if (!UseImm) {
1429     SrcReg2 = getRegForValue(Src2Value);
1430     if (SrcReg2 == 0) return false;
1431   }
1432
1433   // We have i1, i8, or i16, we need to either zero extend or sign extend.
1434   if (needsExt) {
1435     unsigned ResultReg;
1436     ResultReg = ARMEmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
1437     if (ResultReg == 0) return false;
1438     SrcReg1 = ResultReg;
1439     if (!UseImm) {
1440       ResultReg = ARMEmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
1441       if (ResultReg == 0) return false;
1442       SrcReg2 = ResultReg;
1443     }
1444   }
1445
1446   if (!UseImm) {
1447     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1448                             TII.get(CmpOpc))
1449                     .addReg(SrcReg1).addReg(SrcReg2));
1450   } else {
1451     MachineInstrBuilder MIB;
1452     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1453       .addReg(SrcReg1);
1454
1455     // Only add immediate for icmp as the immediate for fcmp is an implicit 0.0.
1456     if (isICmp)
1457       MIB.addImm(Imm);
1458     AddOptionalDefs(MIB);
1459   }
1460
1461   // For floating point we need to move the result to a comparison register
1462   // that we can then use for branches.
1463   if (Ty->isFloatTy() || Ty->isDoubleTy())
1464     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1465                             TII.get(ARM::FMSTAT)));
1466   return true;
1467 }
1468
1469 bool ARMFastISel::SelectCmp(const Instruction *I) {
1470   const CmpInst *CI = cast<CmpInst>(I);
1471   Type *Ty = CI->getOperand(0)->getType();
1472
1473   // Get the compare predicate.
1474   ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
1475
1476   // We may not handle every CC for now.
1477   if (ARMPred == ARMCC::AL) return false;
1478
1479   // Emit the compare.
1480   if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1481     return false;
1482
1483   // Now set a register based on the comparison. Explicitly set the predicates
1484   // here.
1485   unsigned MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1486   TargetRegisterClass *RC = isThumb2 ? ARM::rGPRRegisterClass
1487                                     : ARM::GPRRegisterClass;
1488   unsigned DestReg = createResultReg(RC);
1489   Constant *Zero = ConstantInt::get(Type::getInt32Ty(*Context), 0);
1490   unsigned ZeroReg = TargetMaterializeConstant(Zero);
1491   bool isFloat = (Ty->isFloatTy() || Ty->isDoubleTy());
1492   unsigned CondReg = isFloat ? ARM::FPSCR : ARM::CPSR;
1493   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), DestReg)
1494           .addReg(ZeroReg).addImm(1)
1495           .addImm(ARMPred).addReg(CondReg);
1496
1497   UpdateValueMap(I, DestReg);
1498   return true;
1499 }
1500
1501 bool ARMFastISel::SelectFPExt(const Instruction *I) {
1502   // Make sure we have VFP and that we're extending float to double.
1503   if (!Subtarget->hasVFP2()) return false;
1504
1505   Value *V = I->getOperand(0);
1506   if (!I->getType()->isDoubleTy() ||
1507       !V->getType()->isFloatTy()) return false;
1508
1509   unsigned Op = getRegForValue(V);
1510   if (Op == 0) return false;
1511
1512   unsigned Result = createResultReg(ARM::DPRRegisterClass);
1513   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1514                           TII.get(ARM::VCVTDS), Result)
1515                   .addReg(Op));
1516   UpdateValueMap(I, Result);
1517   return true;
1518 }
1519
1520 bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
1521   // Make sure we have VFP and that we're truncating double to float.
1522   if (!Subtarget->hasVFP2()) return false;
1523
1524   Value *V = I->getOperand(0);
1525   if (!(I->getType()->isFloatTy() &&
1526         V->getType()->isDoubleTy())) return false;
1527
1528   unsigned Op = getRegForValue(V);
1529   if (Op == 0) return false;
1530
1531   unsigned Result = createResultReg(ARM::SPRRegisterClass);
1532   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1533                           TII.get(ARM::VCVTSD), Result)
1534                   .addReg(Op));
1535   UpdateValueMap(I, Result);
1536   return true;
1537 }
1538
1539 bool ARMFastISel::SelectIToFP(const Instruction *I, bool isSigned) {
1540   // Make sure we have VFP.
1541   if (!Subtarget->hasVFP2()) return false;
1542
1543   MVT DstVT;
1544   Type *Ty = I->getType();
1545   if (!isTypeLegal(Ty, DstVT))
1546     return false;
1547
1548   Value *Src = I->getOperand(0);
1549   EVT SrcVT = TLI.getValueType(Src->getType(), true);
1550   if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
1551     return false;
1552
1553   unsigned SrcReg = getRegForValue(Src);
1554   if (SrcReg == 0) return false;
1555
1556   // Handle sign-extension.
1557   if (SrcVT == MVT::i16 || SrcVT == MVT::i8) {
1558     EVT DestVT = MVT::i32;
1559     unsigned ResultReg = ARMEmitIntExt(SrcVT, SrcReg, DestVT,
1560                                        /*isZExt*/!isSigned);
1561     if (ResultReg == 0) return false;
1562     SrcReg = ResultReg;
1563   }
1564
1565   // The conversion routine works on fp-reg to fp-reg and the operand above
1566   // was an integer, move it to the fp registers if possible.
1567   unsigned FP = ARMMoveToFPReg(MVT::f32, SrcReg);
1568   if (FP == 0) return false;
1569
1570   unsigned Opc;
1571   if (Ty->isFloatTy()) Opc = isSigned ? ARM::VSITOS : ARM::VUITOS;
1572   else if (Ty->isDoubleTy()) Opc = isSigned ? ARM::VSITOD : ARM::VUITOD;
1573   else return false;
1574
1575   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1576   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1577                           ResultReg)
1578                   .addReg(FP));
1579   UpdateValueMap(I, ResultReg);
1580   return true;
1581 }
1582
1583 bool ARMFastISel::SelectFPToI(const Instruction *I, bool isSigned) {
1584   // Make sure we have VFP.
1585   if (!Subtarget->hasVFP2()) return false;
1586
1587   MVT DstVT;
1588   Type *RetTy = I->getType();
1589   if (!isTypeLegal(RetTy, DstVT))
1590     return false;
1591
1592   unsigned Op = getRegForValue(I->getOperand(0));
1593   if (Op == 0) return false;
1594
1595   unsigned Opc;
1596   Type *OpTy = I->getOperand(0)->getType();
1597   if (OpTy->isFloatTy()) Opc = isSigned ? ARM::VTOSIZS : ARM::VTOUIZS;
1598   else if (OpTy->isDoubleTy()) Opc = isSigned ? ARM::VTOSIZD : ARM::VTOUIZD;
1599   else return false;
1600
1601   // f64->s32/u32 or f32->s32/u32 both need an intermediate f32 reg.
1602   unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1603   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1604                           ResultReg)
1605                   .addReg(Op));
1606
1607   // This result needs to be in an integer register, but the conversion only
1608   // takes place in fp-regs.
1609   unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1610   if (IntReg == 0) return false;
1611
1612   UpdateValueMap(I, IntReg);
1613   return true;
1614 }
1615
1616 bool ARMFastISel::SelectSelect(const Instruction *I) {
1617   MVT VT;
1618   if (!isTypeLegal(I->getType(), VT))
1619     return false;
1620
1621   // Things need to be register sized for register moves.
1622   if (VT != MVT::i32) return false;
1623   const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
1624
1625   unsigned CondReg = getRegForValue(I->getOperand(0));
1626   if (CondReg == 0) return false;
1627   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1628   if (Op1Reg == 0) return false;
1629
1630   // Check to see if we can use an immediate in the conditional move.
1631   int Imm = 0;
1632   bool UseImm = false;
1633   bool isNegativeImm = false;
1634   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(2))) {
1635     assert (VT == MVT::i32 && "Expecting an i32.");
1636     Imm = (int)ConstInt->getValue().getZExtValue();
1637     if (Imm < 0) {
1638       isNegativeImm = true;
1639       Imm = ~Imm;
1640     }
1641     UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1642       (ARM_AM::getSOImmVal(Imm) != -1);
1643   }
1644
1645   unsigned Op2Reg = 0;
1646   if (!UseImm) {
1647     Op2Reg = getRegForValue(I->getOperand(2));
1648     if (Op2Reg == 0) return false;
1649   }
1650
1651   unsigned CmpOpc = isThumb2 ? ARM::t2CMPri : ARM::CMPri;
1652   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1653                   .addReg(CondReg).addImm(0));
1654
1655   unsigned MovCCOpc;
1656   if (!UseImm) {
1657     MovCCOpc = isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr;
1658   } else {
1659     if (!isNegativeImm) {
1660       MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1661     } else {
1662       MovCCOpc = isThumb2 ? ARM::t2MVNCCi : ARM::MVNCCi;
1663     }
1664   }
1665   unsigned ResultReg = createResultReg(RC);
1666   if (!UseImm)
1667     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1668     .addReg(Op2Reg).addReg(Op1Reg).addImm(ARMCC::NE).addReg(ARM::CPSR);
1669   else
1670     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1671     .addReg(Op1Reg).addImm(Imm).addImm(ARMCC::EQ).addReg(ARM::CPSR);
1672   UpdateValueMap(I, ResultReg);
1673   return true;
1674 }
1675
1676 bool ARMFastISel::SelectDiv(const Instruction *I, bool isSigned) {
1677   MVT VT;
1678   Type *Ty = I->getType();
1679   if (!isTypeLegal(Ty, VT))
1680     return false;
1681
1682   // If we have integer div support we should have selected this automagically.
1683   // In case we have a real miss go ahead and return false and we'll pick
1684   // it up later.
1685   if (Subtarget->hasDivide()) return false;
1686
1687   // Otherwise emit a libcall.
1688   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1689   if (VT == MVT::i8)
1690     LC = isSigned ? RTLIB::SDIV_I8 : RTLIB::UDIV_I8;
1691   else if (VT == MVT::i16)
1692     LC = isSigned ? RTLIB::SDIV_I16 : RTLIB::UDIV_I16;
1693   else if (VT == MVT::i32)
1694     LC = isSigned ? RTLIB::SDIV_I32 : RTLIB::UDIV_I32;
1695   else if (VT == MVT::i64)
1696     LC = isSigned ? RTLIB::SDIV_I64 : RTLIB::UDIV_I64;
1697   else if (VT == MVT::i128)
1698     LC = isSigned ? RTLIB::SDIV_I128 : RTLIB::UDIV_I128;
1699   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1700
1701   return ARMEmitLibcall(I, LC);
1702 }
1703
1704 bool ARMFastISel::SelectRem(const Instruction *I, bool isSigned) {
1705   MVT VT;
1706   Type *Ty = I->getType();
1707   if (!isTypeLegal(Ty, VT))
1708     return false;
1709
1710   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1711   if (VT == MVT::i8)
1712     LC = isSigned ? RTLIB::SREM_I8 : RTLIB::UREM_I8;
1713   else if (VT == MVT::i16)
1714     LC = isSigned ? RTLIB::SREM_I16 : RTLIB::UREM_I16;
1715   else if (VT == MVT::i32)
1716     LC = isSigned ? RTLIB::SREM_I32 : RTLIB::UREM_I32;
1717   else if (VT == MVT::i64)
1718     LC = isSigned ? RTLIB::SREM_I64 : RTLIB::UREM_I64;
1719   else if (VT == MVT::i128)
1720     LC = isSigned ? RTLIB::SREM_I128 : RTLIB::UREM_I128;
1721   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1722
1723   return ARMEmitLibcall(I, LC);
1724 }
1725
1726 bool ARMFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1727   assert (ISDOpcode == ISD::ADD && "Expected an add.");
1728   EVT DestVT  = TLI.getValueType(I->getType(), true);
1729
1730   // We can get here in the case when we have a binary operation on a non-legal
1731   // type and the target independent selector doesn't know how to handle it.
1732   if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
1733     return false;
1734   
1735   unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1736   if (SrcReg1 == 0) return false;
1737
1738   // TODO: Often the 2nd operand is an immediate, which can be encoded directly
1739   // in the instruction, rather then materializing the value in a register.
1740   unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1741   if (SrcReg2 == 0) return false;
1742
1743   unsigned Opc = isThumb2 ? ARM::t2ADDrr : ARM::ADDrr;
1744   unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::i32));
1745   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1746                           TII.get(Opc), ResultReg)
1747                   .addReg(SrcReg1).addReg(SrcReg2));
1748   UpdateValueMap(I, ResultReg);
1749   return true;
1750 }
1751
1752 bool ARMFastISel::SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode) {
1753   EVT VT  = TLI.getValueType(I->getType(), true);
1754
1755   // We can get here in the case when we want to use NEON for our fp
1756   // operations, but can't figure out how to. Just use the vfp instructions
1757   // if we have them.
1758   // FIXME: It'd be nice to use NEON instructions.
1759   Type *Ty = I->getType();
1760   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1761   if (isFloat && !Subtarget->hasVFP2())
1762     return false;
1763
1764   unsigned Opc;
1765   bool is64bit = VT == MVT::f64 || VT == MVT::i64;
1766   switch (ISDOpcode) {
1767     default: return false;
1768     case ISD::FADD:
1769       Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1770       break;
1771     case ISD::FSUB:
1772       Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1773       break;
1774     case ISD::FMUL:
1775       Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1776       break;
1777   }
1778   unsigned Op1 = getRegForValue(I->getOperand(0));
1779   if (Op1 == 0) return false;
1780
1781   unsigned Op2 = getRegForValue(I->getOperand(1));
1782   if (Op2 == 0) return false;
1783
1784   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1785   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1786                           TII.get(Opc), ResultReg)
1787                   .addReg(Op1).addReg(Op2));
1788   UpdateValueMap(I, ResultReg);
1789   return true;
1790 }
1791
1792 // Call Handling Code
1793
1794 // This is largely taken directly from CCAssignFnForNode - we don't support
1795 // varargs in FastISel so that part has been removed.
1796 // TODO: We may not support all of this.
1797 CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC, bool Return) {
1798   switch (CC) {
1799   default:
1800     llvm_unreachable("Unsupported calling convention");
1801   case CallingConv::Fast:
1802     // Ignore fastcc. Silence compiler warnings.
1803     (void)RetFastCC_ARM_APCS;
1804     (void)FastCC_ARM_APCS;
1805     // Fallthrough
1806   case CallingConv::C:
1807     // Use target triple & subtarget features to do actual dispatch.
1808     if (Subtarget->isAAPCS_ABI()) {
1809       if (Subtarget->hasVFP2() &&
1810           TM.Options.FloatABIType == FloatABI::Hard)
1811         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1812       else
1813         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1814     } else
1815         return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1816   case CallingConv::ARM_AAPCS_VFP:
1817     return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1818   case CallingConv::ARM_AAPCS:
1819     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1820   case CallingConv::ARM_APCS:
1821     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1822   }
1823 }
1824
1825 bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1826                                   SmallVectorImpl<unsigned> &ArgRegs,
1827                                   SmallVectorImpl<MVT> &ArgVTs,
1828                                   SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1829                                   SmallVectorImpl<unsigned> &RegArgs,
1830                                   CallingConv::ID CC,
1831                                   unsigned &NumBytes) {
1832   SmallVector<CCValAssign, 16> ArgLocs;
1833   CCState CCInfo(CC, false, *FuncInfo.MF, TM, ArgLocs, *Context);
1834   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC, false));
1835
1836   // Get a count of how many bytes are to be pushed on the stack.
1837   NumBytes = CCInfo.getNextStackOffset();
1838
1839   // Issue CALLSEQ_START
1840   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1841   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1842                           TII.get(AdjStackDown))
1843                   .addImm(NumBytes));
1844
1845   // Process the args.
1846   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1847     CCValAssign &VA = ArgLocs[i];
1848     unsigned Arg = ArgRegs[VA.getValNo()];
1849     MVT ArgVT = ArgVTs[VA.getValNo()];
1850
1851     // We don't handle NEON/vector parameters yet.
1852     if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64)
1853       return false;
1854
1855     // Handle arg promotion, etc.
1856     switch (VA.getLocInfo()) {
1857       case CCValAssign::Full: break;
1858       case CCValAssign::SExt: {
1859         MVT DestVT = VA.getLocVT();
1860         unsigned ResultReg = ARMEmitIntExt(ArgVT, Arg, DestVT,
1861                                            /*isZExt*/false);
1862         assert (ResultReg != 0 && "Failed to emit a sext");
1863         Arg = ResultReg;
1864         ArgVT = DestVT;
1865         break;
1866       }
1867       case CCValAssign::AExt:
1868         // Intentional fall-through.  Handle AExt and ZExt.
1869       case CCValAssign::ZExt: {
1870         MVT DestVT = VA.getLocVT();
1871         unsigned ResultReg = ARMEmitIntExt(ArgVT, Arg, DestVT,
1872                                            /*isZExt*/true);
1873         assert (ResultReg != 0 && "Failed to emit a sext");
1874         Arg = ResultReg;
1875         ArgVT = DestVT;
1876         break;
1877       }
1878       case CCValAssign::BCvt: {
1879         unsigned BC = FastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, Arg,
1880                                  /*TODO: Kill=*/false);
1881         assert(BC != 0 && "Failed to emit a bitcast!");
1882         Arg = BC;
1883         ArgVT = VA.getLocVT();
1884         break;
1885       }
1886       default: llvm_unreachable("Unknown arg promotion!");
1887     }
1888
1889     // Now copy/store arg to correct locations.
1890     if (VA.isRegLoc() && !VA.needsCustom()) {
1891       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1892               VA.getLocReg())
1893         .addReg(Arg);
1894       RegArgs.push_back(VA.getLocReg());
1895     } else if (VA.needsCustom()) {
1896       // TODO: We need custom lowering for vector (v2f64) args.
1897       if (VA.getLocVT() != MVT::f64) return false;
1898
1899       CCValAssign &NextVA = ArgLocs[++i];
1900
1901       // TODO: Only handle register args for now.
1902       if(!(VA.isRegLoc() && NextVA.isRegLoc())) return false;
1903
1904       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1905                               TII.get(ARM::VMOVRRD), VA.getLocReg())
1906                       .addReg(NextVA.getLocReg(), RegState::Define)
1907                       .addReg(Arg));
1908       RegArgs.push_back(VA.getLocReg());
1909       RegArgs.push_back(NextVA.getLocReg());
1910     } else {
1911       assert(VA.isMemLoc());
1912       // Need to store on the stack.
1913       Address Addr;
1914       Addr.BaseType = Address::RegBase;
1915       Addr.Base.Reg = ARM::SP;
1916       Addr.Offset = VA.getLocMemOffset();
1917
1918       if (!ARMEmitStore(ArgVT, Arg, Addr)) return false;
1919     }
1920   }
1921   return true;
1922 }
1923
1924 bool ARMFastISel::FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1925                              const Instruction *I, CallingConv::ID CC,
1926                              unsigned &NumBytes) {
1927   // Issue CALLSEQ_END
1928   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1929   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1930                           TII.get(AdjStackUp))
1931                   .addImm(NumBytes).addImm(0));
1932
1933   // Now the return value.
1934   if (RetVT != MVT::isVoid) {
1935     SmallVector<CCValAssign, 16> RVLocs;
1936     CCState CCInfo(CC, false, *FuncInfo.MF, TM, RVLocs, *Context);
1937     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true));
1938
1939     // Copy all of the result registers out of their specified physreg.
1940     if (RVLocs.size() == 2 && RetVT == MVT::f64) {
1941       // For this move we copy into two registers and then move into the
1942       // double fp reg we want.
1943       EVT DestVT = RVLocs[0].getValVT();
1944       TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
1945       unsigned ResultReg = createResultReg(DstRC);
1946       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1947                               TII.get(ARM::VMOVDRR), ResultReg)
1948                       .addReg(RVLocs[0].getLocReg())
1949                       .addReg(RVLocs[1].getLocReg()));
1950
1951       UsedRegs.push_back(RVLocs[0].getLocReg());
1952       UsedRegs.push_back(RVLocs[1].getLocReg());
1953
1954       // Finally update the result.
1955       UpdateValueMap(I, ResultReg);
1956     } else {
1957       assert(RVLocs.size() == 1 &&"Can't handle non-double multi-reg retvals!");
1958       EVT CopyVT = RVLocs[0].getValVT();
1959
1960       // Special handling for extended integers.
1961       if (RetVT == MVT::i1 || RetVT == MVT::i8 || RetVT == MVT::i16)
1962         CopyVT = MVT::i32;
1963
1964       TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1965
1966       unsigned ResultReg = createResultReg(DstRC);
1967       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1968               ResultReg).addReg(RVLocs[0].getLocReg());
1969       UsedRegs.push_back(RVLocs[0].getLocReg());
1970
1971       // Finally update the result.
1972       UpdateValueMap(I, ResultReg);
1973     }
1974   }
1975
1976   return true;
1977 }
1978
1979 bool ARMFastISel::SelectRet(const Instruction *I) {
1980   const ReturnInst *Ret = cast<ReturnInst>(I);
1981   const Function &F = *I->getParent()->getParent();
1982
1983   if (!FuncInfo.CanLowerReturn)
1984     return false;
1985
1986   if (F.isVarArg())
1987     return false;
1988
1989   CallingConv::ID CC = F.getCallingConv();
1990   if (Ret->getNumOperands() > 0) {
1991     SmallVector<ISD::OutputArg, 4> Outs;
1992     GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
1993                   Outs, TLI);
1994
1995     // Analyze operands of the call, assigning locations to each operand.
1996     SmallVector<CCValAssign, 16> ValLocs;
1997     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,I->getContext());
1998     CCInfo.AnalyzeReturn(Outs, CCAssignFnForCall(CC, true /* is Ret */));
1999
2000     const Value *RV = Ret->getOperand(0);
2001     unsigned Reg = getRegForValue(RV);
2002     if (Reg == 0)
2003       return false;
2004
2005     // Only handle a single return value for now.
2006     if (ValLocs.size() != 1)
2007       return false;
2008
2009     CCValAssign &VA = ValLocs[0];
2010
2011     // Don't bother handling odd stuff for now.
2012     if (VA.getLocInfo() != CCValAssign::Full)
2013       return false;
2014     // Only handle register returns for now.
2015     if (!VA.isRegLoc())
2016       return false;
2017
2018     unsigned SrcReg = Reg + VA.getValNo();
2019     EVT RVVT = TLI.getValueType(RV->getType());
2020     EVT DestVT = VA.getValVT();
2021     // Special handling for extended integers.
2022     if (RVVT != DestVT) {
2023       if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
2024         return false;
2025
2026       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
2027         return false;
2028
2029       assert(DestVT == MVT::i32 && "ARM should always ext to i32");
2030
2031       bool isZExt = Outs[0].Flags.isZExt();
2032       unsigned ResultReg = ARMEmitIntExt(RVVT, SrcReg, DestVT, isZExt);
2033       if (ResultReg == 0) return false;
2034       SrcReg = ResultReg;
2035     }
2036
2037     // Make the copy.
2038     unsigned DstReg = VA.getLocReg();
2039     const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
2040     // Avoid a cross-class copy. This is very unlikely.
2041     if (!SrcRC->contains(DstReg))
2042       return false;
2043     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2044             DstReg).addReg(SrcReg);
2045
2046     // Mark the register as live out of the function.
2047     MRI.addLiveOut(VA.getLocReg());
2048   }
2049
2050   unsigned RetOpc = isThumb2 ? ARM::tBX_RET : ARM::BX_RET;
2051   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2052                           TII.get(RetOpc)));
2053   return true;
2054 }
2055
2056 unsigned ARMFastISel::ARMSelectCallOp(const GlobalValue *GV) {
2057
2058   // iOS needs the r9 versions of the opcodes.
2059   bool isiOS = Subtarget->isTargetIOS();
2060   if (isThumb2) {
2061     return isiOS ? ARM::tBLr9 : ARM::tBL;
2062   } else  {
2063     return isiOS ? ARM::BLr9 : ARM::BL;
2064   }
2065 }
2066
2067 // A quick function that will emit a call for a named libcall in F with the
2068 // vector of passed arguments for the Instruction in I. We can assume that we
2069 // can emit a call for any libcall we can produce. This is an abridged version
2070 // of the full call infrastructure since we won't need to worry about things
2071 // like computed function pointers or strange arguments at call sites.
2072 // TODO: Try to unify this and the normal call bits for ARM, then try to unify
2073 // with X86.
2074 bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
2075   CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
2076
2077   // Handle *simple* calls for now.
2078   Type *RetTy = I->getType();
2079   MVT RetVT;
2080   if (RetTy->isVoidTy())
2081     RetVT = MVT::isVoid;
2082   else if (!isTypeLegal(RetTy, RetVT))
2083     return false;
2084
2085   // TODO: For now if we have long calls specified we don't handle the call.
2086   if (EnableARMLongCalls) return false;
2087
2088   // Set up the argument vectors.
2089   SmallVector<Value*, 8> Args;
2090   SmallVector<unsigned, 8> ArgRegs;
2091   SmallVector<MVT, 8> ArgVTs;
2092   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2093   Args.reserve(I->getNumOperands());
2094   ArgRegs.reserve(I->getNumOperands());
2095   ArgVTs.reserve(I->getNumOperands());
2096   ArgFlags.reserve(I->getNumOperands());
2097   for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2098     Value *Op = I->getOperand(i);
2099     unsigned Arg = getRegForValue(Op);
2100     if (Arg == 0) return false;
2101
2102     Type *ArgTy = Op->getType();
2103     MVT ArgVT;
2104     if (!isTypeLegal(ArgTy, ArgVT)) return false;
2105
2106     ISD::ArgFlagsTy Flags;
2107     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
2108     Flags.setOrigAlign(OriginalAlignment);
2109
2110     Args.push_back(Op);
2111     ArgRegs.push_back(Arg);
2112     ArgVTs.push_back(ArgVT);
2113     ArgFlags.push_back(Flags);
2114   }
2115
2116   // Handle the arguments now that we've gotten them.
2117   SmallVector<unsigned, 4> RegArgs;
2118   unsigned NumBytes;
2119   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
2120     return false;
2121
2122   // Issue the call, BLr9 for iOS, BL otherwise.
2123   // TODO: Turn this into the table of arm call ops.
2124   MachineInstrBuilder MIB;
2125   unsigned CallOpc = ARMSelectCallOp(NULL);
2126   if(isThumb2)
2127     // Explicitly adding the predicate here.
2128     MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2129                          TII.get(CallOpc)))
2130                          .addExternalSymbol(TLI.getLibcallName(Call));
2131   else
2132     // Explicitly adding the predicate here.
2133     MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2134                          TII.get(CallOpc))
2135           .addExternalSymbol(TLI.getLibcallName(Call)));
2136
2137   // Add implicit physical register uses to the call.
2138   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2139     MIB.addReg(RegArgs[i]);
2140
2141   // Finish off the call including any return values.
2142   SmallVector<unsigned, 4> UsedRegs;
2143   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
2144
2145   // Set all unused physreg defs as dead.
2146   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2147
2148   return true;
2149 }
2150
2151 bool ARMFastISel::SelectCall(const Instruction *I,
2152                              const char *IntrMemName = 0) {
2153   const CallInst *CI = cast<CallInst>(I);
2154   const Value *Callee = CI->getCalledValue();
2155
2156   // Can't handle inline asm.
2157   if (isa<InlineAsm>(Callee)) return false;
2158
2159   // Only handle global variable Callees.
2160   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
2161   if (!GV)
2162     return false;
2163
2164   // Check the calling convention.
2165   ImmutableCallSite CS(CI);
2166   CallingConv::ID CC = CS.getCallingConv();
2167
2168   // TODO: Avoid some calling conventions?
2169
2170   // Let SDISel handle vararg functions.
2171   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2172   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2173   if (FTy->isVarArg())
2174     return false;
2175
2176   // Handle *simple* calls for now.
2177   Type *RetTy = I->getType();
2178   MVT RetVT;
2179   if (RetTy->isVoidTy())
2180     RetVT = MVT::isVoid;
2181   else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
2182            RetVT != MVT::i8  && RetVT != MVT::i1)
2183     return false;
2184
2185   // TODO: For now if we have long calls specified we don't handle the call.
2186   if (EnableARMLongCalls) return false;
2187
2188   // Set up the argument vectors.
2189   SmallVector<Value*, 8> Args;
2190   SmallVector<unsigned, 8> ArgRegs;
2191   SmallVector<MVT, 8> ArgVTs;
2192   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2193   Args.reserve(CS.arg_size());
2194   ArgRegs.reserve(CS.arg_size());
2195   ArgVTs.reserve(CS.arg_size());
2196   ArgFlags.reserve(CS.arg_size());
2197   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2198        i != e; ++i) {
2199     // If we're lowering a memory intrinsic instead of a regular call, skip the
2200     // last two arguments, which shouldn't be passed to the underlying function.
2201     if (IntrMemName && e-i <= 2)
2202       break;
2203
2204     ISD::ArgFlagsTy Flags;
2205     unsigned AttrInd = i - CS.arg_begin() + 1;
2206     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2207       Flags.setSExt();
2208     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2209       Flags.setZExt();
2210
2211     // FIXME: Only handle *easy* calls for now.
2212     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
2213         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
2214         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
2215         CS.paramHasAttr(AttrInd, Attribute::ByVal))
2216       return false;
2217
2218     Type *ArgTy = (*i)->getType();
2219     MVT ArgVT;
2220     if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8 &&
2221         ArgVT != MVT::i1)
2222       return false;
2223
2224     unsigned Arg = getRegForValue(*i);
2225     if (Arg == 0)
2226       return false;
2227
2228     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
2229     Flags.setOrigAlign(OriginalAlignment);
2230
2231     Args.push_back(*i);
2232     ArgRegs.push_back(Arg);
2233     ArgVTs.push_back(ArgVT);
2234     ArgFlags.push_back(Flags);
2235   }
2236
2237   // Handle the arguments now that we've gotten them.
2238   SmallVector<unsigned, 4> RegArgs;
2239   unsigned NumBytes;
2240   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
2241     return false;
2242
2243   // Issue the call, BLr9 for iOS, BL otherwise.
2244   // TODO: Turn this into the table of arm call ops.
2245   MachineInstrBuilder MIB;
2246   unsigned CallOpc = ARMSelectCallOp(GV);
2247   // Explicitly adding the predicate here.
2248   if(isThumb2) {
2249     // Explicitly adding the predicate here.
2250     MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2251                                  TII.get(CallOpc)));
2252     if (!IntrMemName)
2253       MIB.addGlobalAddress(GV, 0, 0);
2254     else 
2255       MIB.addExternalSymbol(IntrMemName, 0);
2256   } else {
2257     if (!IntrMemName)
2258       // Explicitly adding the predicate here.
2259       MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2260                                    TII.get(CallOpc))
2261             .addGlobalAddress(GV, 0, 0));
2262     else
2263       MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2264                                    TII.get(CallOpc))
2265             .addExternalSymbol(IntrMemName, 0));
2266   }
2267   
2268   // Add implicit physical register uses to the call.
2269   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2270     MIB.addReg(RegArgs[i]);
2271
2272   // Finish off the call including any return values.
2273   SmallVector<unsigned, 4> UsedRegs;
2274   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
2275
2276   // Set all unused physreg defs as dead.
2277   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2278
2279   return true;
2280 }
2281
2282 bool ARMFastISel::ARMIsMemCpySmall(uint64_t Len) {
2283   return Len <= 16;
2284 }
2285
2286 bool ARMFastISel::ARMTryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len) {
2287   // Make sure we don't bloat code by inlining very large memcpy's.
2288   if (!ARMIsMemCpySmall(Len))
2289     return false;
2290
2291   // We don't care about alignment here since we just emit integer accesses.
2292   while (Len) {
2293     MVT VT;
2294     if (Len >= 4)
2295       VT = MVT::i32;
2296     else if (Len >= 2)
2297       VT = MVT::i16;
2298     else {
2299       assert(Len == 1);
2300       VT = MVT::i8;
2301     }
2302
2303     bool RV;
2304     unsigned ResultReg;
2305     RV = ARMEmitLoad(VT, ResultReg, Src);
2306     assert (RV == true && "Should be able to handle this load.");
2307     RV = ARMEmitStore(VT, ResultReg, Dest);
2308     assert (RV == true && "Should be able to handle this store.");
2309     (void)RV;
2310
2311     unsigned Size = VT.getSizeInBits()/8;
2312     Len -= Size;
2313     Dest.Offset += Size;
2314     Src.Offset += Size;
2315   }
2316
2317   return true;
2318 }
2319
2320 bool ARMFastISel::SelectIntrinsicCall(const IntrinsicInst &I) {
2321   // FIXME: Handle more intrinsics.
2322   switch (I.getIntrinsicID()) {
2323   default: return false;
2324   case Intrinsic::memcpy:
2325   case Intrinsic::memmove: {
2326     const MemTransferInst &MTI = cast<MemTransferInst>(I);
2327     // Don't handle volatile.
2328     if (MTI.isVolatile())
2329       return false;
2330
2331     // Disable inlining for memmove before calls to ComputeAddress.  Otherwise,
2332     // we would emit dead code because we don't currently handle memmoves.
2333     bool isMemCpy = (I.getIntrinsicID() == Intrinsic::memcpy);
2334     if (isa<ConstantInt>(MTI.getLength()) && isMemCpy) {
2335       // Small memcpy's are common enough that we want to do them without a call
2336       // if possible.
2337       uint64_t Len = cast<ConstantInt>(MTI.getLength())->getZExtValue();
2338       if (ARMIsMemCpySmall(Len)) {
2339         Address Dest, Src;
2340         if (!ARMComputeAddress(MTI.getRawDest(), Dest) ||
2341             !ARMComputeAddress(MTI.getRawSource(), Src))
2342           return false;
2343         if (ARMTryEmitSmallMemCpy(Dest, Src, Len))
2344           return true;
2345       }
2346     }
2347     
2348     if (!MTI.getLength()->getType()->isIntegerTy(32))
2349       return false;
2350     
2351     if (MTI.getSourceAddressSpace() > 255 || MTI.getDestAddressSpace() > 255)
2352       return false;
2353
2354     const char *IntrMemName = isa<MemCpyInst>(I) ? "memcpy" : "memmove";
2355     return SelectCall(&I, IntrMemName);
2356   }
2357   case Intrinsic::memset: {
2358     const MemSetInst &MSI = cast<MemSetInst>(I);
2359     // Don't handle volatile.
2360     if (MSI.isVolatile())
2361       return false;
2362     
2363     if (!MSI.getLength()->getType()->isIntegerTy(32))
2364       return false;
2365     
2366     if (MSI.getDestAddressSpace() > 255)
2367       return false;
2368     
2369     return SelectCall(&I, "memset");
2370   }
2371   }
2372 }
2373
2374 bool ARMFastISel::SelectTrunc(const Instruction *I) {
2375   // The high bits for a type smaller than the register size are assumed to be 
2376   // undefined.
2377   Value *Op = I->getOperand(0);
2378
2379   EVT SrcVT, DestVT;
2380   SrcVT = TLI.getValueType(Op->getType(), true);
2381   DestVT = TLI.getValueType(I->getType(), true);
2382
2383   if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
2384     return false;
2385   if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
2386     return false;
2387
2388   unsigned SrcReg = getRegForValue(Op);
2389   if (!SrcReg) return false;
2390
2391   // Because the high bits are undefined, a truncate doesn't generate
2392   // any code.
2393   UpdateValueMap(I, SrcReg);
2394   return true;
2395 }
2396
2397 unsigned ARMFastISel::ARMEmitIntExt(EVT SrcVT, unsigned SrcReg, EVT DestVT,
2398                                     bool isZExt) {
2399   if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
2400     return 0;
2401
2402   unsigned Opc;
2403   bool isBoolZext = false;
2404   if (!SrcVT.isSimple()) return 0;
2405   switch (SrcVT.getSimpleVT().SimpleTy) {
2406   default: return 0;
2407   case MVT::i16:
2408     if (!Subtarget->hasV6Ops()) return 0;
2409     if (isZExt)
2410       Opc = isThumb2 ? ARM::t2UXTH : ARM::UXTH;
2411     else
2412       Opc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
2413     break;
2414   case MVT::i8:
2415     if (!Subtarget->hasV6Ops()) return 0;
2416     if (isZExt)
2417       Opc = isThumb2 ? ARM::t2UXTB : ARM::UXTB;
2418     else
2419       Opc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
2420     break;
2421   case MVT::i1:
2422     if (isZExt) {
2423       Opc = isThumb2 ? ARM::t2ANDri : ARM::ANDri;
2424       isBoolZext = true;
2425       break;
2426     }
2427     return 0;
2428   }
2429
2430   unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::i32));
2431   MachineInstrBuilder MIB;
2432   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
2433         .addReg(SrcReg);
2434   if (isBoolZext)
2435     MIB.addImm(1);
2436   else
2437     MIB.addImm(0);
2438   AddOptionalDefs(MIB);
2439   return ResultReg;
2440 }
2441
2442 bool ARMFastISel::SelectIntExt(const Instruction *I) {
2443   // On ARM, in general, integer casts don't involve legal types; this code
2444   // handles promotable integers.
2445   Type *DestTy = I->getType();
2446   Value *Src = I->getOperand(0);
2447   Type *SrcTy = Src->getType();
2448
2449   EVT SrcVT, DestVT;
2450   SrcVT = TLI.getValueType(SrcTy, true);
2451   DestVT = TLI.getValueType(DestTy, true);
2452
2453   bool isZExt = isa<ZExtInst>(I);
2454   unsigned SrcReg = getRegForValue(Src);
2455   if (!SrcReg) return false;
2456
2457   unsigned ResultReg = ARMEmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
2458   if (ResultReg == 0) return false;
2459   UpdateValueMap(I, ResultReg);
2460   return true;
2461 }
2462
2463 // TODO: SoftFP support.
2464 bool ARMFastISel::TargetSelectInstruction(const Instruction *I) {
2465
2466   switch (I->getOpcode()) {
2467     case Instruction::Load:
2468       return SelectLoad(I);
2469     case Instruction::Store:
2470       return SelectStore(I);
2471     case Instruction::Br:
2472       return SelectBranch(I);
2473     case Instruction::ICmp:
2474     case Instruction::FCmp:
2475       return SelectCmp(I);
2476     case Instruction::FPExt:
2477       return SelectFPExt(I);
2478     case Instruction::FPTrunc:
2479       return SelectFPTrunc(I);
2480     case Instruction::SIToFP:
2481       return SelectIToFP(I, /*isSigned*/ true);
2482     case Instruction::UIToFP:
2483       return SelectIToFP(I, /*isSigned*/ false);
2484     case Instruction::FPToSI:
2485       return SelectFPToI(I, /*isSigned*/ true);
2486     case Instruction::FPToUI:
2487       return SelectFPToI(I, /*isSigned*/ false);
2488     case Instruction::Add:
2489       return SelectBinaryIntOp(I, ISD::ADD);
2490     case Instruction::FAdd:
2491       return SelectBinaryFPOp(I, ISD::FADD);
2492     case Instruction::FSub:
2493       return SelectBinaryFPOp(I, ISD::FSUB);
2494     case Instruction::FMul:
2495       return SelectBinaryFPOp(I, ISD::FMUL);
2496     case Instruction::SDiv:
2497       return SelectDiv(I, /*isSigned*/ true);
2498     case Instruction::UDiv:
2499       return SelectDiv(I, /*isSigned*/ false);
2500     case Instruction::SRem:
2501       return SelectRem(I, /*isSigned*/ true);
2502     case Instruction::URem:
2503       return SelectRem(I, /*isSigned*/ false);
2504     case Instruction::Call:
2505       if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2506         return SelectIntrinsicCall(*II);
2507       return SelectCall(I);
2508     case Instruction::Select:
2509       return SelectSelect(I);
2510     case Instruction::Ret:
2511       return SelectRet(I);
2512     case Instruction::Trunc:
2513       return SelectTrunc(I);
2514     case Instruction::ZExt:
2515     case Instruction::SExt:
2516       return SelectIntExt(I);
2517     default: break;
2518   }
2519   return false;
2520 }
2521
2522 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
2523 /// vreg is being provided by the specified load instruction.  If possible,
2524 /// try to fold the load as an operand to the instruction, returning true if
2525 /// successful.
2526 bool ARMFastISel::TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
2527                                 const LoadInst *LI) {
2528   // Verify we have a legal type before going any further.
2529   MVT VT;
2530   if (!isLoadTypeLegal(LI->getType(), VT))
2531     return false;
2532
2533   // Combine load followed by zero- or sign-extend.
2534   // ldrb r1, [r0]       ldrb r1, [r0]
2535   // uxtb r2, r1     =>
2536   // mov  r3, r2         mov  r3, r1
2537   bool isZExt = true;
2538   switch(MI->getOpcode()) {
2539     default: return false;
2540     case ARM::SXTH:
2541     case ARM::t2SXTH:
2542       isZExt = false;
2543     case ARM::UXTH:
2544     case ARM::t2UXTH:
2545       if (VT != MVT::i16)
2546         return false;
2547     break;
2548     case ARM::SXTB:
2549     case ARM::t2SXTB:
2550       isZExt = false;
2551     case ARM::UXTB:
2552     case ARM::t2UXTB:
2553       if (VT != MVT::i8)
2554         return false;
2555     break;
2556   }
2557   // See if we can handle this address.
2558   Address Addr;
2559   if (!ARMComputeAddress(LI->getOperand(0), Addr)) return false;
2560   
2561   unsigned ResultReg = MI->getOperand(0).getReg();
2562   if (!ARMEmitLoad(VT, ResultReg, Addr, LI->getAlignment(), isZExt, false))
2563     return false;
2564   MI->eraseFromParent();
2565   return true;
2566 }
2567
2568 namespace llvm {
2569   llvm::FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo) {
2570     // Completely untested on non-iOS.
2571     const TargetMachine &TM = funcInfo.MF->getTarget();
2572
2573     // Darwin and thumb1 only for now.
2574     const ARMSubtarget *Subtarget = &TM.getSubtarget<ARMSubtarget>();
2575     if (Subtarget->isTargetIOS() && !Subtarget->isThumb1Only() &&
2576         !DisableARMFastISel)
2577       return new ARMFastISel(funcInfo);
2578     return 0;
2579   }
2580 }