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