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