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