1 //===-- AArch6464FastISel.cpp - AArch64 FastISel implementation -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the AArch64-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // AArch64GenFastISel.inc, which is #included here.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "AArch64.h"
17 #include "AArch64CallingConvention.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/FastISel.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GetElementPtrTypeIterator.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/MC/MCSymbol.h"
40 using namespace llvm;
41 
42 namespace {
43 
44 class AArch64FastISel final : public FastISel {
45   class Address {
46   public:
47     typedef enum {
48       RegBase,
49       FrameIndexBase
50     } BaseKind;
51 
52   private:
53     BaseKind Kind;
54     AArch64_AM::ShiftExtendType ExtType;
55     union {
56       unsigned Reg;
57       int FI;
58     } Base;
59     unsigned OffsetReg;
60     unsigned Shift;
61     int64_t Offset;
62     const GlobalValue *GV;
63 
64   public:
65     Address() : Kind(RegBase), ExtType(AArch64_AM::InvalidShiftExtend),
66       OffsetReg(0), Shift(0), Offset(0), GV(nullptr) { Base.Reg = 0; }
67     void setKind(BaseKind K) { Kind = K; }
68     BaseKind getKind() const { return Kind; }
69     void setExtendType(AArch64_AM::ShiftExtendType E) { ExtType = E; }
70     AArch64_AM::ShiftExtendType getExtendType() const { return ExtType; }
71     bool isRegBase() const { return Kind == RegBase; }
72     bool isFIBase() const { return Kind == FrameIndexBase; }
73     void setReg(unsigned Reg) {
74       assert(isRegBase() && "Invalid base register access!");
75       Base.Reg = Reg;
76     }
77     unsigned getReg() const {
78       assert(isRegBase() && "Invalid base register access!");
79       return Base.Reg;
80     }
81     void setOffsetReg(unsigned Reg) {
82       OffsetReg = Reg;
83     }
84     unsigned getOffsetReg() const {
85       return OffsetReg;
86     }
87     void setFI(unsigned FI) {
88       assert(isFIBase() && "Invalid base frame index  access!");
89       Base.FI = FI;
90     }
91     unsigned getFI() const {
92       assert(isFIBase() && "Invalid base frame index access!");
93       return Base.FI;
94     }
95     void setOffset(int64_t O) { Offset = O; }
96     int64_t getOffset() { return Offset; }
97     void setShift(unsigned S) { Shift = S; }
98     unsigned getShift() { return Shift; }
99 
100     void setGlobalValue(const GlobalValue *G) { GV = G; }
101     const GlobalValue *getGlobalValue() { return GV; }
102   };
103 
104   /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
105   /// make the right decision when generating code for different targets.
106   const AArch64Subtarget *Subtarget;
107   LLVMContext *Context;
108 
109   bool fastLowerArguments() override;
110   bool fastLowerCall(CallLoweringInfo &CLI) override;
111   bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
112 
113 private:
114   // Selection routines.
115   bool selectAddSub(const Instruction *I);
116   bool selectLogicalOp(const Instruction *I);
117   bool selectLoad(const Instruction *I);
118   bool selectStore(const Instruction *I);
119   bool selectBranch(const Instruction *I);
120   bool selectIndirectBr(const Instruction *I);
121   bool selectCmp(const Instruction *I);
122   bool selectSelect(const Instruction *I);
123   bool selectFPExt(const Instruction *I);
124   bool selectFPTrunc(const Instruction *I);
125   bool selectFPToInt(const Instruction *I, bool Signed);
126   bool selectIntToFP(const Instruction *I, bool Signed);
127   bool selectRem(const Instruction *I, unsigned ISDOpcode);
128   bool selectRet(const Instruction *I);
129   bool selectTrunc(const Instruction *I);
130   bool selectIntExt(const Instruction *I);
131   bool selectMul(const Instruction *I);
132   bool selectShift(const Instruction *I);
133   bool selectBitCast(const Instruction *I);
134   bool selectFRem(const Instruction *I);
135   bool selectSDiv(const Instruction *I);
136   bool selectGetElementPtr(const Instruction *I);
137 
138   // Utility helper routines.
139   bool isTypeLegal(Type *Ty, MVT &VT);
140   bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
141   bool isValueAvailable(const Value *V) const;
142   bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
143   bool computeCallAddress(const Value *V, Address &Addr);
144   bool simplifyAddress(Address &Addr, MVT VT);
145   void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
146                             unsigned Flags, unsigned ScaleFactor,
147                             MachineMemOperand *MMO);
148   bool isMemCpySmall(uint64_t Len, unsigned Alignment);
149   bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
150                           unsigned Alignment);
151   bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
152                          const Value *Cond);
153   bool optimizeIntExtLoad(const Instruction *I, MVT RetVT, MVT SrcVT);
154   bool optimizeSelect(const SelectInst *SI);
155   std::pair<unsigned, bool> getRegForGEPIndex(const Value *Idx);
156 
157   // Emit helper routines.
158   unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
159                       const Value *RHS, bool SetFlags = false,
160                       bool WantResult = true,  bool IsZExt = false);
161   unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
162                          bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
163                          bool SetFlags = false, bool WantResult = true);
164   unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
165                          bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
166                          bool WantResult = true);
167   unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
168                          bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
169                          AArch64_AM::ShiftExtendType ShiftType,
170                          uint64_t ShiftImm, bool SetFlags = false,
171                          bool WantResult = true);
172   unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
173                          bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
174                           AArch64_AM::ShiftExtendType ExtType,
175                           uint64_t ShiftImm, bool SetFlags = false,
176                          bool WantResult = true);
177 
178   // Emit functions.
179   bool emitCompareAndBranch(const BranchInst *BI);
180   bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
181   bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
182   bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
183   bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
184   unsigned emitLoad(MVT VT, MVT ResultVT, Address Addr, bool WantZExt = true,
185                     MachineMemOperand *MMO = nullptr);
186   bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
187                  MachineMemOperand *MMO = nullptr);
188   unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
189   unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
190   unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
191                    bool SetFlags = false, bool WantResult = true,
192                    bool IsZExt = false);
193   unsigned emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill, int64_t Imm);
194   unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
195                    bool SetFlags = false, bool WantResult = true,
196                    bool IsZExt = false);
197   unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
198                        unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
199   unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
200                        unsigned RHSReg, bool RHSIsKill,
201                        AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
202                        bool WantResult = true);
203   unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
204                          const Value *RHS);
205   unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
206                             bool LHSIsKill, uint64_t Imm);
207   unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
208                             bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
209                             uint64_t ShiftImm);
210   unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
211   unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
212                       unsigned Op1, bool Op1IsKill);
213   unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
214                         unsigned Op1, bool Op1IsKill);
215   unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
216                         unsigned Op1, bool Op1IsKill);
217   unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
218                       unsigned Op1Reg, bool Op1IsKill);
219   unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
220                       uint64_t Imm, bool IsZExt = true);
221   unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
222                       unsigned Op1Reg, bool Op1IsKill);
223   unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
224                       uint64_t Imm, bool IsZExt = true);
225   unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
226                       unsigned Op1Reg, bool Op1IsKill);
227   unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
228                       uint64_t Imm, bool IsZExt = false);
229 
230   unsigned materializeInt(const ConstantInt *CI, MVT VT);
231   unsigned materializeFP(const ConstantFP *CFP, MVT VT);
232   unsigned materializeGV(const GlobalValue *GV);
233 
234   // Call handling routines.
235 private:
236   CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
237   bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
238                        unsigned &NumBytes);
239   bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
240 
241 public:
242   // Backend specific FastISel code.
243   unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
244   unsigned fastMaterializeConstant(const Constant *C) override;
245   unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
246 
247   explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
248                            const TargetLibraryInfo *LibInfo)
249       : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
250     Subtarget =
251         &static_cast<const AArch64Subtarget &>(FuncInfo.MF->getSubtarget());
252     Context = &FuncInfo.Fn->getContext();
253   }
254 
255   bool fastSelectInstruction(const Instruction *I) override;
256 
257 #include "AArch64GenFastISel.inc"
258 };
259 
260 } // end anonymous namespace
261 
262 #include "AArch64GenCallingConv.inc"
263 
264 /// \brief Check if the sign-/zero-extend will be a noop.
265 static bool isIntExtFree(const Instruction *I) {
266   assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
267          "Unexpected integer extend instruction.");
268   assert(!I->getType()->isVectorTy() && I->getType()->isIntegerTy() &&
269          "Unexpected value type.");
270   bool IsZExt = isa<ZExtInst>(I);
271 
272   if (const auto *LI = dyn_cast<LoadInst>(I->getOperand(0)))
273     if (LI->hasOneUse())
274       return true;
275 
276   if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0)))
277     if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr()))
278       return true;
279 
280   return false;
281 }
282 
283 /// \brief Determine the implicit scale factor that is applied by a memory
284 /// operation for a given value type.
285 static unsigned getImplicitScaleFactor(MVT VT) {
286   switch (VT.SimpleTy) {
287   default:
288     return 0;    // invalid
289   case MVT::i1:  // fall-through
290   case MVT::i8:
291     return 1;
292   case MVT::i16:
293     return 2;
294   case MVT::i32: // fall-through
295   case MVT::f32:
296     return 4;
297   case MVT::i64: // fall-through
298   case MVT::f64:
299     return 8;
300   }
301 }
302 
303 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
304   if (CC == CallingConv::WebKit_JS)
305     return CC_AArch64_WebKit_JS;
306   if (CC == CallingConv::GHC)
307     return CC_AArch64_GHC;
308   return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
309 }
310 
311 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
312   assert(TLI.getValueType(DL, AI->getType(), true) == MVT::i64 &&
313          "Alloca should always return a pointer.");
314 
315   // Don't handle dynamic allocas.
316   if (!FuncInfo.StaticAllocaMap.count(AI))
317     return 0;
318 
319   DenseMap<const AllocaInst *, int>::iterator SI =
320       FuncInfo.StaticAllocaMap.find(AI);
321 
322   if (SI != FuncInfo.StaticAllocaMap.end()) {
323     unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
324     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
325             ResultReg)
326         .addFrameIndex(SI->second)
327         .addImm(0)
328         .addImm(0);
329     return ResultReg;
330   }
331 
332   return 0;
333 }
334 
335 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
336   if (VT > MVT::i64)
337     return 0;
338 
339   if (!CI->isZero())
340     return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
341 
342   // Create a copy from the zero register to materialize a "0" value.
343   const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
344                                                    : &AArch64::GPR32RegClass;
345   unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
346   unsigned ResultReg = createResultReg(RC);
347   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
348           ResultReg).addReg(ZeroReg, getKillRegState(true));
349   return ResultReg;
350 }
351 
352 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
353   // Positive zero (+0.0) has to be materialized with a fmov from the zero
354   // register, because the immediate version of fmov cannot encode zero.
355   if (CFP->isNullValue())
356     return fastMaterializeFloatZero(CFP);
357 
358   if (VT != MVT::f32 && VT != MVT::f64)
359     return 0;
360 
361   const APFloat Val = CFP->getValueAPF();
362   bool Is64Bit = (VT == MVT::f64);
363   // This checks to see if we can use FMOV instructions to materialize
364   // a constant, otherwise we have to materialize via the constant pool.
365   if (TLI.isFPImmLegal(Val, VT)) {
366     int Imm =
367         Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
368     assert((Imm != -1) && "Cannot encode floating-point constant.");
369     unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
370     return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
371   }
372 
373   // For the MachO large code model materialize the FP constant in code.
374   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
375     unsigned Opc1 = Is64Bit ? AArch64::MOVi64imm : AArch64::MOVi32imm;
376     const TargetRegisterClass *RC = Is64Bit ?
377         &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
378 
379     unsigned TmpReg = createResultReg(RC);
380     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc1), TmpReg)
381         .addImm(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
382 
383     unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
384     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
385             TII.get(TargetOpcode::COPY), ResultReg)
386         .addReg(TmpReg, getKillRegState(true));
387 
388     return ResultReg;
389   }
390 
391   // Materialize via constant pool.  MachineConstantPool wants an explicit
392   // alignment.
393   unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
394   if (Align == 0)
395     Align = DL.getTypeAllocSize(CFP->getType());
396 
397   unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
398   unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
399   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
400           ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
401 
402   unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
403   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
404   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
405       .addReg(ADRPReg)
406       .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
407   return ResultReg;
408 }
409 
410 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
411   // We can't handle thread-local variables quickly yet.
412   if (GV->isThreadLocal())
413     return 0;
414 
415   // MachO still uses GOT for large code-model accesses, but ELF requires
416   // movz/movk sequences, which FastISel doesn't handle yet.
417   if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
418     return 0;
419 
420   unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
421 
422   EVT DestEVT = TLI.getValueType(DL, GV->getType(), true);
423   if (!DestEVT.isSimple())
424     return 0;
425 
426   unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
427   unsigned ResultReg;
428 
429   if (OpFlags & AArch64II::MO_GOT) {
430     // ADRP + LDRX
431     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
432             ADRPReg)
433       .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
434 
435     ResultReg = createResultReg(&AArch64::GPR64RegClass);
436     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
437             ResultReg)
438       .addReg(ADRPReg)
439       .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
440                         AArch64II::MO_NC);
441   } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
442     // We can't handle addresses loaded from a constant pool quickly yet.
443     return 0;
444   } else {
445     // ADRP + ADDX
446     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
447             ADRPReg)
448       .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
449 
450     ResultReg = createResultReg(&AArch64::GPR64spRegClass);
451     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
452             ResultReg)
453       .addReg(ADRPReg)
454       .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
455       .addImm(0);
456   }
457   return ResultReg;
458 }
459 
460 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
461   EVT CEVT = TLI.getValueType(DL, C->getType(), true);
462 
463   // Only handle simple types.
464   if (!CEVT.isSimple())
465     return 0;
466   MVT VT = CEVT.getSimpleVT();
467 
468   if (const auto *CI = dyn_cast<ConstantInt>(C))
469     return materializeInt(CI, VT);
470   else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
471     return materializeFP(CFP, VT);
472   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
473     return materializeGV(GV);
474 
475   return 0;
476 }
477 
478 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
479   assert(CFP->isNullValue() &&
480          "Floating-point constant is not a positive zero.");
481   MVT VT;
482   if (!isTypeLegal(CFP->getType(), VT))
483     return 0;
484 
485   if (VT != MVT::f32 && VT != MVT::f64)
486     return 0;
487 
488   bool Is64Bit = (VT == MVT::f64);
489   unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
490   unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
491   return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
492 }
493 
494 /// \brief Check if the multiply is by a power-of-2 constant.
495 static bool isMulPowOf2(const Value *I) {
496   if (const auto *MI = dyn_cast<MulOperator>(I)) {
497     if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
498       if (C->getValue().isPowerOf2())
499         return true;
500     if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
501       if (C->getValue().isPowerOf2())
502         return true;
503   }
504   return false;
505 }
506 
507 // Computes the address to get to an object.
508 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
509 {
510   const User *U = nullptr;
511   unsigned Opcode = Instruction::UserOp1;
512   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
513     // Don't walk into other basic blocks unless the object is an alloca from
514     // another block, otherwise it may not have a virtual register assigned.
515     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
516         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
517       Opcode = I->getOpcode();
518       U = I;
519     }
520   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
521     Opcode = C->getOpcode();
522     U = C;
523   }
524 
525   if (auto *Ty = dyn_cast<PointerType>(Obj->getType()))
526     if (Ty->getAddressSpace() > 255)
527       // Fast instruction selection doesn't support the special
528       // address spaces.
529       return false;
530 
531   switch (Opcode) {
532   default:
533     break;
534   case Instruction::BitCast: {
535     // Look through bitcasts.
536     return computeAddress(U->getOperand(0), Addr, Ty);
537   }
538   case Instruction::IntToPtr: {
539     // Look past no-op inttoptrs.
540     if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
541         TLI.getPointerTy(DL))
542       return computeAddress(U->getOperand(0), Addr, Ty);
543     break;
544   }
545   case Instruction::PtrToInt: {
546     // Look past no-op ptrtoints.
547     if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
548       return computeAddress(U->getOperand(0), Addr, Ty);
549     break;
550   }
551   case Instruction::GetElementPtr: {
552     Address SavedAddr = Addr;
553     uint64_t TmpOffset = Addr.getOffset();
554 
555     // Iterate through the GEP folding the constants into offsets where
556     // we can.
557     for (gep_type_iterator GTI = gep_type_begin(U), E = gep_type_end(U);
558          GTI != E; ++GTI) {
559       const Value *Op = GTI.getOperand();
560       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
561         const StructLayout *SL = DL.getStructLayout(STy);
562         unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
563         TmpOffset += SL->getElementOffset(Idx);
564       } else {
565         uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
566         for (;;) {
567           if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
568             // Constant-offset addressing.
569             TmpOffset += CI->getSExtValue() * S;
570             break;
571           }
572           if (canFoldAddIntoGEP(U, Op)) {
573             // A compatible add with a constant operand. Fold the constant.
574             ConstantInt *CI =
575                 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
576             TmpOffset += CI->getSExtValue() * S;
577             // Iterate on the other operand.
578             Op = cast<AddOperator>(Op)->getOperand(0);
579             continue;
580           }
581           // Unsupported
582           goto unsupported_gep;
583         }
584       }
585     }
586 
587     // Try to grab the base operand now.
588     Addr.setOffset(TmpOffset);
589     if (computeAddress(U->getOperand(0), Addr, Ty))
590       return true;
591 
592     // We failed, restore everything and try the other options.
593     Addr = SavedAddr;
594 
595   unsupported_gep:
596     break;
597   }
598   case Instruction::Alloca: {
599     const AllocaInst *AI = cast<AllocaInst>(Obj);
600     DenseMap<const AllocaInst *, int>::iterator SI =
601         FuncInfo.StaticAllocaMap.find(AI);
602     if (SI != FuncInfo.StaticAllocaMap.end()) {
603       Addr.setKind(Address::FrameIndexBase);
604       Addr.setFI(SI->second);
605       return true;
606     }
607     break;
608   }
609   case Instruction::Add: {
610     // Adds of constants are common and easy enough.
611     const Value *LHS = U->getOperand(0);
612     const Value *RHS = U->getOperand(1);
613 
614     if (isa<ConstantInt>(LHS))
615       std::swap(LHS, RHS);
616 
617     if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
618       Addr.setOffset(Addr.getOffset() + CI->getSExtValue());
619       return computeAddress(LHS, Addr, Ty);
620     }
621 
622     Address Backup = Addr;
623     if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
624       return true;
625     Addr = Backup;
626 
627     break;
628   }
629   case Instruction::Sub: {
630     // Subs of constants are common and easy enough.
631     const Value *LHS = U->getOperand(0);
632     const Value *RHS = U->getOperand(1);
633 
634     if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
635       Addr.setOffset(Addr.getOffset() - CI->getSExtValue());
636       return computeAddress(LHS, Addr, Ty);
637     }
638     break;
639   }
640   case Instruction::Shl: {
641     if (Addr.getOffsetReg())
642       break;
643 
644     const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1));
645     if (!CI)
646       break;
647 
648     unsigned Val = CI->getZExtValue();
649     if (Val < 1 || Val > 3)
650       break;
651 
652     uint64_t NumBytes = 0;
653     if (Ty && Ty->isSized()) {
654       uint64_t NumBits = DL.getTypeSizeInBits(Ty);
655       NumBytes = NumBits / 8;
656       if (!isPowerOf2_64(NumBits))
657         NumBytes = 0;
658     }
659 
660     if (NumBytes != (1ULL << Val))
661       break;
662 
663     Addr.setShift(Val);
664     Addr.setExtendType(AArch64_AM::LSL);
665 
666     const Value *Src = U->getOperand(0);
667     if (const auto *I = dyn_cast<Instruction>(Src)) {
668       if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
669         // Fold the zext or sext when it won't become a noop.
670         if (const auto *ZE = dyn_cast<ZExtInst>(I)) {
671           if (!isIntExtFree(ZE) &&
672               ZE->getOperand(0)->getType()->isIntegerTy(32)) {
673             Addr.setExtendType(AArch64_AM::UXTW);
674             Src = ZE->getOperand(0);
675           }
676         } else if (const auto *SE = dyn_cast<SExtInst>(I)) {
677           if (!isIntExtFree(SE) &&
678               SE->getOperand(0)->getType()->isIntegerTy(32)) {
679             Addr.setExtendType(AArch64_AM::SXTW);
680             Src = SE->getOperand(0);
681           }
682         }
683       }
684     }
685 
686     if (const auto *AI = dyn_cast<BinaryOperator>(Src))
687       if (AI->getOpcode() == Instruction::And) {
688         const Value *LHS = AI->getOperand(0);
689         const Value *RHS = AI->getOperand(1);
690 
691         if (const auto *C = dyn_cast<ConstantInt>(LHS))
692           if (C->getValue() == 0xffffffff)
693             std::swap(LHS, RHS);
694 
695         if (const auto *C = dyn_cast<ConstantInt>(RHS))
696           if (C->getValue() == 0xffffffff) {
697             Addr.setExtendType(AArch64_AM::UXTW);
698             unsigned Reg = getRegForValue(LHS);
699             if (!Reg)
700               return false;
701             bool RegIsKill = hasTrivialKill(LHS);
702             Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
703                                              AArch64::sub_32);
704             Addr.setOffsetReg(Reg);
705             return true;
706           }
707       }
708 
709     unsigned Reg = getRegForValue(Src);
710     if (!Reg)
711       return false;
712     Addr.setOffsetReg(Reg);
713     return true;
714   }
715   case Instruction::Mul: {
716     if (Addr.getOffsetReg())
717       break;
718 
719     if (!isMulPowOf2(U))
720       break;
721 
722     const Value *LHS = U->getOperand(0);
723     const Value *RHS = U->getOperand(1);
724 
725     // Canonicalize power-of-2 value to the RHS.
726     if (const auto *C = dyn_cast<ConstantInt>(LHS))
727       if (C->getValue().isPowerOf2())
728         std::swap(LHS, RHS);
729 
730     assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
731     const auto *C = cast<ConstantInt>(RHS);
732     unsigned Val = C->getValue().logBase2();
733     if (Val < 1 || Val > 3)
734       break;
735 
736     uint64_t NumBytes = 0;
737     if (Ty && Ty->isSized()) {
738       uint64_t NumBits = DL.getTypeSizeInBits(Ty);
739       NumBytes = NumBits / 8;
740       if (!isPowerOf2_64(NumBits))
741         NumBytes = 0;
742     }
743 
744     if (NumBytes != (1ULL << Val))
745       break;
746 
747     Addr.setShift(Val);
748     Addr.setExtendType(AArch64_AM::LSL);
749 
750     const Value *Src = LHS;
751     if (const auto *I = dyn_cast<Instruction>(Src)) {
752       if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
753         // Fold the zext or sext when it won't become a noop.
754         if (const auto *ZE = dyn_cast<ZExtInst>(I)) {
755           if (!isIntExtFree(ZE) &&
756               ZE->getOperand(0)->getType()->isIntegerTy(32)) {
757             Addr.setExtendType(AArch64_AM::UXTW);
758             Src = ZE->getOperand(0);
759           }
760         } else if (const auto *SE = dyn_cast<SExtInst>(I)) {
761           if (!isIntExtFree(SE) &&
762               SE->getOperand(0)->getType()->isIntegerTy(32)) {
763             Addr.setExtendType(AArch64_AM::SXTW);
764             Src = SE->getOperand(0);
765           }
766         }
767       }
768     }
769 
770     unsigned Reg = getRegForValue(Src);
771     if (!Reg)
772       return false;
773     Addr.setOffsetReg(Reg);
774     return true;
775   }
776   case Instruction::And: {
777     if (Addr.getOffsetReg())
778       break;
779 
780     if (!Ty || DL.getTypeSizeInBits(Ty) != 8)
781       break;
782 
783     const Value *LHS = U->getOperand(0);
784     const Value *RHS = U->getOperand(1);
785 
786     if (const auto *C = dyn_cast<ConstantInt>(LHS))
787       if (C->getValue() == 0xffffffff)
788         std::swap(LHS, RHS);
789 
790     if (const auto *C = dyn_cast<ConstantInt>(RHS))
791       if (C->getValue() == 0xffffffff) {
792         Addr.setShift(0);
793         Addr.setExtendType(AArch64_AM::LSL);
794         Addr.setExtendType(AArch64_AM::UXTW);
795 
796         unsigned Reg = getRegForValue(LHS);
797         if (!Reg)
798           return false;
799         bool RegIsKill = hasTrivialKill(LHS);
800         Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
801                                          AArch64::sub_32);
802         Addr.setOffsetReg(Reg);
803         return true;
804       }
805     break;
806   }
807   case Instruction::SExt:
808   case Instruction::ZExt: {
809     if (!Addr.getReg() || Addr.getOffsetReg())
810       break;
811 
812     const Value *Src = nullptr;
813     // Fold the zext or sext when it won't become a noop.
814     if (const auto *ZE = dyn_cast<ZExtInst>(U)) {
815       if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
816         Addr.setExtendType(AArch64_AM::UXTW);
817         Src = ZE->getOperand(0);
818       }
819     } else if (const auto *SE = dyn_cast<SExtInst>(U)) {
820       if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
821         Addr.setExtendType(AArch64_AM::SXTW);
822         Src = SE->getOperand(0);
823       }
824     }
825 
826     if (!Src)
827       break;
828 
829     Addr.setShift(0);
830     unsigned Reg = getRegForValue(Src);
831     if (!Reg)
832       return false;
833     Addr.setOffsetReg(Reg);
834     return true;
835   }
836   } // end switch
837 
838   if (Addr.isRegBase() && !Addr.getReg()) {
839     unsigned Reg = getRegForValue(Obj);
840     if (!Reg)
841       return false;
842     Addr.setReg(Reg);
843     return true;
844   }
845 
846   if (!Addr.getOffsetReg()) {
847     unsigned Reg = getRegForValue(Obj);
848     if (!Reg)
849       return false;
850     Addr.setOffsetReg(Reg);
851     return true;
852   }
853 
854   return false;
855 }
856 
857 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
858   const User *U = nullptr;
859   unsigned Opcode = Instruction::UserOp1;
860   bool InMBB = true;
861 
862   if (const auto *I = dyn_cast<Instruction>(V)) {
863     Opcode = I->getOpcode();
864     U = I;
865     InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
866   } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
867     Opcode = C->getOpcode();
868     U = C;
869   }
870 
871   switch (Opcode) {
872   default: break;
873   case Instruction::BitCast:
874     // Look past bitcasts if its operand is in the same BB.
875     if (InMBB)
876       return computeCallAddress(U->getOperand(0), Addr);
877     break;
878   case Instruction::IntToPtr:
879     // Look past no-op inttoptrs if its operand is in the same BB.
880     if (InMBB &&
881         TLI.getValueType(DL, U->getOperand(0)->getType()) ==
882             TLI.getPointerTy(DL))
883       return computeCallAddress(U->getOperand(0), Addr);
884     break;
885   case Instruction::PtrToInt:
886     // Look past no-op ptrtoints if its operand is in the same BB.
887     if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
888       return computeCallAddress(U->getOperand(0), Addr);
889     break;
890   }
891 
892   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
893     Addr.setGlobalValue(GV);
894     return true;
895   }
896 
897   // If all else fails, try to materialize the value in a register.
898   if (!Addr.getGlobalValue()) {
899     Addr.setReg(getRegForValue(V));
900     return Addr.getReg() != 0;
901   }
902 
903   return false;
904 }
905 
906 
907 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
908   EVT evt = TLI.getValueType(DL, Ty, true);
909 
910   // Only handle simple types.
911   if (evt == MVT::Other || !evt.isSimple())
912     return false;
913   VT = evt.getSimpleVT();
914 
915   // This is a legal type, but it's not something we handle in fast-isel.
916   if (VT == MVT::f128)
917     return false;
918 
919   // Handle all other legal types, i.e. a register that will directly hold this
920   // value.
921   return TLI.isTypeLegal(VT);
922 }
923 
924 /// \brief Determine if the value type is supported by FastISel.
925 ///
926 /// FastISel for AArch64 can handle more value types than are legal. This adds
927 /// simple value type such as i1, i8, and i16.
928 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
929   if (Ty->isVectorTy() && !IsVectorAllowed)
930     return false;
931 
932   if (isTypeLegal(Ty, VT))
933     return true;
934 
935   // If this is a type than can be sign or zero-extended to a basic operation
936   // go ahead and accept it now.
937   if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
938     return true;
939 
940   return false;
941 }
942 
943 bool AArch64FastISel::isValueAvailable(const Value *V) const {
944   if (!isa<Instruction>(V))
945     return true;
946 
947   const auto *I = cast<Instruction>(V);
948   return FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB;
949 }
950 
951 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
952   unsigned ScaleFactor = getImplicitScaleFactor(VT);
953   if (!ScaleFactor)
954     return false;
955 
956   bool ImmediateOffsetNeedsLowering = false;
957   bool RegisterOffsetNeedsLowering = false;
958   int64_t Offset = Addr.getOffset();
959   if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
960     ImmediateOffsetNeedsLowering = true;
961   else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
962            !isUInt<12>(Offset / ScaleFactor))
963     ImmediateOffsetNeedsLowering = true;
964 
965   // Cannot encode an offset register and an immediate offset in the same
966   // instruction. Fold the immediate offset into the load/store instruction and
967   // emit an additional add to take care of the offset register.
968   if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.getOffsetReg())
969     RegisterOffsetNeedsLowering = true;
970 
971   // Cannot encode zero register as base.
972   if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
973     RegisterOffsetNeedsLowering = true;
974 
975   // If this is a stack pointer and the offset needs to be simplified then put
976   // the alloca address into a register, set the base type back to register and
977   // continue. This should almost never happen.
978   if ((ImmediateOffsetNeedsLowering || Addr.getOffsetReg()) && Addr.isFIBase())
979   {
980     unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
981     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
982             ResultReg)
983       .addFrameIndex(Addr.getFI())
984       .addImm(0)
985       .addImm(0);
986     Addr.setKind(Address::RegBase);
987     Addr.setReg(ResultReg);
988   }
989 
990   if (RegisterOffsetNeedsLowering) {
991     unsigned ResultReg = 0;
992     if (Addr.getReg()) {
993       if (Addr.getExtendType() == AArch64_AM::SXTW ||
994           Addr.getExtendType() == AArch64_AM::UXTW   )
995         ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
996                                   /*TODO:IsKill=*/false, Addr.getOffsetReg(),
997                                   /*TODO:IsKill=*/false, Addr.getExtendType(),
998                                   Addr.getShift());
999       else
1000         ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
1001                                   /*TODO:IsKill=*/false, Addr.getOffsetReg(),
1002                                   /*TODO:IsKill=*/false, AArch64_AM::LSL,
1003                                   Addr.getShift());
1004     } else {
1005       if (Addr.getExtendType() == AArch64_AM::UXTW)
1006         ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
1007                                /*Op0IsKill=*/false, Addr.getShift(),
1008                                /*IsZExt=*/true);
1009       else if (Addr.getExtendType() == AArch64_AM::SXTW)
1010         ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
1011                                /*Op0IsKill=*/false, Addr.getShift(),
1012                                /*IsZExt=*/false);
1013       else
1014         ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
1015                                /*Op0IsKill=*/false, Addr.getShift());
1016     }
1017     if (!ResultReg)
1018       return false;
1019 
1020     Addr.setReg(ResultReg);
1021     Addr.setOffsetReg(0);
1022     Addr.setShift(0);
1023     Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
1024   }
1025 
1026   // Since the offset is too large for the load/store instruction get the
1027   // reg+offset into a register.
1028   if (ImmediateOffsetNeedsLowering) {
1029     unsigned ResultReg;
1030     if (Addr.getReg())
1031       // Try to fold the immediate into the add instruction.
1032       ResultReg = emitAdd_ri_(MVT::i64, Addr.getReg(), /*IsKill=*/false, Offset);
1033     else
1034       ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1035 
1036     if (!ResultReg)
1037       return false;
1038     Addr.setReg(ResultReg);
1039     Addr.setOffset(0);
1040   }
1041   return true;
1042 }
1043 
1044 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
1045                                            const MachineInstrBuilder &MIB,
1046                                            unsigned Flags,
1047                                            unsigned ScaleFactor,
1048                                            MachineMemOperand *MMO) {
1049   int64_t Offset = Addr.getOffset() / ScaleFactor;
1050   // Frame base works a bit differently. Handle it separately.
1051   if (Addr.isFIBase()) {
1052     int FI = Addr.getFI();
1053     // FIXME: We shouldn't be using getObjectSize/getObjectAlignment.  The size
1054     // and alignment should be based on the VT.
1055     MMO = FuncInfo.MF->getMachineMemOperand(
1056         MachinePointerInfo::getFixedStack(*FuncInfo.MF, FI, Offset), Flags,
1057         MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1058     // Now add the rest of the operands.
1059     MIB.addFrameIndex(FI).addImm(Offset);
1060   } else {
1061     assert(Addr.isRegBase() && "Unexpected address kind.");
1062     const MCInstrDesc &II = MIB->getDesc();
1063     unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1064     Addr.setReg(
1065       constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1066     Addr.setOffsetReg(
1067       constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1068     if (Addr.getOffsetReg()) {
1069       assert(Addr.getOffset() == 0 && "Unexpected offset");
1070       bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1071                       Addr.getExtendType() == AArch64_AM::SXTX;
1072       MIB.addReg(Addr.getReg());
1073       MIB.addReg(Addr.getOffsetReg());
1074       MIB.addImm(IsSigned);
1075       MIB.addImm(Addr.getShift() != 0);
1076     } else
1077       MIB.addReg(Addr.getReg()).addImm(Offset);
1078   }
1079 
1080   if (MMO)
1081     MIB.addMemOperand(MMO);
1082 }
1083 
1084 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1085                                      const Value *RHS, bool SetFlags,
1086                                      bool WantResult,  bool IsZExt) {
1087   AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1088   bool NeedExtend = false;
1089   switch (RetVT.SimpleTy) {
1090   default:
1091     return 0;
1092   case MVT::i1:
1093     NeedExtend = true;
1094     break;
1095   case MVT::i8:
1096     NeedExtend = true;
1097     ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1098     break;
1099   case MVT::i16:
1100     NeedExtend = true;
1101     ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1102     break;
1103   case MVT::i32:  // fall-through
1104   case MVT::i64:
1105     break;
1106   }
1107   MVT SrcVT = RetVT;
1108   RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1109 
1110   // Canonicalize immediates to the RHS first.
1111   if (UseAdd && isa<Constant>(LHS) && !isa<Constant>(RHS))
1112     std::swap(LHS, RHS);
1113 
1114   // Canonicalize mul by power of 2 to the RHS.
1115   if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1116     if (isMulPowOf2(LHS))
1117       std::swap(LHS, RHS);
1118 
1119   // Canonicalize shift immediate to the RHS.
1120   if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1121     if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1122       if (isa<ConstantInt>(SI->getOperand(1)))
1123         if (SI->getOpcode() == Instruction::Shl  ||
1124             SI->getOpcode() == Instruction::LShr ||
1125             SI->getOpcode() == Instruction::AShr   )
1126           std::swap(LHS, RHS);
1127 
1128   unsigned LHSReg = getRegForValue(LHS);
1129   if (!LHSReg)
1130     return 0;
1131   bool LHSIsKill = hasTrivialKill(LHS);
1132 
1133   if (NeedExtend)
1134     LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1135 
1136   unsigned ResultReg = 0;
1137   if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1138     uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1139     if (C->isNegative())
1140       ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1141                                 SetFlags, WantResult);
1142     else
1143       ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1144                                 WantResult);
1145   } else if (const auto *C = dyn_cast<Constant>(RHS))
1146     if (C->isNullValue())
1147       ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, 0, SetFlags,
1148                                 WantResult);
1149 
1150   if (ResultReg)
1151     return ResultReg;
1152 
1153   // Only extend the RHS within the instruction if there is a valid extend type.
1154   if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1155       isValueAvailable(RHS)) {
1156     if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1157       if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1158         if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1159           unsigned RHSReg = getRegForValue(SI->getOperand(0));
1160           if (!RHSReg)
1161             return 0;
1162           bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1163           return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1164                                RHSIsKill, ExtendType, C->getZExtValue(),
1165                                SetFlags, WantResult);
1166         }
1167     unsigned RHSReg = getRegForValue(RHS);
1168     if (!RHSReg)
1169       return 0;
1170     bool RHSIsKill = hasTrivialKill(RHS);
1171     return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1172                          ExtendType, 0, SetFlags, WantResult);
1173   }
1174 
1175   // Check if the mul can be folded into the instruction.
1176   if (RHS->hasOneUse() && isValueAvailable(RHS)) {
1177     if (isMulPowOf2(RHS)) {
1178       const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1179       const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1180 
1181       if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1182         if (C->getValue().isPowerOf2())
1183           std::swap(MulLHS, MulRHS);
1184 
1185       assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1186       uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1187       unsigned RHSReg = getRegForValue(MulLHS);
1188       if (!RHSReg)
1189         return 0;
1190       bool RHSIsKill = hasTrivialKill(MulLHS);
1191       ResultReg = emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1192                                 RHSIsKill, AArch64_AM::LSL, ShiftVal, SetFlags,
1193                                 WantResult);
1194       if (ResultReg)
1195         return ResultReg;
1196     }
1197   }
1198 
1199   // Check if the shift can be folded into the instruction.
1200   if (RHS->hasOneUse() && isValueAvailable(RHS)) {
1201     if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1202       if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1203         AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1204         switch (SI->getOpcode()) {
1205         default: break;
1206         case Instruction::Shl:  ShiftType = AArch64_AM::LSL; break;
1207         case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1208         case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1209         }
1210         uint64_t ShiftVal = C->getZExtValue();
1211         if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1212           unsigned RHSReg = getRegForValue(SI->getOperand(0));
1213           if (!RHSReg)
1214             return 0;
1215           bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1216           ResultReg = emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1217                                     RHSIsKill, ShiftType, ShiftVal, SetFlags,
1218                                     WantResult);
1219           if (ResultReg)
1220             return ResultReg;
1221         }
1222       }
1223     }
1224   }
1225 
1226   unsigned RHSReg = getRegForValue(RHS);
1227   if (!RHSReg)
1228     return 0;
1229   bool RHSIsKill = hasTrivialKill(RHS);
1230 
1231   if (NeedExtend)
1232     RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1233 
1234   return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1235                        SetFlags, WantResult);
1236 }
1237 
1238 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1239                                         bool LHSIsKill, unsigned RHSReg,
1240                                         bool RHSIsKill, bool SetFlags,
1241                                         bool WantResult) {
1242   assert(LHSReg && RHSReg && "Invalid register number.");
1243 
1244   if (RetVT != MVT::i32 && RetVT != MVT::i64)
1245     return 0;
1246 
1247   static const unsigned OpcTable[2][2][2] = {
1248     { { AArch64::SUBWrr,  AArch64::SUBXrr  },
1249       { AArch64::ADDWrr,  AArch64::ADDXrr  }  },
1250     { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1251       { AArch64::ADDSWrr, AArch64::ADDSXrr }  }
1252   };
1253   bool Is64Bit = RetVT == MVT::i64;
1254   unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1255   const TargetRegisterClass *RC =
1256       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1257   unsigned ResultReg;
1258   if (WantResult)
1259     ResultReg = createResultReg(RC);
1260   else
1261     ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1262 
1263   const MCInstrDesc &II = TII.get(Opc);
1264   LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1265   RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1266   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1267       .addReg(LHSReg, getKillRegState(LHSIsKill))
1268       .addReg(RHSReg, getKillRegState(RHSIsKill));
1269   return ResultReg;
1270 }
1271 
1272 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1273                                         bool LHSIsKill, uint64_t Imm,
1274                                         bool SetFlags, bool WantResult) {
1275   assert(LHSReg && "Invalid register number.");
1276 
1277   if (RetVT != MVT::i32 && RetVT != MVT::i64)
1278     return 0;
1279 
1280   unsigned ShiftImm;
1281   if (isUInt<12>(Imm))
1282     ShiftImm = 0;
1283   else if ((Imm & 0xfff000) == Imm) {
1284     ShiftImm = 12;
1285     Imm >>= 12;
1286   } else
1287     return 0;
1288 
1289   static const unsigned OpcTable[2][2][2] = {
1290     { { AArch64::SUBWri,  AArch64::SUBXri  },
1291       { AArch64::ADDWri,  AArch64::ADDXri  }  },
1292     { { AArch64::SUBSWri, AArch64::SUBSXri },
1293       { AArch64::ADDSWri, AArch64::ADDSXri }  }
1294   };
1295   bool Is64Bit = RetVT == MVT::i64;
1296   unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1297   const TargetRegisterClass *RC;
1298   if (SetFlags)
1299     RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1300   else
1301     RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1302   unsigned ResultReg;
1303   if (WantResult)
1304     ResultReg = createResultReg(RC);
1305   else
1306     ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1307 
1308   const MCInstrDesc &II = TII.get(Opc);
1309   LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1310   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1311       .addReg(LHSReg, getKillRegState(LHSIsKill))
1312       .addImm(Imm)
1313       .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1314   return ResultReg;
1315 }
1316 
1317 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1318                                         bool LHSIsKill, unsigned RHSReg,
1319                                         bool RHSIsKill,
1320                                         AArch64_AM::ShiftExtendType ShiftType,
1321                                         uint64_t ShiftImm, bool SetFlags,
1322                                         bool WantResult) {
1323   assert(LHSReg && RHSReg && "Invalid register number.");
1324 
1325   if (RetVT != MVT::i32 && RetVT != MVT::i64)
1326     return 0;
1327 
1328   // Don't deal with undefined shifts.
1329   if (ShiftImm >= RetVT.getSizeInBits())
1330     return 0;
1331 
1332   static const unsigned OpcTable[2][2][2] = {
1333     { { AArch64::SUBWrs,  AArch64::SUBXrs  },
1334       { AArch64::ADDWrs,  AArch64::ADDXrs  }  },
1335     { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1336       { AArch64::ADDSWrs, AArch64::ADDSXrs }  }
1337   };
1338   bool Is64Bit = RetVT == MVT::i64;
1339   unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1340   const TargetRegisterClass *RC =
1341       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1342   unsigned ResultReg;
1343   if (WantResult)
1344     ResultReg = createResultReg(RC);
1345   else
1346     ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1347 
1348   const MCInstrDesc &II = TII.get(Opc);
1349   LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1350   RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1351   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1352       .addReg(LHSReg, getKillRegState(LHSIsKill))
1353       .addReg(RHSReg, getKillRegState(RHSIsKill))
1354       .addImm(getShifterImm(ShiftType, ShiftImm));
1355   return ResultReg;
1356 }
1357 
1358 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1359                                         bool LHSIsKill, unsigned RHSReg,
1360                                         bool RHSIsKill,
1361                                         AArch64_AM::ShiftExtendType ExtType,
1362                                         uint64_t ShiftImm, bool SetFlags,
1363                                         bool WantResult) {
1364   assert(LHSReg && RHSReg && "Invalid register number.");
1365 
1366   if (RetVT != MVT::i32 && RetVT != MVT::i64)
1367     return 0;
1368 
1369   if (ShiftImm >= 4)
1370     return 0;
1371 
1372   static const unsigned OpcTable[2][2][2] = {
1373     { { AArch64::SUBWrx,  AArch64::SUBXrx  },
1374       { AArch64::ADDWrx,  AArch64::ADDXrx  }  },
1375     { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1376       { AArch64::ADDSWrx, AArch64::ADDSXrx }  }
1377   };
1378   bool Is64Bit = RetVT == MVT::i64;
1379   unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1380   const TargetRegisterClass *RC = nullptr;
1381   if (SetFlags)
1382     RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1383   else
1384     RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1385   unsigned ResultReg;
1386   if (WantResult)
1387     ResultReg = createResultReg(RC);
1388   else
1389     ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1390 
1391   const MCInstrDesc &II = TII.get(Opc);
1392   LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1393   RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1394   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1395       .addReg(LHSReg, getKillRegState(LHSIsKill))
1396       .addReg(RHSReg, getKillRegState(RHSIsKill))
1397       .addImm(getArithExtendImm(ExtType, ShiftImm));
1398   return ResultReg;
1399 }
1400 
1401 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1402   Type *Ty = LHS->getType();
1403   EVT EVT = TLI.getValueType(DL, Ty, true);
1404   if (!EVT.isSimple())
1405     return false;
1406   MVT VT = EVT.getSimpleVT();
1407 
1408   switch (VT.SimpleTy) {
1409   default:
1410     return false;
1411   case MVT::i1:
1412   case MVT::i8:
1413   case MVT::i16:
1414   case MVT::i32:
1415   case MVT::i64:
1416     return emitICmp(VT, LHS, RHS, IsZExt);
1417   case MVT::f32:
1418   case MVT::f64:
1419     return emitFCmp(VT, LHS, RHS);
1420   }
1421 }
1422 
1423 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1424                                bool IsZExt) {
1425   return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1426                  IsZExt) != 0;
1427 }
1428 
1429 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1430                                   uint64_t Imm) {
1431   return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1432                        /*SetFlags=*/true, /*WantResult=*/false) != 0;
1433 }
1434 
1435 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1436   if (RetVT != MVT::f32 && RetVT != MVT::f64)
1437     return false;
1438 
1439   // Check to see if the 2nd operand is a constant that we can encode directly
1440   // in the compare.
1441   bool UseImm = false;
1442   if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1443     if (CFP->isZero() && !CFP->isNegative())
1444       UseImm = true;
1445 
1446   unsigned LHSReg = getRegForValue(LHS);
1447   if (!LHSReg)
1448     return false;
1449   bool LHSIsKill = hasTrivialKill(LHS);
1450 
1451   if (UseImm) {
1452     unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1453     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1454         .addReg(LHSReg, getKillRegState(LHSIsKill));
1455     return true;
1456   }
1457 
1458   unsigned RHSReg = getRegForValue(RHS);
1459   if (!RHSReg)
1460     return false;
1461   bool RHSIsKill = hasTrivialKill(RHS);
1462 
1463   unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1464   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1465       .addReg(LHSReg, getKillRegState(LHSIsKill))
1466       .addReg(RHSReg, getKillRegState(RHSIsKill));
1467   return true;
1468 }
1469 
1470 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1471                                   bool SetFlags, bool WantResult, bool IsZExt) {
1472   return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1473                     IsZExt);
1474 }
1475 
1476 /// \brief This method is a wrapper to simplify add emission.
1477 ///
1478 /// First try to emit an add with an immediate operand using emitAddSub_ri. If
1479 /// that fails, then try to materialize the immediate into a register and use
1480 /// emitAddSub_rr instead.
1481 unsigned AArch64FastISel::emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill,
1482                                       int64_t Imm) {
1483   unsigned ResultReg;
1484   if (Imm < 0)
1485     ResultReg = emitAddSub_ri(false, VT, Op0, Op0IsKill, -Imm);
1486   else
1487     ResultReg = emitAddSub_ri(true, VT, Op0, Op0IsKill, Imm);
1488 
1489   if (ResultReg)
1490     return ResultReg;
1491 
1492   unsigned CReg = fastEmit_i(VT, VT, ISD::Constant, Imm);
1493   if (!CReg)
1494     return 0;
1495 
1496   ResultReg = emitAddSub_rr(true, VT, Op0, Op0IsKill, CReg, true);
1497   return ResultReg;
1498 }
1499 
1500 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1501                                   bool SetFlags, bool WantResult, bool IsZExt) {
1502   return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1503                     IsZExt);
1504 }
1505 
1506 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1507                                       bool LHSIsKill, unsigned RHSReg,
1508                                       bool RHSIsKill, bool WantResult) {
1509   return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1510                        RHSIsKill, /*SetFlags=*/true, WantResult);
1511 }
1512 
1513 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1514                                       bool LHSIsKill, unsigned RHSReg,
1515                                       bool RHSIsKill,
1516                                       AArch64_AM::ShiftExtendType ShiftType,
1517                                       uint64_t ShiftImm, bool WantResult) {
1518   return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1519                        RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1520                        WantResult);
1521 }
1522 
1523 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1524                                         const Value *LHS, const Value *RHS) {
1525   // Canonicalize immediates to the RHS first.
1526   if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1527     std::swap(LHS, RHS);
1528 
1529   // Canonicalize mul by power-of-2 to the RHS.
1530   if (LHS->hasOneUse() && isValueAvailable(LHS))
1531     if (isMulPowOf2(LHS))
1532       std::swap(LHS, RHS);
1533 
1534   // Canonicalize shift immediate to the RHS.
1535   if (LHS->hasOneUse() && isValueAvailable(LHS))
1536     if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1537       if (isa<ConstantInt>(SI->getOperand(1)))
1538         std::swap(LHS, RHS);
1539 
1540   unsigned LHSReg = getRegForValue(LHS);
1541   if (!LHSReg)
1542     return 0;
1543   bool LHSIsKill = hasTrivialKill(LHS);
1544 
1545   unsigned ResultReg = 0;
1546   if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1547     uint64_t Imm = C->getZExtValue();
1548     ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1549   }
1550   if (ResultReg)
1551     return ResultReg;
1552 
1553   // Check if the mul can be folded into the instruction.
1554   if (RHS->hasOneUse() && isValueAvailable(RHS)) {
1555     if (isMulPowOf2(RHS)) {
1556       const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1557       const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1558 
1559       if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1560         if (C->getValue().isPowerOf2())
1561           std::swap(MulLHS, MulRHS);
1562 
1563       assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1564       uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1565 
1566       unsigned RHSReg = getRegForValue(MulLHS);
1567       if (!RHSReg)
1568         return 0;
1569       bool RHSIsKill = hasTrivialKill(MulLHS);
1570       ResultReg = emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1571                                    RHSIsKill, ShiftVal);
1572       if (ResultReg)
1573         return ResultReg;
1574     }
1575   }
1576 
1577   // Check if the shift can be folded into the instruction.
1578   if (RHS->hasOneUse() && isValueAvailable(RHS)) {
1579     if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1580       if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1581         uint64_t ShiftVal = C->getZExtValue();
1582         unsigned RHSReg = getRegForValue(SI->getOperand(0));
1583         if (!RHSReg)
1584           return 0;
1585         bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1586         ResultReg = emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1587                                      RHSIsKill, ShiftVal);
1588         if (ResultReg)
1589           return ResultReg;
1590       }
1591   }
1592 
1593   unsigned RHSReg = getRegForValue(RHS);
1594   if (!RHSReg)
1595     return 0;
1596   bool RHSIsKill = hasTrivialKill(RHS);
1597 
1598   MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1599   ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1600   if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1601     uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1602     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1603   }
1604   return ResultReg;
1605 }
1606 
1607 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1608                                            unsigned LHSReg, bool LHSIsKill,
1609                                            uint64_t Imm) {
1610   static_assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR),
1611                 "ISD nodes are not consecutive!");
1612   static const unsigned OpcTable[3][2] = {
1613     { AArch64::ANDWri, AArch64::ANDXri },
1614     { AArch64::ORRWri, AArch64::ORRXri },
1615     { AArch64::EORWri, AArch64::EORXri }
1616   };
1617   const TargetRegisterClass *RC;
1618   unsigned Opc;
1619   unsigned RegSize;
1620   switch (RetVT.SimpleTy) {
1621   default:
1622     return 0;
1623   case MVT::i1:
1624   case MVT::i8:
1625   case MVT::i16:
1626   case MVT::i32: {
1627     unsigned Idx = ISDOpc - ISD::AND;
1628     Opc = OpcTable[Idx][0];
1629     RC = &AArch64::GPR32spRegClass;
1630     RegSize = 32;
1631     break;
1632   }
1633   case MVT::i64:
1634     Opc = OpcTable[ISDOpc - ISD::AND][1];
1635     RC = &AArch64::GPR64spRegClass;
1636     RegSize = 64;
1637     break;
1638   }
1639 
1640   if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1641     return 0;
1642 
1643   unsigned ResultReg =
1644       fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1645                       AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1646   if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1647     uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1648     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1649   }
1650   return ResultReg;
1651 }
1652 
1653 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1654                                            unsigned LHSReg, bool LHSIsKill,
1655                                            unsigned RHSReg, bool RHSIsKill,
1656                                            uint64_t ShiftImm) {
1657   static_assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR),
1658                 "ISD nodes are not consecutive!");
1659   static const unsigned OpcTable[3][2] = {
1660     { AArch64::ANDWrs, AArch64::ANDXrs },
1661     { AArch64::ORRWrs, AArch64::ORRXrs },
1662     { AArch64::EORWrs, AArch64::EORXrs }
1663   };
1664 
1665   // Don't deal with undefined shifts.
1666   if (ShiftImm >= RetVT.getSizeInBits())
1667     return 0;
1668 
1669   const TargetRegisterClass *RC;
1670   unsigned Opc;
1671   switch (RetVT.SimpleTy) {
1672   default:
1673     return 0;
1674   case MVT::i1:
1675   case MVT::i8:
1676   case MVT::i16:
1677   case MVT::i32:
1678     Opc = OpcTable[ISDOpc - ISD::AND][0];
1679     RC = &AArch64::GPR32RegClass;
1680     break;
1681   case MVT::i64:
1682     Opc = OpcTable[ISDOpc - ISD::AND][1];
1683     RC = &AArch64::GPR64RegClass;
1684     break;
1685   }
1686   unsigned ResultReg =
1687       fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1688                        AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1689   if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1690     uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1691     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1692   }
1693   return ResultReg;
1694 }
1695 
1696 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1697                                      uint64_t Imm) {
1698   return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1699 }
1700 
1701 unsigned AArch64FastISel::emitLoad(MVT VT, MVT RetVT, Address Addr,
1702                                    bool WantZExt, MachineMemOperand *MMO) {
1703   if (!TLI.allowsMisalignedMemoryAccesses(VT))
1704     return 0;
1705 
1706   // Simplify this down to something we can handle.
1707   if (!simplifyAddress(Addr, VT))
1708     return 0;
1709 
1710   unsigned ScaleFactor = getImplicitScaleFactor(VT);
1711   if (!ScaleFactor)
1712     llvm_unreachable("Unexpected value type.");
1713 
1714   // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1715   // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1716   bool UseScaled = true;
1717   if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1718     UseScaled = false;
1719     ScaleFactor = 1;
1720   }
1721 
1722   static const unsigned GPOpcTable[2][8][4] = {
1723     // Sign-extend.
1724     { { AArch64::LDURSBWi,  AArch64::LDURSHWi,  AArch64::LDURWi,
1725         AArch64::LDURXi  },
1726       { AArch64::LDURSBXi,  AArch64::LDURSHXi,  AArch64::LDURSWi,
1727         AArch64::LDURXi  },
1728       { AArch64::LDRSBWui,  AArch64::LDRSHWui,  AArch64::LDRWui,
1729         AArch64::LDRXui  },
1730       { AArch64::LDRSBXui,  AArch64::LDRSHXui,  AArch64::LDRSWui,
1731         AArch64::LDRXui  },
1732       { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRWroX,
1733         AArch64::LDRXroX },
1734       { AArch64::LDRSBXroX, AArch64::LDRSHXroX, AArch64::LDRSWroX,
1735         AArch64::LDRXroX },
1736       { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRWroW,
1737         AArch64::LDRXroW },
1738       { AArch64::LDRSBXroW, AArch64::LDRSHXroW, AArch64::LDRSWroW,
1739         AArch64::LDRXroW }
1740     },
1741     // Zero-extend.
1742     { { AArch64::LDURBBi,   AArch64::LDURHHi,   AArch64::LDURWi,
1743         AArch64::LDURXi  },
1744       { AArch64::LDURBBi,   AArch64::LDURHHi,   AArch64::LDURWi,
1745         AArch64::LDURXi  },
1746       { AArch64::LDRBBui,   AArch64::LDRHHui,   AArch64::LDRWui,
1747         AArch64::LDRXui  },
1748       { AArch64::LDRBBui,   AArch64::LDRHHui,   AArch64::LDRWui,
1749         AArch64::LDRXui  },
1750       { AArch64::LDRBBroX,  AArch64::LDRHHroX,  AArch64::LDRWroX,
1751         AArch64::LDRXroX },
1752       { AArch64::LDRBBroX,  AArch64::LDRHHroX,  AArch64::LDRWroX,
1753         AArch64::LDRXroX },
1754       { AArch64::LDRBBroW,  AArch64::LDRHHroW,  AArch64::LDRWroW,
1755         AArch64::LDRXroW },
1756       { AArch64::LDRBBroW,  AArch64::LDRHHroW,  AArch64::LDRWroW,
1757         AArch64::LDRXroW }
1758     }
1759   };
1760 
1761   static const unsigned FPOpcTable[4][2] = {
1762     { AArch64::LDURSi,  AArch64::LDURDi  },
1763     { AArch64::LDRSui,  AArch64::LDRDui  },
1764     { AArch64::LDRSroX, AArch64::LDRDroX },
1765     { AArch64::LDRSroW, AArch64::LDRDroW }
1766   };
1767 
1768   unsigned Opc;
1769   const TargetRegisterClass *RC;
1770   bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1771                       Addr.getOffsetReg();
1772   unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1773   if (Addr.getExtendType() == AArch64_AM::UXTW ||
1774       Addr.getExtendType() == AArch64_AM::SXTW)
1775     Idx++;
1776 
1777   bool IsRet64Bit = RetVT == MVT::i64;
1778   switch (VT.SimpleTy) {
1779   default:
1780     llvm_unreachable("Unexpected value type.");
1781   case MVT::i1: // Intentional fall-through.
1782   case MVT::i8:
1783     Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][0];
1784     RC = (IsRet64Bit && !WantZExt) ?
1785              &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1786     break;
1787   case MVT::i16:
1788     Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][1];
1789     RC = (IsRet64Bit && !WantZExt) ?
1790              &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1791     break;
1792   case MVT::i32:
1793     Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][2];
1794     RC = (IsRet64Bit && !WantZExt) ?
1795              &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1796     break;
1797   case MVT::i64:
1798     Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][3];
1799     RC = &AArch64::GPR64RegClass;
1800     break;
1801   case MVT::f32:
1802     Opc = FPOpcTable[Idx][0];
1803     RC = &AArch64::FPR32RegClass;
1804     break;
1805   case MVT::f64:
1806     Opc = FPOpcTable[Idx][1];
1807     RC = &AArch64::FPR64RegClass;
1808     break;
1809   }
1810 
1811   // Create the base instruction, then add the operands.
1812   unsigned ResultReg = createResultReg(RC);
1813   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1814                                     TII.get(Opc), ResultReg);
1815   addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1816 
1817   // Loading an i1 requires special handling.
1818   if (VT == MVT::i1) {
1819     unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1820     assert(ANDReg && "Unexpected AND instruction emission failure.");
1821     ResultReg = ANDReg;
1822   }
1823 
1824   // For zero-extending loads to 64bit we emit a 32bit load and then convert
1825   // the 32bit reg to a 64bit reg.
1826   if (WantZExt && RetVT == MVT::i64 && VT <= MVT::i32) {
1827     unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
1828     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1829             TII.get(AArch64::SUBREG_TO_REG), Reg64)
1830         .addImm(0)
1831         .addReg(ResultReg, getKillRegState(true))
1832         .addImm(AArch64::sub_32);
1833     ResultReg = Reg64;
1834   }
1835   return ResultReg;
1836 }
1837 
1838 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1839   MVT VT;
1840   if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1841     return false;
1842 
1843   if (VT.isVector())
1844     return selectOperator(I, I->getOpcode());
1845 
1846   unsigned ResultReg;
1847   switch (I->getOpcode()) {
1848   default:
1849     llvm_unreachable("Unexpected instruction.");
1850   case Instruction::Add:
1851     ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1852     break;
1853   case Instruction::Sub:
1854     ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1855     break;
1856   }
1857   if (!ResultReg)
1858     return false;
1859 
1860   updateValueMap(I, ResultReg);
1861   return true;
1862 }
1863 
1864 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1865   MVT VT;
1866   if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1867     return false;
1868 
1869   if (VT.isVector())
1870     return selectOperator(I, I->getOpcode());
1871 
1872   unsigned ResultReg;
1873   switch (I->getOpcode()) {
1874   default:
1875     llvm_unreachable("Unexpected instruction.");
1876   case Instruction::And:
1877     ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1878     break;
1879   case Instruction::Or:
1880     ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1881     break;
1882   case Instruction::Xor:
1883     ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1884     break;
1885   }
1886   if (!ResultReg)
1887     return false;
1888 
1889   updateValueMap(I, ResultReg);
1890   return true;
1891 }
1892 
1893 bool AArch64FastISel::selectLoad(const Instruction *I) {
1894   MVT VT;
1895   // Verify we have a legal type before going any further.  Currently, we handle
1896   // simple types that will directly fit in a register (i32/f32/i64/f64) or
1897   // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1898   if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1899       cast<LoadInst>(I)->isAtomic())
1900     return false;
1901 
1902   const Value *SV = I->getOperand(0);
1903   if (TLI.supportSwiftError()) {
1904     // Swifterror values can come from either a function parameter with
1905     // swifterror attribute or an alloca with swifterror attribute.
1906     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1907       if (Arg->hasSwiftErrorAttr())
1908         return false;
1909     }
1910 
1911     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1912       if (Alloca->isSwiftError())
1913         return false;
1914     }
1915   }
1916 
1917   // See if we can handle this address.
1918   Address Addr;
1919   if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1920     return false;
1921 
1922   // Fold the following sign-/zero-extend into the load instruction.
1923   bool WantZExt = true;
1924   MVT RetVT = VT;
1925   const Value *IntExtVal = nullptr;
1926   if (I->hasOneUse()) {
1927     if (const auto *ZE = dyn_cast<ZExtInst>(I->use_begin()->getUser())) {
1928       if (isTypeSupported(ZE->getType(), RetVT))
1929         IntExtVal = ZE;
1930       else
1931         RetVT = VT;
1932     } else if (const auto *SE = dyn_cast<SExtInst>(I->use_begin()->getUser())) {
1933       if (isTypeSupported(SE->getType(), RetVT))
1934         IntExtVal = SE;
1935       else
1936         RetVT = VT;
1937       WantZExt = false;
1938     }
1939   }
1940 
1941   unsigned ResultReg =
1942       emitLoad(VT, RetVT, Addr, WantZExt, createMachineMemOperandFor(I));
1943   if (!ResultReg)
1944     return false;
1945 
1946   // There are a few different cases we have to handle, because the load or the
1947   // sign-/zero-extend might not be selected by FastISel if we fall-back to
1948   // SelectionDAG. There is also an ordering issue when both instructions are in
1949   // different basic blocks.
1950   // 1.) The load instruction is selected by FastISel, but the integer extend
1951   //     not. This usually happens when the integer extend is in a different
1952   //     basic block and SelectionDAG took over for that basic block.
1953   // 2.) The load instruction is selected before the integer extend. This only
1954   //     happens when the integer extend is in a different basic block.
1955   // 3.) The load instruction is selected by SelectionDAG and the integer extend
1956   //     by FastISel. This happens if there are instructions between the load
1957   //     and the integer extend that couldn't be selected by FastISel.
1958   if (IntExtVal) {
1959     // The integer extend hasn't been emitted yet. FastISel or SelectionDAG
1960     // could select it. Emit a copy to subreg if necessary. FastISel will remove
1961     // it when it selects the integer extend.
1962     unsigned Reg = lookUpRegForValue(IntExtVal);
1963     auto *MI = MRI.getUniqueVRegDef(Reg);
1964     if (!MI) {
1965       if (RetVT == MVT::i64 && VT <= MVT::i32) {
1966         if (WantZExt) {
1967           // Delete the last emitted instruction from emitLoad (SUBREG_TO_REG).
1968           std::prev(FuncInfo.InsertPt)->eraseFromParent();
1969           ResultReg = std::prev(FuncInfo.InsertPt)->getOperand(0).getReg();
1970         } else
1971           ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg,
1972                                                  /*IsKill=*/true,
1973                                                  AArch64::sub_32);
1974       }
1975       updateValueMap(I, ResultReg);
1976       return true;
1977     }
1978 
1979     // The integer extend has already been emitted - delete all the instructions
1980     // that have been emitted by the integer extend lowering code and use the
1981     // result from the load instruction directly.
1982     while (MI) {
1983       Reg = 0;
1984       for (auto &Opnd : MI->uses()) {
1985         if (Opnd.isReg()) {
1986           Reg = Opnd.getReg();
1987           break;
1988         }
1989       }
1990       MI->eraseFromParent();
1991       MI = nullptr;
1992       if (Reg)
1993         MI = MRI.getUniqueVRegDef(Reg);
1994     }
1995     updateValueMap(IntExtVal, ResultReg);
1996     return true;
1997   }
1998 
1999   updateValueMap(I, ResultReg);
2000   return true;
2001 }
2002 
2003 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
2004                                 MachineMemOperand *MMO) {
2005   if (!TLI.allowsMisalignedMemoryAccesses(VT))
2006     return false;
2007 
2008   // Simplify this down to something we can handle.
2009   if (!simplifyAddress(Addr, VT))
2010     return false;
2011 
2012   unsigned ScaleFactor = getImplicitScaleFactor(VT);
2013   if (!ScaleFactor)
2014     llvm_unreachable("Unexpected value type.");
2015 
2016   // Negative offsets require unscaled, 9-bit, signed immediate offsets.
2017   // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
2018   bool UseScaled = true;
2019   if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
2020     UseScaled = false;
2021     ScaleFactor = 1;
2022   }
2023 
2024   static const unsigned OpcTable[4][6] = {
2025     { AArch64::STURBBi,  AArch64::STURHHi,  AArch64::STURWi,  AArch64::STURXi,
2026       AArch64::STURSi,   AArch64::STURDi },
2027     { AArch64::STRBBui,  AArch64::STRHHui,  AArch64::STRWui,  AArch64::STRXui,
2028       AArch64::STRSui,   AArch64::STRDui },
2029     { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
2030       AArch64::STRSroX,  AArch64::STRDroX },
2031     { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
2032       AArch64::STRSroW,  AArch64::STRDroW }
2033   };
2034 
2035   unsigned Opc;
2036   bool VTIsi1 = false;
2037   bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
2038                       Addr.getOffsetReg();
2039   unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
2040   if (Addr.getExtendType() == AArch64_AM::UXTW ||
2041       Addr.getExtendType() == AArch64_AM::SXTW)
2042     Idx++;
2043 
2044   switch (VT.SimpleTy) {
2045   default: llvm_unreachable("Unexpected value type.");
2046   case MVT::i1:  VTIsi1 = true;
2047   case MVT::i8:  Opc = OpcTable[Idx][0]; break;
2048   case MVT::i16: Opc = OpcTable[Idx][1]; break;
2049   case MVT::i32: Opc = OpcTable[Idx][2]; break;
2050   case MVT::i64: Opc = OpcTable[Idx][3]; break;
2051   case MVT::f32: Opc = OpcTable[Idx][4]; break;
2052   case MVT::f64: Opc = OpcTable[Idx][5]; break;
2053   }
2054 
2055   // Storing an i1 requires special handling.
2056   if (VTIsi1 && SrcReg != AArch64::WZR) {
2057     unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
2058     assert(ANDReg && "Unexpected AND instruction emission failure.");
2059     SrcReg = ANDReg;
2060   }
2061   // Create the base instruction, then add the operands.
2062   const MCInstrDesc &II = TII.get(Opc);
2063   SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2064   MachineInstrBuilder MIB =
2065       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
2066   addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
2067 
2068   return true;
2069 }
2070 
2071 bool AArch64FastISel::selectStore(const Instruction *I) {
2072   MVT VT;
2073   const Value *Op0 = I->getOperand(0);
2074   // Verify we have a legal type before going any further.  Currently, we handle
2075   // simple types that will directly fit in a register (i32/f32/i64/f64) or
2076   // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
2077   if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
2078       cast<StoreInst>(I)->isAtomic())
2079     return false;
2080 
2081   const Value *PtrV = I->getOperand(1);
2082   if (TLI.supportSwiftError()) {
2083     // Swifterror values can come from either a function parameter with
2084     // swifterror attribute or an alloca with swifterror attribute.
2085     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
2086       if (Arg->hasSwiftErrorAttr())
2087         return false;
2088     }
2089 
2090     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
2091       if (Alloca->isSwiftError())
2092         return false;
2093     }
2094   }
2095 
2096   // Get the value to be stored into a register. Use the zero register directly
2097   // when possible to avoid an unnecessary copy and a wasted register.
2098   unsigned SrcReg = 0;
2099   if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
2100     if (CI->isZero())
2101       SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2102   } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
2103     if (CF->isZero() && !CF->isNegative()) {
2104       VT = MVT::getIntegerVT(VT.getSizeInBits());
2105       SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2106     }
2107   }
2108 
2109   if (!SrcReg)
2110     SrcReg = getRegForValue(Op0);
2111 
2112   if (!SrcReg)
2113     return false;
2114 
2115   // See if we can handle this address.
2116   Address Addr;
2117   if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
2118     return false;
2119 
2120   if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
2121     return false;
2122   return true;
2123 }
2124 
2125 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
2126   switch (Pred) {
2127   case CmpInst::FCMP_ONE:
2128   case CmpInst::FCMP_UEQ:
2129   default:
2130     // AL is our "false" for now. The other two need more compares.
2131     return AArch64CC::AL;
2132   case CmpInst::ICMP_EQ:
2133   case CmpInst::FCMP_OEQ:
2134     return AArch64CC::EQ;
2135   case CmpInst::ICMP_SGT:
2136   case CmpInst::FCMP_OGT:
2137     return AArch64CC::GT;
2138   case CmpInst::ICMP_SGE:
2139   case CmpInst::FCMP_OGE:
2140     return AArch64CC::GE;
2141   case CmpInst::ICMP_UGT:
2142   case CmpInst::FCMP_UGT:
2143     return AArch64CC::HI;
2144   case CmpInst::FCMP_OLT:
2145     return AArch64CC::MI;
2146   case CmpInst::ICMP_ULE:
2147   case CmpInst::FCMP_OLE:
2148     return AArch64CC::LS;
2149   case CmpInst::FCMP_ORD:
2150     return AArch64CC::VC;
2151   case CmpInst::FCMP_UNO:
2152     return AArch64CC::VS;
2153   case CmpInst::FCMP_UGE:
2154     return AArch64CC::PL;
2155   case CmpInst::ICMP_SLT:
2156   case CmpInst::FCMP_ULT:
2157     return AArch64CC::LT;
2158   case CmpInst::ICMP_SLE:
2159   case CmpInst::FCMP_ULE:
2160     return AArch64CC::LE;
2161   case CmpInst::FCMP_UNE:
2162   case CmpInst::ICMP_NE:
2163     return AArch64CC::NE;
2164   case CmpInst::ICMP_UGE:
2165     return AArch64CC::HS;
2166   case CmpInst::ICMP_ULT:
2167     return AArch64CC::LO;
2168   }
2169 }
2170 
2171 /// \brief Try to emit a combined compare-and-branch instruction.
2172 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
2173   assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
2174   const CmpInst *CI = cast<CmpInst>(BI->getCondition());
2175   CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2176 
2177   const Value *LHS = CI->getOperand(0);
2178   const Value *RHS = CI->getOperand(1);
2179 
2180   MVT VT;
2181   if (!isTypeSupported(LHS->getType(), VT))
2182     return false;
2183 
2184   unsigned BW = VT.getSizeInBits();
2185   if (BW > 64)
2186     return false;
2187 
2188   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2189   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2190 
2191   // Try to take advantage of fallthrough opportunities.
2192   if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2193     std::swap(TBB, FBB);
2194     Predicate = CmpInst::getInversePredicate(Predicate);
2195   }
2196 
2197   int TestBit = -1;
2198   bool IsCmpNE;
2199   switch (Predicate) {
2200   default:
2201     return false;
2202   case CmpInst::ICMP_EQ:
2203   case CmpInst::ICMP_NE:
2204     if (isa<Constant>(LHS) && cast<Constant>(LHS)->isNullValue())
2205       std::swap(LHS, RHS);
2206 
2207     if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2208       return false;
2209 
2210     if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
2211       if (AI->getOpcode() == Instruction::And && isValueAvailable(AI)) {
2212         const Value *AndLHS = AI->getOperand(0);
2213         const Value *AndRHS = AI->getOperand(1);
2214 
2215         if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
2216           if (C->getValue().isPowerOf2())
2217             std::swap(AndLHS, AndRHS);
2218 
2219         if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
2220           if (C->getValue().isPowerOf2()) {
2221             TestBit = C->getValue().logBase2();
2222             LHS = AndLHS;
2223           }
2224       }
2225 
2226     if (VT == MVT::i1)
2227       TestBit = 0;
2228 
2229     IsCmpNE = Predicate == CmpInst::ICMP_NE;
2230     break;
2231   case CmpInst::ICMP_SLT:
2232   case CmpInst::ICMP_SGE:
2233     if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2234       return false;
2235 
2236     TestBit = BW - 1;
2237     IsCmpNE = Predicate == CmpInst::ICMP_SLT;
2238     break;
2239   case CmpInst::ICMP_SGT:
2240   case CmpInst::ICMP_SLE:
2241     if (!isa<ConstantInt>(RHS))
2242       return false;
2243 
2244     if (cast<ConstantInt>(RHS)->getValue() != APInt(BW, -1, true))
2245       return false;
2246 
2247     TestBit = BW - 1;
2248     IsCmpNE = Predicate == CmpInst::ICMP_SLE;
2249     break;
2250   } // end switch
2251 
2252   static const unsigned OpcTable[2][2][2] = {
2253     { {AArch64::CBZW,  AArch64::CBZX },
2254       {AArch64::CBNZW, AArch64::CBNZX} },
2255     { {AArch64::TBZW,  AArch64::TBZX },
2256       {AArch64::TBNZW, AArch64::TBNZX} }
2257   };
2258 
2259   bool IsBitTest = TestBit != -1;
2260   bool Is64Bit = BW == 64;
2261   if (TestBit < 32 && TestBit >= 0)
2262     Is64Bit = false;
2263 
2264   unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2265   const MCInstrDesc &II = TII.get(Opc);
2266 
2267   unsigned SrcReg = getRegForValue(LHS);
2268   if (!SrcReg)
2269     return false;
2270   bool SrcIsKill = hasTrivialKill(LHS);
2271 
2272   if (BW == 64 && !Is64Bit)
2273     SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2274                                         AArch64::sub_32);
2275 
2276   if ((BW < 32) && !IsBitTest)
2277     SrcReg = emitIntExt(VT, SrcReg, MVT::i32, /*IsZExt=*/true);
2278 
2279   // Emit the combined compare and branch instruction.
2280   SrcReg = constrainOperandRegClass(II, SrcReg,  II.getNumDefs());
2281   MachineInstrBuilder MIB =
2282       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2283           .addReg(SrcReg, getKillRegState(SrcIsKill));
2284   if (IsBitTest)
2285     MIB.addImm(TestBit);
2286   MIB.addMBB(TBB);
2287 
2288   finishCondBranch(BI->getParent(), TBB, FBB);
2289   return true;
2290 }
2291 
2292 bool AArch64FastISel::selectBranch(const Instruction *I) {
2293   const BranchInst *BI = cast<BranchInst>(I);
2294   if (BI->isUnconditional()) {
2295     MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2296     fastEmitBranch(MSucc, BI->getDebugLoc());
2297     return true;
2298   }
2299 
2300   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2301   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2302 
2303   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2304     if (CI->hasOneUse() && isValueAvailable(CI)) {
2305       // Try to optimize or fold the cmp.
2306       CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2307       switch (Predicate) {
2308       default:
2309         break;
2310       case CmpInst::FCMP_FALSE:
2311         fastEmitBranch(FBB, DbgLoc);
2312         return true;
2313       case CmpInst::FCMP_TRUE:
2314         fastEmitBranch(TBB, DbgLoc);
2315         return true;
2316       }
2317 
2318       // Try to emit a combined compare-and-branch first.
2319       if (emitCompareAndBranch(BI))
2320         return true;
2321 
2322       // Try to take advantage of fallthrough opportunities.
2323       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2324         std::swap(TBB, FBB);
2325         Predicate = CmpInst::getInversePredicate(Predicate);
2326       }
2327 
2328       // Emit the cmp.
2329       if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2330         return false;
2331 
2332       // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2333       // instruction.
2334       AArch64CC::CondCode CC = getCompareCC(Predicate);
2335       AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2336       switch (Predicate) {
2337       default:
2338         break;
2339       case CmpInst::FCMP_UEQ:
2340         ExtraCC = AArch64CC::EQ;
2341         CC = AArch64CC::VS;
2342         break;
2343       case CmpInst::FCMP_ONE:
2344         ExtraCC = AArch64CC::MI;
2345         CC = AArch64CC::GT;
2346         break;
2347       }
2348       assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2349 
2350       // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2351       if (ExtraCC != AArch64CC::AL) {
2352         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2353             .addImm(ExtraCC)
2354             .addMBB(TBB);
2355       }
2356 
2357       // Emit the branch.
2358       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2359           .addImm(CC)
2360           .addMBB(TBB);
2361 
2362       finishCondBranch(BI->getParent(), TBB, FBB);
2363       return true;
2364     }
2365   } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2366     uint64_t Imm = CI->getZExtValue();
2367     MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2368     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2369         .addMBB(Target);
2370 
2371     // Obtain the branch probability and add the target to the successor list.
2372     if (FuncInfo.BPI) {
2373       auto BranchProbability = FuncInfo.BPI->getEdgeProbability(
2374           BI->getParent(), Target->getBasicBlock());
2375       FuncInfo.MBB->addSuccessor(Target, BranchProbability);
2376     } else
2377       FuncInfo.MBB->addSuccessorWithoutProb(Target);
2378     return true;
2379   } else {
2380     AArch64CC::CondCode CC = AArch64CC::NE;
2381     if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2382       // Fake request the condition, otherwise the intrinsic might be completely
2383       // optimized away.
2384       unsigned CondReg = getRegForValue(BI->getCondition());
2385       if (!CondReg)
2386         return false;
2387 
2388       // Emit the branch.
2389       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2390         .addImm(CC)
2391         .addMBB(TBB);
2392 
2393       finishCondBranch(BI->getParent(), TBB, FBB);
2394       return true;
2395     }
2396   }
2397 
2398   unsigned CondReg = getRegForValue(BI->getCondition());
2399   if (CondReg == 0)
2400     return false;
2401   bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2402 
2403   // i1 conditions come as i32 values, test the lowest bit with tb(n)z.
2404   unsigned Opcode = AArch64::TBNZW;
2405   if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2406     std::swap(TBB, FBB);
2407     Opcode = AArch64::TBZW;
2408   }
2409 
2410   const MCInstrDesc &II = TII.get(Opcode);
2411   unsigned ConstrainedCondReg
2412     = constrainOperandRegClass(II, CondReg, II.getNumDefs());
2413   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2414       .addReg(ConstrainedCondReg, getKillRegState(CondRegIsKill))
2415       .addImm(0)
2416       .addMBB(TBB);
2417 
2418   finishCondBranch(BI->getParent(), TBB, FBB);
2419   return true;
2420 }
2421 
2422 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2423   const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2424   unsigned AddrReg = getRegForValue(BI->getOperand(0));
2425   if (AddrReg == 0)
2426     return false;
2427 
2428   // Emit the indirect branch.
2429   const MCInstrDesc &II = TII.get(AArch64::BR);
2430   AddrReg = constrainOperandRegClass(II, AddrReg,  II.getNumDefs());
2431   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2432 
2433   // Make sure the CFG is up-to-date.
2434   for (auto *Succ : BI->successors())
2435     FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[Succ]);
2436 
2437   return true;
2438 }
2439 
2440 bool AArch64FastISel::selectCmp(const Instruction *I) {
2441   const CmpInst *CI = cast<CmpInst>(I);
2442 
2443   // Vectors of i1 are weird: bail out.
2444   if (CI->getType()->isVectorTy())
2445     return false;
2446 
2447   // Try to optimize or fold the cmp.
2448   CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2449   unsigned ResultReg = 0;
2450   switch (Predicate) {
2451   default:
2452     break;
2453   case CmpInst::FCMP_FALSE:
2454     ResultReg = createResultReg(&AArch64::GPR32RegClass);
2455     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2456             TII.get(TargetOpcode::COPY), ResultReg)
2457         .addReg(AArch64::WZR, getKillRegState(true));
2458     break;
2459   case CmpInst::FCMP_TRUE:
2460     ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2461     break;
2462   }
2463 
2464   if (ResultReg) {
2465     updateValueMap(I, ResultReg);
2466     return true;
2467   }
2468 
2469   // Emit the cmp.
2470   if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2471     return false;
2472 
2473   ResultReg = createResultReg(&AArch64::GPR32RegClass);
2474 
2475   // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2476   // condition codes are inverted, because they are used by CSINC.
2477   static unsigned CondCodeTable[2][2] = {
2478     { AArch64CC::NE, AArch64CC::VC },
2479     { AArch64CC::PL, AArch64CC::LE }
2480   };
2481   unsigned *CondCodes = nullptr;
2482   switch (Predicate) {
2483   default:
2484     break;
2485   case CmpInst::FCMP_UEQ:
2486     CondCodes = &CondCodeTable[0][0];
2487     break;
2488   case CmpInst::FCMP_ONE:
2489     CondCodes = &CondCodeTable[1][0];
2490     break;
2491   }
2492 
2493   if (CondCodes) {
2494     unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2495     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2496             TmpReg1)
2497         .addReg(AArch64::WZR, getKillRegState(true))
2498         .addReg(AArch64::WZR, getKillRegState(true))
2499         .addImm(CondCodes[0]);
2500     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2501             ResultReg)
2502         .addReg(TmpReg1, getKillRegState(true))
2503         .addReg(AArch64::WZR, getKillRegState(true))
2504         .addImm(CondCodes[1]);
2505 
2506     updateValueMap(I, ResultReg);
2507     return true;
2508   }
2509 
2510   // Now set a register based on the comparison.
2511   AArch64CC::CondCode CC = getCompareCC(Predicate);
2512   assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2513   AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2514   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2515           ResultReg)
2516       .addReg(AArch64::WZR, getKillRegState(true))
2517       .addReg(AArch64::WZR, getKillRegState(true))
2518       .addImm(invertedCC);
2519 
2520   updateValueMap(I, ResultReg);
2521   return true;
2522 }
2523 
2524 /// \brief Optimize selects of i1 if one of the operands has a 'true' or 'false'
2525 /// value.
2526 bool AArch64FastISel::optimizeSelect(const SelectInst *SI) {
2527   if (!SI->getType()->isIntegerTy(1))
2528     return false;
2529 
2530   const Value *Src1Val, *Src2Val;
2531   unsigned Opc = 0;
2532   bool NeedExtraOp = false;
2533   if (auto *CI = dyn_cast<ConstantInt>(SI->getTrueValue())) {
2534     if (CI->isOne()) {
2535       Src1Val = SI->getCondition();
2536       Src2Val = SI->getFalseValue();
2537       Opc = AArch64::ORRWrr;
2538     } else {
2539       assert(CI->isZero());
2540       Src1Val = SI->getFalseValue();
2541       Src2Val = SI->getCondition();
2542       Opc = AArch64::BICWrr;
2543     }
2544   } else if (auto *CI = dyn_cast<ConstantInt>(SI->getFalseValue())) {
2545     if (CI->isOne()) {
2546       Src1Val = SI->getCondition();
2547       Src2Val = SI->getTrueValue();
2548       Opc = AArch64::ORRWrr;
2549       NeedExtraOp = true;
2550     } else {
2551       assert(CI->isZero());
2552       Src1Val = SI->getCondition();
2553       Src2Val = SI->getTrueValue();
2554       Opc = AArch64::ANDWrr;
2555     }
2556   }
2557 
2558   if (!Opc)
2559     return false;
2560 
2561   unsigned Src1Reg = getRegForValue(Src1Val);
2562   if (!Src1Reg)
2563     return false;
2564   bool Src1IsKill = hasTrivialKill(Src1Val);
2565 
2566   unsigned Src2Reg = getRegForValue(Src2Val);
2567   if (!Src2Reg)
2568     return false;
2569   bool Src2IsKill = hasTrivialKill(Src2Val);
2570 
2571   if (NeedExtraOp) {
2572     Src1Reg = emitLogicalOp_ri(ISD::XOR, MVT::i32, Src1Reg, Src1IsKill, 1);
2573     Src1IsKill = true;
2574   }
2575   unsigned ResultReg = fastEmitInst_rr(Opc, &AArch64::GPR32RegClass, Src1Reg,
2576                                        Src1IsKill, Src2Reg, Src2IsKill);
2577   updateValueMap(SI, ResultReg);
2578   return true;
2579 }
2580 
2581 bool AArch64FastISel::selectSelect(const Instruction *I) {
2582   assert(isa<SelectInst>(I) && "Expected a select instruction.");
2583   MVT VT;
2584   if (!isTypeSupported(I->getType(), VT))
2585     return false;
2586 
2587   unsigned Opc;
2588   const TargetRegisterClass *RC;
2589   switch (VT.SimpleTy) {
2590   default:
2591     return false;
2592   case MVT::i1:
2593   case MVT::i8:
2594   case MVT::i16:
2595   case MVT::i32:
2596     Opc = AArch64::CSELWr;
2597     RC = &AArch64::GPR32RegClass;
2598     break;
2599   case MVT::i64:
2600     Opc = AArch64::CSELXr;
2601     RC = &AArch64::GPR64RegClass;
2602     break;
2603   case MVT::f32:
2604     Opc = AArch64::FCSELSrrr;
2605     RC = &AArch64::FPR32RegClass;
2606     break;
2607   case MVT::f64:
2608     Opc = AArch64::FCSELDrrr;
2609     RC = &AArch64::FPR64RegClass;
2610     break;
2611   }
2612 
2613   const SelectInst *SI = cast<SelectInst>(I);
2614   const Value *Cond = SI->getCondition();
2615   AArch64CC::CondCode CC = AArch64CC::NE;
2616   AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2617 
2618   if (optimizeSelect(SI))
2619     return true;
2620 
2621   // Try to pickup the flags, so we don't have to emit another compare.
2622   if (foldXALUIntrinsic(CC, I, Cond)) {
2623     // Fake request the condition to force emission of the XALU intrinsic.
2624     unsigned CondReg = getRegForValue(Cond);
2625     if (!CondReg)
2626       return false;
2627   } else if (isa<CmpInst>(Cond) && cast<CmpInst>(Cond)->hasOneUse() &&
2628              isValueAvailable(Cond)) {
2629     const auto *Cmp = cast<CmpInst>(Cond);
2630     // Try to optimize or fold the cmp.
2631     CmpInst::Predicate Predicate = optimizeCmpPredicate(Cmp);
2632     const Value *FoldSelect = nullptr;
2633     switch (Predicate) {
2634     default:
2635       break;
2636     case CmpInst::FCMP_FALSE:
2637       FoldSelect = SI->getFalseValue();
2638       break;
2639     case CmpInst::FCMP_TRUE:
2640       FoldSelect = SI->getTrueValue();
2641       break;
2642     }
2643 
2644     if (FoldSelect) {
2645       unsigned SrcReg = getRegForValue(FoldSelect);
2646       if (!SrcReg)
2647         return false;
2648       unsigned UseReg = lookUpRegForValue(SI);
2649       if (UseReg)
2650         MRI.clearKillFlags(UseReg);
2651 
2652       updateValueMap(I, SrcReg);
2653       return true;
2654     }
2655 
2656     // Emit the cmp.
2657     if (!emitCmp(Cmp->getOperand(0), Cmp->getOperand(1), Cmp->isUnsigned()))
2658       return false;
2659 
2660     // FCMP_UEQ and FCMP_ONE cannot be checked with a single select instruction.
2661     CC = getCompareCC(Predicate);
2662     switch (Predicate) {
2663     default:
2664       break;
2665     case CmpInst::FCMP_UEQ:
2666       ExtraCC = AArch64CC::EQ;
2667       CC = AArch64CC::VS;
2668       break;
2669     case CmpInst::FCMP_ONE:
2670       ExtraCC = AArch64CC::MI;
2671       CC = AArch64CC::GT;
2672       break;
2673     }
2674     assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2675   } else {
2676     unsigned CondReg = getRegForValue(Cond);
2677     if (!CondReg)
2678       return false;
2679     bool CondIsKill = hasTrivialKill(Cond);
2680 
2681     const MCInstrDesc &II = TII.get(AArch64::ANDSWri);
2682     CondReg = constrainOperandRegClass(II, CondReg, 1);
2683 
2684     // Emit a TST instruction (ANDS wzr, reg, #imm).
2685     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II,
2686             AArch64::WZR)
2687         .addReg(CondReg, getKillRegState(CondIsKill))
2688         .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
2689   }
2690 
2691   unsigned Src1Reg = getRegForValue(SI->getTrueValue());
2692   bool Src1IsKill = hasTrivialKill(SI->getTrueValue());
2693 
2694   unsigned Src2Reg = getRegForValue(SI->getFalseValue());
2695   bool Src2IsKill = hasTrivialKill(SI->getFalseValue());
2696 
2697   if (!Src1Reg || !Src2Reg)
2698     return false;
2699 
2700   if (ExtraCC != AArch64CC::AL) {
2701     Src2Reg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2702                                Src2IsKill, ExtraCC);
2703     Src2IsKill = true;
2704   }
2705   unsigned ResultReg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2706                                         Src2IsKill, CC);
2707   updateValueMap(I, ResultReg);
2708   return true;
2709 }
2710 
2711 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2712   Value *V = I->getOperand(0);
2713   if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2714     return false;
2715 
2716   unsigned Op = getRegForValue(V);
2717   if (Op == 0)
2718     return false;
2719 
2720   unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2721   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2722           ResultReg).addReg(Op);
2723   updateValueMap(I, ResultReg);
2724   return true;
2725 }
2726 
2727 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2728   Value *V = I->getOperand(0);
2729   if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2730     return false;
2731 
2732   unsigned Op = getRegForValue(V);
2733   if (Op == 0)
2734     return false;
2735 
2736   unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2737   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2738           ResultReg).addReg(Op);
2739   updateValueMap(I, ResultReg);
2740   return true;
2741 }
2742 
2743 // FPToUI and FPToSI
2744 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2745   MVT DestVT;
2746   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2747     return false;
2748 
2749   unsigned SrcReg = getRegForValue(I->getOperand(0));
2750   if (SrcReg == 0)
2751     return false;
2752 
2753   EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType(), true);
2754   if (SrcVT == MVT::f128)
2755     return false;
2756 
2757   unsigned Opc;
2758   if (SrcVT == MVT::f64) {
2759     if (Signed)
2760       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2761     else
2762       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2763   } else {
2764     if (Signed)
2765       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2766     else
2767       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2768   }
2769   unsigned ResultReg = createResultReg(
2770       DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2771   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2772       .addReg(SrcReg);
2773   updateValueMap(I, ResultReg);
2774   return true;
2775 }
2776 
2777 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2778   MVT DestVT;
2779   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2780     return false;
2781   assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2782           "Unexpected value type.");
2783 
2784   unsigned SrcReg = getRegForValue(I->getOperand(0));
2785   if (!SrcReg)
2786     return false;
2787   bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2788 
2789   EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType(), true);
2790 
2791   // Handle sign-extension.
2792   if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2793     SrcReg =
2794         emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2795     if (!SrcReg)
2796       return false;
2797     SrcIsKill = true;
2798   }
2799 
2800   unsigned Opc;
2801   if (SrcVT == MVT::i64) {
2802     if (Signed)
2803       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2804     else
2805       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2806   } else {
2807     if (Signed)
2808       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2809     else
2810       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2811   }
2812 
2813   unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2814                                       SrcIsKill);
2815   updateValueMap(I, ResultReg);
2816   return true;
2817 }
2818 
2819 bool AArch64FastISel::fastLowerArguments() {
2820   if (!FuncInfo.CanLowerReturn)
2821     return false;
2822 
2823   const Function *F = FuncInfo.Fn;
2824   if (F->isVarArg())
2825     return false;
2826 
2827   CallingConv::ID CC = F->getCallingConv();
2828   if (CC != CallingConv::C)
2829     return false;
2830 
2831   // Only handle simple cases of up to 8 GPR and FPR each.
2832   unsigned GPRCnt = 0;
2833   unsigned FPRCnt = 0;
2834   unsigned Idx = 0;
2835   for (auto const &Arg : F->args()) {
2836     // The first argument is at index 1.
2837     ++Idx;
2838     if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2839         F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2840         F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2841         F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
2842         F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
2843         F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2844       return false;
2845 
2846     Type *ArgTy = Arg.getType();
2847     if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2848       return false;
2849 
2850     EVT ArgVT = TLI.getValueType(DL, ArgTy);
2851     if (!ArgVT.isSimple())
2852       return false;
2853 
2854     MVT VT = ArgVT.getSimpleVT().SimpleTy;
2855     if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2856       return false;
2857 
2858     if (VT.isVector() &&
2859         (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2860       return false;
2861 
2862     if (VT >= MVT::i1 && VT <= MVT::i64)
2863       ++GPRCnt;
2864     else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2865              VT.is128BitVector())
2866       ++FPRCnt;
2867     else
2868       return false;
2869 
2870     if (GPRCnt > 8 || FPRCnt > 8)
2871       return false;
2872   }
2873 
2874   static const MCPhysReg Registers[6][8] = {
2875     { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2876       AArch64::W5, AArch64::W6, AArch64::W7 },
2877     { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2878       AArch64::X5, AArch64::X6, AArch64::X7 },
2879     { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2880       AArch64::H5, AArch64::H6, AArch64::H7 },
2881     { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2882       AArch64::S5, AArch64::S6, AArch64::S7 },
2883     { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2884       AArch64::D5, AArch64::D6, AArch64::D7 },
2885     { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2886       AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2887   };
2888 
2889   unsigned GPRIdx = 0;
2890   unsigned FPRIdx = 0;
2891   for (auto const &Arg : F->args()) {
2892     MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
2893     unsigned SrcReg;
2894     const TargetRegisterClass *RC;
2895     if (VT >= MVT::i1 && VT <= MVT::i32) {
2896       SrcReg = Registers[0][GPRIdx++];
2897       RC = &AArch64::GPR32RegClass;
2898       VT = MVT::i32;
2899     } else if (VT == MVT::i64) {
2900       SrcReg = Registers[1][GPRIdx++];
2901       RC = &AArch64::GPR64RegClass;
2902     } else if (VT == MVT::f16) {
2903       SrcReg = Registers[2][FPRIdx++];
2904       RC = &AArch64::FPR16RegClass;
2905     } else if (VT ==  MVT::f32) {
2906       SrcReg = Registers[3][FPRIdx++];
2907       RC = &AArch64::FPR32RegClass;
2908     } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2909       SrcReg = Registers[4][FPRIdx++];
2910       RC = &AArch64::FPR64RegClass;
2911     } else if (VT.is128BitVector()) {
2912       SrcReg = Registers[5][FPRIdx++];
2913       RC = &AArch64::FPR128RegClass;
2914     } else
2915       llvm_unreachable("Unexpected value type.");
2916 
2917     unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2918     // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2919     // Without this, EmitLiveInCopies may eliminate the livein if its only
2920     // use is a bitcast (which isn't turned into an instruction).
2921     unsigned ResultReg = createResultReg(RC);
2922     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2923             TII.get(TargetOpcode::COPY), ResultReg)
2924         .addReg(DstReg, getKillRegState(true));
2925     updateValueMap(&Arg, ResultReg);
2926   }
2927   return true;
2928 }
2929 
2930 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2931                                       SmallVectorImpl<MVT> &OutVTs,
2932                                       unsigned &NumBytes) {
2933   CallingConv::ID CC = CLI.CallConv;
2934   SmallVector<CCValAssign, 16> ArgLocs;
2935   CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2936   CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2937 
2938   // Get a count of how many bytes are to be pushed on the stack.
2939   NumBytes = CCInfo.getNextStackOffset();
2940 
2941   // Issue CALLSEQ_START
2942   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2943   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2944     .addImm(NumBytes);
2945 
2946   // Process the args.
2947   for (CCValAssign &VA : ArgLocs) {
2948     const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2949     MVT ArgVT = OutVTs[VA.getValNo()];
2950 
2951     unsigned ArgReg = getRegForValue(ArgVal);
2952     if (!ArgReg)
2953       return false;
2954 
2955     // Handle arg promotion: SExt, ZExt, AExt.
2956     switch (VA.getLocInfo()) {
2957     case CCValAssign::Full:
2958       break;
2959     case CCValAssign::SExt: {
2960       MVT DestVT = VA.getLocVT();
2961       MVT SrcVT = ArgVT;
2962       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2963       if (!ArgReg)
2964         return false;
2965       break;
2966     }
2967     case CCValAssign::AExt:
2968     // Intentional fall-through.
2969     case CCValAssign::ZExt: {
2970       MVT DestVT = VA.getLocVT();
2971       MVT SrcVT = ArgVT;
2972       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2973       if (!ArgReg)
2974         return false;
2975       break;
2976     }
2977     default:
2978       llvm_unreachable("Unknown arg promotion!");
2979     }
2980 
2981     // Now copy/store arg to correct locations.
2982     if (VA.isRegLoc() && !VA.needsCustom()) {
2983       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2984               TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2985       CLI.OutRegs.push_back(VA.getLocReg());
2986     } else if (VA.needsCustom()) {
2987       // FIXME: Handle custom args.
2988       return false;
2989     } else {
2990       assert(VA.isMemLoc() && "Assuming store on stack.");
2991 
2992       // Don't emit stores for undef values.
2993       if (isa<UndefValue>(ArgVal))
2994         continue;
2995 
2996       // Need to store on the stack.
2997       unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2998 
2999       unsigned BEAlign = 0;
3000       if (ArgSize < 8 && !Subtarget->isLittleEndian())
3001         BEAlign = 8 - ArgSize;
3002 
3003       Address Addr;
3004       Addr.setKind(Address::RegBase);
3005       Addr.setReg(AArch64::SP);
3006       Addr.setOffset(VA.getLocMemOffset() + BEAlign);
3007 
3008       unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3009       MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3010           MachinePointerInfo::getStack(*FuncInfo.MF, Addr.getOffset()),
3011           MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
3012 
3013       if (!emitStore(ArgVT, ArgReg, Addr, MMO))
3014         return false;
3015     }
3016   }
3017   return true;
3018 }
3019 
3020 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
3021                                  unsigned NumBytes) {
3022   CallingConv::ID CC = CLI.CallConv;
3023 
3024   // Issue CALLSEQ_END
3025   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3026   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3027     .addImm(NumBytes).addImm(0);
3028 
3029   // Now the return value.
3030   if (RetVT != MVT::isVoid) {
3031     SmallVector<CCValAssign, 16> RVLocs;
3032     CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
3033     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
3034 
3035     // Only handle a single return value.
3036     if (RVLocs.size() != 1)
3037       return false;
3038 
3039     // Copy all of the result registers out of their specified physreg.
3040     MVT CopyVT = RVLocs[0].getValVT();
3041 
3042     // TODO: Handle big-endian results
3043     if (CopyVT.isVector() && !Subtarget->isLittleEndian())
3044       return false;
3045 
3046     unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
3047     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3048             TII.get(TargetOpcode::COPY), ResultReg)
3049         .addReg(RVLocs[0].getLocReg());
3050     CLI.InRegs.push_back(RVLocs[0].getLocReg());
3051 
3052     CLI.ResultReg = ResultReg;
3053     CLI.NumResultRegs = 1;
3054   }
3055 
3056   return true;
3057 }
3058 
3059 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3060   CallingConv::ID CC  = CLI.CallConv;
3061   bool IsTailCall     = CLI.IsTailCall;
3062   bool IsVarArg       = CLI.IsVarArg;
3063   const Value *Callee = CLI.Callee;
3064   MCSymbol *Symbol = CLI.Symbol;
3065 
3066   if (!Callee && !Symbol)
3067     return false;
3068 
3069   // Allow SelectionDAG isel to handle tail calls.
3070   if (IsTailCall)
3071     return false;
3072 
3073   CodeModel::Model CM = TM.getCodeModel();
3074   // Only support the small and large code model.
3075   if (CM != CodeModel::Small && CM != CodeModel::Large)
3076     return false;
3077 
3078   // FIXME: Add large code model support for ELF.
3079   if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
3080     return false;
3081 
3082   // Let SDISel handle vararg functions.
3083   if (IsVarArg)
3084     return false;
3085 
3086   // FIXME: Only handle *simple* calls for now.
3087   MVT RetVT;
3088   if (CLI.RetTy->isVoidTy())
3089     RetVT = MVT::isVoid;
3090   else if (!isTypeLegal(CLI.RetTy, RetVT))
3091     return false;
3092 
3093   for (auto Flag : CLI.OutFlags)
3094     if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal() ||
3095         Flag.isSwiftSelf() || Flag.isSwiftError())
3096       return false;
3097 
3098   // Set up the argument vectors.
3099   SmallVector<MVT, 16> OutVTs;
3100   OutVTs.reserve(CLI.OutVals.size());
3101 
3102   for (auto *Val : CLI.OutVals) {
3103     MVT VT;
3104     if (!isTypeLegal(Val->getType(), VT) &&
3105         !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
3106       return false;
3107 
3108     // We don't handle vector parameters yet.
3109     if (VT.isVector() || VT.getSizeInBits() > 64)
3110       return false;
3111 
3112     OutVTs.push_back(VT);
3113   }
3114 
3115   Address Addr;
3116   if (Callee && !computeCallAddress(Callee, Addr))
3117     return false;
3118 
3119   // Handle the arguments now that we've gotten them.
3120   unsigned NumBytes;
3121   if (!processCallArgs(CLI, OutVTs, NumBytes))
3122     return false;
3123 
3124   // Issue the call.
3125   MachineInstrBuilder MIB;
3126   if (CM == CodeModel::Small) {
3127     const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
3128     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
3129     if (Symbol)
3130       MIB.addSym(Symbol, 0);
3131     else if (Addr.getGlobalValue())
3132       MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
3133     else if (Addr.getReg()) {
3134       unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
3135       MIB.addReg(Reg);
3136     } else
3137       return false;
3138   } else {
3139     unsigned CallReg = 0;
3140     if (Symbol) {
3141       unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
3142       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
3143               ADRPReg)
3144           .addSym(Symbol, AArch64II::MO_GOT | AArch64II::MO_PAGE);
3145 
3146       CallReg = createResultReg(&AArch64::GPR64RegClass);
3147       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3148               TII.get(AArch64::LDRXui), CallReg)
3149           .addReg(ADRPReg)
3150           .addSym(Symbol,
3151                   AArch64II::MO_GOT | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3152     } else if (Addr.getGlobalValue())
3153       CallReg = materializeGV(Addr.getGlobalValue());
3154     else if (Addr.getReg())
3155       CallReg = Addr.getReg();
3156 
3157     if (!CallReg)
3158       return false;
3159 
3160     const MCInstrDesc &II = TII.get(AArch64::BLR);
3161     CallReg = constrainOperandRegClass(II, CallReg, 0);
3162     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
3163   }
3164 
3165   // Add implicit physical register uses to the call.
3166   for (auto Reg : CLI.OutRegs)
3167     MIB.addReg(Reg, RegState::Implicit);
3168 
3169   // Add a register mask with the call-preserved registers.
3170   // Proper defs for return values will be added by setPhysRegsDeadExcept().
3171   MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3172 
3173   CLI.Call = MIB;
3174 
3175   // Finish off the call including any return values.
3176   return finishCall(CLI, RetVT, NumBytes);
3177 }
3178 
3179 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
3180   if (Alignment)
3181     return Len / Alignment <= 4;
3182   else
3183     return Len < 32;
3184 }
3185 
3186 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
3187                                          uint64_t Len, unsigned Alignment) {
3188   // Make sure we don't bloat code by inlining very large memcpy's.
3189   if (!isMemCpySmall(Len, Alignment))
3190     return false;
3191 
3192   int64_t UnscaledOffset = 0;
3193   Address OrigDest = Dest;
3194   Address OrigSrc = Src;
3195 
3196   while (Len) {
3197     MVT VT;
3198     if (!Alignment || Alignment >= 8) {
3199       if (Len >= 8)
3200         VT = MVT::i64;
3201       else if (Len >= 4)
3202         VT = MVT::i32;
3203       else if (Len >= 2)
3204         VT = MVT::i16;
3205       else {
3206         VT = MVT::i8;
3207       }
3208     } else {
3209       // Bound based on alignment.
3210       if (Len >= 4 && Alignment == 4)
3211         VT = MVT::i32;
3212       else if (Len >= 2 && Alignment == 2)
3213         VT = MVT::i16;
3214       else {
3215         VT = MVT::i8;
3216       }
3217     }
3218 
3219     unsigned ResultReg = emitLoad(VT, VT, Src);
3220     if (!ResultReg)
3221       return false;
3222 
3223     if (!emitStore(VT, ResultReg, Dest))
3224       return false;
3225 
3226     int64_t Size = VT.getSizeInBits() / 8;
3227     Len -= Size;
3228     UnscaledOffset += Size;
3229 
3230     // We need to recompute the unscaled offset for each iteration.
3231     Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
3232     Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
3233   }
3234 
3235   return true;
3236 }
3237 
3238 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
3239 /// into the user. The condition code will only be updated on success.
3240 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
3241                                         const Instruction *I,
3242                                         const Value *Cond) {
3243   if (!isa<ExtractValueInst>(Cond))
3244     return false;
3245 
3246   const auto *EV = cast<ExtractValueInst>(Cond);
3247   if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
3248     return false;
3249 
3250   const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
3251   MVT RetVT;
3252   const Function *Callee = II->getCalledFunction();
3253   Type *RetTy =
3254   cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
3255   if (!isTypeLegal(RetTy, RetVT))
3256     return false;
3257 
3258   if (RetVT != MVT::i32 && RetVT != MVT::i64)
3259     return false;
3260 
3261   const Value *LHS = II->getArgOperand(0);
3262   const Value *RHS = II->getArgOperand(1);
3263 
3264   // Canonicalize immediate to the RHS.
3265   if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3266       isCommutativeIntrinsic(II))
3267     std::swap(LHS, RHS);
3268 
3269   // Simplify multiplies.
3270   Intrinsic::ID IID = II->getIntrinsicID();
3271   switch (IID) {
3272   default:
3273     break;
3274   case Intrinsic::smul_with_overflow:
3275     if (const auto *C = dyn_cast<ConstantInt>(RHS))
3276       if (C->getValue() == 2)
3277         IID = Intrinsic::sadd_with_overflow;
3278     break;
3279   case Intrinsic::umul_with_overflow:
3280     if (const auto *C = dyn_cast<ConstantInt>(RHS))
3281       if (C->getValue() == 2)
3282         IID = Intrinsic::uadd_with_overflow;
3283     break;
3284   }
3285 
3286   AArch64CC::CondCode TmpCC;
3287   switch (IID) {
3288   default:
3289     return false;
3290   case Intrinsic::sadd_with_overflow:
3291   case Intrinsic::ssub_with_overflow:
3292     TmpCC = AArch64CC::VS;
3293     break;
3294   case Intrinsic::uadd_with_overflow:
3295     TmpCC = AArch64CC::HS;
3296     break;
3297   case Intrinsic::usub_with_overflow:
3298     TmpCC = AArch64CC::LO;
3299     break;
3300   case Intrinsic::smul_with_overflow:
3301   case Intrinsic::umul_with_overflow:
3302     TmpCC = AArch64CC::NE;
3303     break;
3304   }
3305 
3306   // Check if both instructions are in the same basic block.
3307   if (!isValueAvailable(II))
3308     return false;
3309 
3310   // Make sure nothing is in the way
3311   BasicBlock::const_iterator Start(I);
3312   BasicBlock::const_iterator End(II);
3313   for (auto Itr = std::prev(Start); Itr != End; --Itr) {
3314     // We only expect extractvalue instructions between the intrinsic and the
3315     // instruction to be selected.
3316     if (!isa<ExtractValueInst>(Itr))
3317       return false;
3318 
3319     // Check that the extractvalue operand comes from the intrinsic.
3320     const auto *EVI = cast<ExtractValueInst>(Itr);
3321     if (EVI->getAggregateOperand() != II)
3322       return false;
3323   }
3324 
3325   CC = TmpCC;
3326   return true;
3327 }
3328 
3329 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3330   // FIXME: Handle more intrinsics.
3331   switch (II->getIntrinsicID()) {
3332   default: return false;
3333   case Intrinsic::frameaddress: {
3334     MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3335     MFI->setFrameAddressIsTaken(true);
3336 
3337     const AArch64RegisterInfo *RegInfo =
3338         static_cast<const AArch64RegisterInfo *>(Subtarget->getRegisterInfo());
3339     unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3340     unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3341     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3342             TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3343     // Recursively load frame address
3344     // ldr x0, [fp]
3345     // ldr x0, [x0]
3346     // ldr x0, [x0]
3347     // ...
3348     unsigned DestReg;
3349     unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3350     while (Depth--) {
3351       DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3352                                 SrcReg, /*IsKill=*/true, 0);
3353       assert(DestReg && "Unexpected LDR instruction emission failure.");
3354       SrcReg = DestReg;
3355     }
3356 
3357     updateValueMap(II, SrcReg);
3358     return true;
3359   }
3360   case Intrinsic::memcpy:
3361   case Intrinsic::memmove: {
3362     const auto *MTI = cast<MemTransferInst>(II);
3363     // Don't handle volatile.
3364     if (MTI->isVolatile())
3365       return false;
3366 
3367     // Disable inlining for memmove before calls to ComputeAddress.  Otherwise,
3368     // we would emit dead code because we don't currently handle memmoves.
3369     bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3370     if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3371       // Small memcpy's are common enough that we want to do them without a call
3372       // if possible.
3373       uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3374       unsigned Alignment = MTI->getAlignment();
3375       if (isMemCpySmall(Len, Alignment)) {
3376         Address Dest, Src;
3377         if (!computeAddress(MTI->getRawDest(), Dest) ||
3378             !computeAddress(MTI->getRawSource(), Src))
3379           return false;
3380         if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3381           return true;
3382       }
3383     }
3384 
3385     if (!MTI->getLength()->getType()->isIntegerTy(64))
3386       return false;
3387 
3388     if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3389       // Fast instruction selection doesn't support the special
3390       // address spaces.
3391       return false;
3392 
3393     const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3394     return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3395   }
3396   case Intrinsic::memset: {
3397     const MemSetInst *MSI = cast<MemSetInst>(II);
3398     // Don't handle volatile.
3399     if (MSI->isVolatile())
3400       return false;
3401 
3402     if (!MSI->getLength()->getType()->isIntegerTy(64))
3403       return false;
3404 
3405     if (MSI->getDestAddressSpace() > 255)
3406       // Fast instruction selection doesn't support the special
3407       // address spaces.
3408       return false;
3409 
3410     return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3411   }
3412   case Intrinsic::sin:
3413   case Intrinsic::cos:
3414   case Intrinsic::pow: {
3415     MVT RetVT;
3416     if (!isTypeLegal(II->getType(), RetVT))
3417       return false;
3418 
3419     if (RetVT != MVT::f32 && RetVT != MVT::f64)
3420       return false;
3421 
3422     static const RTLIB::Libcall LibCallTable[3][2] = {
3423       { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3424       { RTLIB::COS_F32, RTLIB::COS_F64 },
3425       { RTLIB::POW_F32, RTLIB::POW_F64 }
3426     };
3427     RTLIB::Libcall LC;
3428     bool Is64Bit = RetVT == MVT::f64;
3429     switch (II->getIntrinsicID()) {
3430     default:
3431       llvm_unreachable("Unexpected intrinsic.");
3432     case Intrinsic::sin:
3433       LC = LibCallTable[0][Is64Bit];
3434       break;
3435     case Intrinsic::cos:
3436       LC = LibCallTable[1][Is64Bit];
3437       break;
3438     case Intrinsic::pow:
3439       LC = LibCallTable[2][Is64Bit];
3440       break;
3441     }
3442 
3443     ArgListTy Args;
3444     Args.reserve(II->getNumArgOperands());
3445 
3446     // Populate the argument list.
3447     for (auto &Arg : II->arg_operands()) {
3448       ArgListEntry Entry;
3449       Entry.Val = Arg;
3450       Entry.Ty = Arg->getType();
3451       Args.push_back(Entry);
3452     }
3453 
3454     CallLoweringInfo CLI;
3455     MCContext &Ctx = MF->getContext();
3456     CLI.setCallee(DL, Ctx, TLI.getLibcallCallingConv(LC), II->getType(),
3457                   TLI.getLibcallName(LC), std::move(Args));
3458     if (!lowerCallTo(CLI))
3459       return false;
3460     updateValueMap(II, CLI.ResultReg);
3461     return true;
3462   }
3463   case Intrinsic::fabs: {
3464     MVT VT;
3465     if (!isTypeLegal(II->getType(), VT))
3466       return false;
3467 
3468     unsigned Opc;
3469     switch (VT.SimpleTy) {
3470     default:
3471       return false;
3472     case MVT::f32:
3473       Opc = AArch64::FABSSr;
3474       break;
3475     case MVT::f64:
3476       Opc = AArch64::FABSDr;
3477       break;
3478     }
3479     unsigned SrcReg = getRegForValue(II->getOperand(0));
3480     if (!SrcReg)
3481       return false;
3482     bool SrcRegIsKill = hasTrivialKill(II->getOperand(0));
3483     unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3484     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3485       .addReg(SrcReg, getKillRegState(SrcRegIsKill));
3486     updateValueMap(II, ResultReg);
3487     return true;
3488   }
3489   case Intrinsic::trap: {
3490     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3491         .addImm(1);
3492     return true;
3493   }
3494   case Intrinsic::sqrt: {
3495     Type *RetTy = II->getCalledFunction()->getReturnType();
3496 
3497     MVT VT;
3498     if (!isTypeLegal(RetTy, VT))
3499       return false;
3500 
3501     unsigned Op0Reg = getRegForValue(II->getOperand(0));
3502     if (!Op0Reg)
3503       return false;
3504     bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3505 
3506     unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3507     if (!ResultReg)
3508       return false;
3509 
3510     updateValueMap(II, ResultReg);
3511     return true;
3512   }
3513   case Intrinsic::sadd_with_overflow:
3514   case Intrinsic::uadd_with_overflow:
3515   case Intrinsic::ssub_with_overflow:
3516   case Intrinsic::usub_with_overflow:
3517   case Intrinsic::smul_with_overflow:
3518   case Intrinsic::umul_with_overflow: {
3519     // This implements the basic lowering of the xalu with overflow intrinsics.
3520     const Function *Callee = II->getCalledFunction();
3521     auto *Ty = cast<StructType>(Callee->getReturnType());
3522     Type *RetTy = Ty->getTypeAtIndex(0U);
3523 
3524     MVT VT;
3525     if (!isTypeLegal(RetTy, VT))
3526       return false;
3527 
3528     if (VT != MVT::i32 && VT != MVT::i64)
3529       return false;
3530 
3531     const Value *LHS = II->getArgOperand(0);
3532     const Value *RHS = II->getArgOperand(1);
3533     // Canonicalize immediate to the RHS.
3534     if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3535         isCommutativeIntrinsic(II))
3536       std::swap(LHS, RHS);
3537 
3538     // Simplify multiplies.
3539     Intrinsic::ID IID = II->getIntrinsicID();
3540     switch (IID) {
3541     default:
3542       break;
3543     case Intrinsic::smul_with_overflow:
3544       if (const auto *C = dyn_cast<ConstantInt>(RHS))
3545         if (C->getValue() == 2) {
3546           IID = Intrinsic::sadd_with_overflow;
3547           RHS = LHS;
3548         }
3549       break;
3550     case Intrinsic::umul_with_overflow:
3551       if (const auto *C = dyn_cast<ConstantInt>(RHS))
3552         if (C->getValue() == 2) {
3553           IID = Intrinsic::uadd_with_overflow;
3554           RHS = LHS;
3555         }
3556       break;
3557     }
3558 
3559     unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3560     AArch64CC::CondCode CC = AArch64CC::Invalid;
3561     switch (IID) {
3562     default: llvm_unreachable("Unexpected intrinsic!");
3563     case Intrinsic::sadd_with_overflow:
3564       ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3565       CC = AArch64CC::VS;
3566       break;
3567     case Intrinsic::uadd_with_overflow:
3568       ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3569       CC = AArch64CC::HS;
3570       break;
3571     case Intrinsic::ssub_with_overflow:
3572       ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3573       CC = AArch64CC::VS;
3574       break;
3575     case Intrinsic::usub_with_overflow:
3576       ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3577       CC = AArch64CC::LO;
3578       break;
3579     case Intrinsic::smul_with_overflow: {
3580       CC = AArch64CC::NE;
3581       unsigned LHSReg = getRegForValue(LHS);
3582       if (!LHSReg)
3583         return false;
3584       bool LHSIsKill = hasTrivialKill(LHS);
3585 
3586       unsigned RHSReg = getRegForValue(RHS);
3587       if (!RHSReg)
3588         return false;
3589       bool RHSIsKill = hasTrivialKill(RHS);
3590 
3591       if (VT == MVT::i32) {
3592         MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3593         unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3594                                        /*IsKill=*/false, 32);
3595         MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3596                                             AArch64::sub_32);
3597         ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3598                                               AArch64::sub_32);
3599         emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3600                     AArch64_AM::ASR, 31, /*WantResult=*/false);
3601       } else {
3602         assert(VT == MVT::i64 && "Unexpected value type.");
3603         // LHSReg and RHSReg cannot be killed by this Mul, since they are
3604         // reused in the next instruction.
3605         MulReg = emitMul_rr(VT, LHSReg, /*IsKill=*/false, RHSReg,
3606                             /*IsKill=*/false);
3607         unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3608                                         RHSReg, RHSIsKill);
3609         emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3610                     AArch64_AM::ASR, 63, /*WantResult=*/false);
3611       }
3612       break;
3613     }
3614     case Intrinsic::umul_with_overflow: {
3615       CC = AArch64CC::NE;
3616       unsigned LHSReg = getRegForValue(LHS);
3617       if (!LHSReg)
3618         return false;
3619       bool LHSIsKill = hasTrivialKill(LHS);
3620 
3621       unsigned RHSReg = getRegForValue(RHS);
3622       if (!RHSReg)
3623         return false;
3624       bool RHSIsKill = hasTrivialKill(RHS);
3625 
3626       if (VT == MVT::i32) {
3627         MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3628         emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3629                     /*IsKill=*/false, AArch64_AM::LSR, 32,
3630                     /*WantResult=*/false);
3631         MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3632                                             AArch64::sub_32);
3633       } else {
3634         assert(VT == MVT::i64 && "Unexpected value type.");
3635         // LHSReg and RHSReg cannot be killed by this Mul, since they are
3636         // reused in the next instruction.
3637         MulReg = emitMul_rr(VT, LHSReg, /*IsKill=*/false, RHSReg,
3638                             /*IsKill=*/false);
3639         unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3640                                         RHSReg, RHSIsKill);
3641         emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3642                     /*IsKill=*/false, /*WantResult=*/false);
3643       }
3644       break;
3645     }
3646     }
3647 
3648     if (MulReg) {
3649       ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3650       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3651               TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3652     }
3653 
3654     ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3655                                   AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3656                                   /*IsKill=*/true, getInvertedCondCode(CC));
3657     (void)ResultReg2;
3658     assert((ResultReg1 + 1) == ResultReg2 &&
3659            "Nonconsecutive result registers.");
3660     updateValueMap(II, ResultReg1, 2);
3661     return true;
3662   }
3663   }
3664   return false;
3665 }
3666 
3667 bool AArch64FastISel::selectRet(const Instruction *I) {
3668   const ReturnInst *Ret = cast<ReturnInst>(I);
3669   const Function &F = *I->getParent()->getParent();
3670 
3671   if (!FuncInfo.CanLowerReturn)
3672     return false;
3673 
3674   if (F.isVarArg())
3675     return false;
3676 
3677   if (TLI.supportSwiftError() &&
3678       F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
3679     return false;
3680 
3681   if (TLI.supportSplitCSR(FuncInfo.MF))
3682     return false;
3683 
3684   // Build a list of return value registers.
3685   SmallVector<unsigned, 4> RetRegs;
3686 
3687   if (Ret->getNumOperands() > 0) {
3688     CallingConv::ID CC = F.getCallingConv();
3689     SmallVector<ISD::OutputArg, 4> Outs;
3690     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
3691 
3692     // Analyze operands of the call, assigning locations to each operand.
3693     SmallVector<CCValAssign, 16> ValLocs;
3694     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3695     CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3696                                                      : RetCC_AArch64_AAPCS;
3697     CCInfo.AnalyzeReturn(Outs, RetCC);
3698 
3699     // Only handle a single return value for now.
3700     if (ValLocs.size() != 1)
3701       return false;
3702 
3703     CCValAssign &VA = ValLocs[0];
3704     const Value *RV = Ret->getOperand(0);
3705 
3706     // Don't bother handling odd stuff for now.
3707     if ((VA.getLocInfo() != CCValAssign::Full) &&
3708         (VA.getLocInfo() != CCValAssign::BCvt))
3709       return false;
3710 
3711     // Only handle register returns for now.
3712     if (!VA.isRegLoc())
3713       return false;
3714 
3715     unsigned Reg = getRegForValue(RV);
3716     if (Reg == 0)
3717       return false;
3718 
3719     unsigned SrcReg = Reg + VA.getValNo();
3720     unsigned DestReg = VA.getLocReg();
3721     // Avoid a cross-class copy. This is very unlikely.
3722     if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3723       return false;
3724 
3725     EVT RVEVT = TLI.getValueType(DL, RV->getType());
3726     if (!RVEVT.isSimple())
3727       return false;
3728 
3729     // Vectors (of > 1 lane) in big endian need tricky handling.
3730     if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3731         !Subtarget->isLittleEndian())
3732       return false;
3733 
3734     MVT RVVT = RVEVT.getSimpleVT();
3735     if (RVVT == MVT::f128)
3736       return false;
3737 
3738     MVT DestVT = VA.getValVT();
3739     // Special handling for extended integers.
3740     if (RVVT != DestVT) {
3741       if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3742         return false;
3743 
3744       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3745         return false;
3746 
3747       bool IsZExt = Outs[0].Flags.isZExt();
3748       SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3749       if (SrcReg == 0)
3750         return false;
3751     }
3752 
3753     // Make the copy.
3754     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3755             TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3756 
3757     // Add register to return instruction.
3758     RetRegs.push_back(VA.getLocReg());
3759   }
3760 
3761   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3762                                     TII.get(AArch64::RET_ReallyLR));
3763   for (unsigned RetReg : RetRegs)
3764     MIB.addReg(RetReg, RegState::Implicit);
3765   return true;
3766 }
3767 
3768 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3769   Type *DestTy = I->getType();
3770   Value *Op = I->getOperand(0);
3771   Type *SrcTy = Op->getType();
3772 
3773   EVT SrcEVT = TLI.getValueType(DL, SrcTy, true);
3774   EVT DestEVT = TLI.getValueType(DL, DestTy, true);
3775   if (!SrcEVT.isSimple())
3776     return false;
3777   if (!DestEVT.isSimple())
3778     return false;
3779 
3780   MVT SrcVT = SrcEVT.getSimpleVT();
3781   MVT DestVT = DestEVT.getSimpleVT();
3782 
3783   if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3784       SrcVT != MVT::i8)
3785     return false;
3786   if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3787       DestVT != MVT::i1)
3788     return false;
3789 
3790   unsigned SrcReg = getRegForValue(Op);
3791   if (!SrcReg)
3792     return false;
3793   bool SrcIsKill = hasTrivialKill(Op);
3794 
3795   // If we're truncating from i64 to a smaller non-legal type then generate an
3796   // AND. Otherwise, we know the high bits are undefined and a truncate only
3797   // generate a COPY. We cannot mark the source register also as result
3798   // register, because this can incorrectly transfer the kill flag onto the
3799   // source register.
3800   unsigned ResultReg;
3801   if (SrcVT == MVT::i64) {
3802     uint64_t Mask = 0;
3803     switch (DestVT.SimpleTy) {
3804     default:
3805       // Trunc i64 to i32 is handled by the target-independent fast-isel.
3806       return false;
3807     case MVT::i1:
3808       Mask = 0x1;
3809       break;
3810     case MVT::i8:
3811       Mask = 0xff;
3812       break;
3813     case MVT::i16:
3814       Mask = 0xffff;
3815       break;
3816     }
3817     // Issue an extract_subreg to get the lower 32-bits.
3818     unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3819                                                 AArch64::sub_32);
3820     // Create the AND instruction which performs the actual truncation.
3821     ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3822     assert(ResultReg && "Unexpected AND instruction emission failure.");
3823   } else {
3824     ResultReg = createResultReg(&AArch64::GPR32RegClass);
3825     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3826             TII.get(TargetOpcode::COPY), ResultReg)
3827         .addReg(SrcReg, getKillRegState(SrcIsKill));
3828   }
3829 
3830   updateValueMap(I, ResultReg);
3831   return true;
3832 }
3833 
3834 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3835   assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3836           DestVT == MVT::i64) &&
3837          "Unexpected value type.");
3838   // Handle i8 and i16 as i32.
3839   if (DestVT == MVT::i8 || DestVT == MVT::i16)
3840     DestVT = MVT::i32;
3841 
3842   if (IsZExt) {
3843     unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3844     assert(ResultReg && "Unexpected AND instruction emission failure.");
3845     if (DestVT == MVT::i64) {
3846       // We're ZExt i1 to i64.  The ANDWri Wd, Ws, #1 implicitly clears the
3847       // upper 32 bits.  Emit a SUBREG_TO_REG to extend from Wd to Xd.
3848       unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3849       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3850               TII.get(AArch64::SUBREG_TO_REG), Reg64)
3851           .addImm(0)
3852           .addReg(ResultReg)
3853           .addImm(AArch64::sub_32);
3854       ResultReg = Reg64;
3855     }
3856     return ResultReg;
3857   } else {
3858     if (DestVT == MVT::i64) {
3859       // FIXME: We're SExt i1 to i64.
3860       return 0;
3861     }
3862     return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3863                             /*TODO:IsKill=*/false, 0, 0);
3864   }
3865 }
3866 
3867 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3868                                       unsigned Op1, bool Op1IsKill) {
3869   unsigned Opc, ZReg;
3870   switch (RetVT.SimpleTy) {
3871   default: return 0;
3872   case MVT::i8:
3873   case MVT::i16:
3874   case MVT::i32:
3875     RetVT = MVT::i32;
3876     Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3877   case MVT::i64:
3878     Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3879   }
3880 
3881   const TargetRegisterClass *RC =
3882       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3883   return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3884                           /*IsKill=*/ZReg, true);
3885 }
3886 
3887 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3888                                         unsigned Op1, bool Op1IsKill) {
3889   if (RetVT != MVT::i64)
3890     return 0;
3891 
3892   return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3893                           Op0, Op0IsKill, Op1, Op1IsKill,
3894                           AArch64::XZR, /*IsKill=*/true);
3895 }
3896 
3897 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3898                                         unsigned Op1, bool Op1IsKill) {
3899   if (RetVT != MVT::i64)
3900     return 0;
3901 
3902   return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3903                           Op0, Op0IsKill, Op1, Op1IsKill,
3904                           AArch64::XZR, /*IsKill=*/true);
3905 }
3906 
3907 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3908                                      unsigned Op1Reg, bool Op1IsKill) {
3909   unsigned Opc = 0;
3910   bool NeedTrunc = false;
3911   uint64_t Mask = 0;
3912   switch (RetVT.SimpleTy) {
3913   default: return 0;
3914   case MVT::i8:  Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff;   break;
3915   case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3916   case MVT::i32: Opc = AArch64::LSLVWr;                                  break;
3917   case MVT::i64: Opc = AArch64::LSLVXr;                                  break;
3918   }
3919 
3920   const TargetRegisterClass *RC =
3921       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3922   if (NeedTrunc) {
3923     Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3924     Op1IsKill = true;
3925   }
3926   unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3927                                        Op1IsKill);
3928   if (NeedTrunc)
3929     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3930   return ResultReg;
3931 }
3932 
3933 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3934                                      bool Op0IsKill, uint64_t Shift,
3935                                      bool IsZExt) {
3936   assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3937          "Unexpected source/return type pair.");
3938   assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3939           SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3940          "Unexpected source value type.");
3941   assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3942           RetVT == MVT::i64) && "Unexpected return value type.");
3943 
3944   bool Is64Bit = (RetVT == MVT::i64);
3945   unsigned RegSize = Is64Bit ? 64 : 32;
3946   unsigned DstBits = RetVT.getSizeInBits();
3947   unsigned SrcBits = SrcVT.getSizeInBits();
3948   const TargetRegisterClass *RC =
3949       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3950 
3951   // Just emit a copy for "zero" shifts.
3952   if (Shift == 0) {
3953     if (RetVT == SrcVT) {
3954       unsigned ResultReg = createResultReg(RC);
3955       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3956               TII.get(TargetOpcode::COPY), ResultReg)
3957           .addReg(Op0, getKillRegState(Op0IsKill));
3958       return ResultReg;
3959     } else
3960       return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3961   }
3962 
3963   // Don't deal with undefined shifts.
3964   if (Shift >= DstBits)
3965     return 0;
3966 
3967   // For immediate shifts we can fold the zero-/sign-extension into the shift.
3968   // {S|U}BFM Wd, Wn, #r, #s
3969   // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3970 
3971   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3972   // %2 = shl i16 %1, 4
3973   // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3974   // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3975   // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3976   // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3977 
3978   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3979   // %2 = shl i16 %1, 8
3980   // Wd<32+7-24,32-24> = Wn<7:0>
3981   // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3982   // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3983   // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3984 
3985   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3986   // %2 = shl i16 %1, 12
3987   // Wd<32+3-20,32-20> = Wn<3:0>
3988   // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3989   // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3990   // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3991 
3992   unsigned ImmR = RegSize - Shift;
3993   // Limit the width to the length of the source type.
3994   unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3995   static const unsigned OpcTable[2][2] = {
3996     {AArch64::SBFMWri, AArch64::SBFMXri},
3997     {AArch64::UBFMWri, AArch64::UBFMXri}
3998   };
3999   unsigned Opc = OpcTable[IsZExt][Is64Bit];
4000   if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4001     unsigned TmpReg = MRI.createVirtualRegister(RC);
4002     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4003             TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4004         .addImm(0)
4005         .addReg(Op0, getKillRegState(Op0IsKill))
4006         .addImm(AArch64::sub_32);
4007     Op0 = TmpReg;
4008     Op0IsKill = true;
4009   }
4010   return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4011 }
4012 
4013 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
4014                                      unsigned Op1Reg, bool Op1IsKill) {
4015   unsigned Opc = 0;
4016   bool NeedTrunc = false;
4017   uint64_t Mask = 0;
4018   switch (RetVT.SimpleTy) {
4019   default: return 0;
4020   case MVT::i8:  Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff;   break;
4021   case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
4022   case MVT::i32: Opc = AArch64::LSRVWr; break;
4023   case MVT::i64: Opc = AArch64::LSRVXr; break;
4024   }
4025 
4026   const TargetRegisterClass *RC =
4027       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4028   if (NeedTrunc) {
4029     Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
4030     Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4031     Op0IsKill = Op1IsKill = true;
4032   }
4033   unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4034                                        Op1IsKill);
4035   if (NeedTrunc)
4036     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4037   return ResultReg;
4038 }
4039 
4040 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4041                                      bool Op0IsKill, uint64_t Shift,
4042                                      bool IsZExt) {
4043   assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4044          "Unexpected source/return type pair.");
4045   assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4046           SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4047          "Unexpected source value type.");
4048   assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4049           RetVT == MVT::i64) && "Unexpected return value type.");
4050 
4051   bool Is64Bit = (RetVT == MVT::i64);
4052   unsigned RegSize = Is64Bit ? 64 : 32;
4053   unsigned DstBits = RetVT.getSizeInBits();
4054   unsigned SrcBits = SrcVT.getSizeInBits();
4055   const TargetRegisterClass *RC =
4056       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4057 
4058   // Just emit a copy for "zero" shifts.
4059   if (Shift == 0) {
4060     if (RetVT == SrcVT) {
4061       unsigned ResultReg = createResultReg(RC);
4062       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4063               TII.get(TargetOpcode::COPY), ResultReg)
4064       .addReg(Op0, getKillRegState(Op0IsKill));
4065       return ResultReg;
4066     } else
4067       return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4068   }
4069 
4070   // Don't deal with undefined shifts.
4071   if (Shift >= DstBits)
4072     return 0;
4073 
4074   // For immediate shifts we can fold the zero-/sign-extension into the shift.
4075   // {S|U}BFM Wd, Wn, #r, #s
4076   // Wd<s-r:0> = Wn<s:r> when r <= s
4077 
4078   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4079   // %2 = lshr i16 %1, 4
4080   // Wd<7-4:0> = Wn<7:4>
4081   // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
4082   // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4083   // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4084 
4085   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4086   // %2 = lshr i16 %1, 8
4087   // Wd<7-7,0> = Wn<7:7>
4088   // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
4089   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4090   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4091 
4092   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4093   // %2 = lshr i16 %1, 12
4094   // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4095   // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
4096   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4097   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4098 
4099   if (Shift >= SrcBits && IsZExt)
4100     return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4101 
4102   // It is not possible to fold a sign-extend into the LShr instruction. In this
4103   // case emit a sign-extend.
4104   if (!IsZExt) {
4105     Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4106     if (!Op0)
4107       return 0;
4108     Op0IsKill = true;
4109     SrcVT = RetVT;
4110     SrcBits = SrcVT.getSizeInBits();
4111     IsZExt = true;
4112   }
4113 
4114   unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4115   unsigned ImmS = SrcBits - 1;
4116   static const unsigned OpcTable[2][2] = {
4117     {AArch64::SBFMWri, AArch64::SBFMXri},
4118     {AArch64::UBFMWri, AArch64::UBFMXri}
4119   };
4120   unsigned Opc = OpcTable[IsZExt][Is64Bit];
4121   if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4122     unsigned TmpReg = MRI.createVirtualRegister(RC);
4123     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4124             TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4125         .addImm(0)
4126         .addReg(Op0, getKillRegState(Op0IsKill))
4127         .addImm(AArch64::sub_32);
4128     Op0 = TmpReg;
4129     Op0IsKill = true;
4130   }
4131   return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4132 }
4133 
4134 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
4135                                      unsigned Op1Reg, bool Op1IsKill) {
4136   unsigned Opc = 0;
4137   bool NeedTrunc = false;
4138   uint64_t Mask = 0;
4139   switch (RetVT.SimpleTy) {
4140   default: return 0;
4141   case MVT::i8:  Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff;   break;
4142   case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
4143   case MVT::i32: Opc = AArch64::ASRVWr;                                  break;
4144   case MVT::i64: Opc = AArch64::ASRVXr;                                  break;
4145   }
4146 
4147   const TargetRegisterClass *RC =
4148       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4149   if (NeedTrunc) {
4150     Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
4151     Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4152     Op0IsKill = Op1IsKill = true;
4153   }
4154   unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4155                                        Op1IsKill);
4156   if (NeedTrunc)
4157     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4158   return ResultReg;
4159 }
4160 
4161 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4162                                      bool Op0IsKill, uint64_t Shift,
4163                                      bool IsZExt) {
4164   assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4165          "Unexpected source/return type pair.");
4166   assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4167           SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4168          "Unexpected source value type.");
4169   assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4170           RetVT == MVT::i64) && "Unexpected return value type.");
4171 
4172   bool Is64Bit = (RetVT == MVT::i64);
4173   unsigned RegSize = Is64Bit ? 64 : 32;
4174   unsigned DstBits = RetVT.getSizeInBits();
4175   unsigned SrcBits = SrcVT.getSizeInBits();
4176   const TargetRegisterClass *RC =
4177       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4178 
4179   // Just emit a copy for "zero" shifts.
4180   if (Shift == 0) {
4181     if (RetVT == SrcVT) {
4182       unsigned ResultReg = createResultReg(RC);
4183       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4184               TII.get(TargetOpcode::COPY), ResultReg)
4185       .addReg(Op0, getKillRegState(Op0IsKill));
4186       return ResultReg;
4187     } else
4188       return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4189   }
4190 
4191   // Don't deal with undefined shifts.
4192   if (Shift >= DstBits)
4193     return 0;
4194 
4195   // For immediate shifts we can fold the zero-/sign-extension into the shift.
4196   // {S|U}BFM Wd, Wn, #r, #s
4197   // Wd<s-r:0> = Wn<s:r> when r <= s
4198 
4199   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4200   // %2 = ashr i16 %1, 4
4201   // Wd<7-4:0> = Wn<7:4>
4202   // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
4203   // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4204   // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4205 
4206   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4207   // %2 = ashr i16 %1, 8
4208   // Wd<7-7,0> = Wn<7:7>
4209   // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4210   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4211   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4212 
4213   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4214   // %2 = ashr i16 %1, 12
4215   // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4216   // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4217   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4218   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4219 
4220   if (Shift >= SrcBits && IsZExt)
4221     return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4222 
4223   unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4224   unsigned ImmS = SrcBits - 1;
4225   static const unsigned OpcTable[2][2] = {
4226     {AArch64::SBFMWri, AArch64::SBFMXri},
4227     {AArch64::UBFMWri, AArch64::UBFMXri}
4228   };
4229   unsigned Opc = OpcTable[IsZExt][Is64Bit];
4230   if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4231     unsigned TmpReg = MRI.createVirtualRegister(RC);
4232     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4233             TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4234         .addImm(0)
4235         .addReg(Op0, getKillRegState(Op0IsKill))
4236         .addImm(AArch64::sub_32);
4237     Op0 = TmpReg;
4238     Op0IsKill = true;
4239   }
4240   return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4241 }
4242 
4243 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
4244                                      bool IsZExt) {
4245   assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
4246 
4247   // FastISel does not have plumbing to deal with extensions where the SrcVT or
4248   // DestVT are odd things, so test to make sure that they are both types we can
4249   // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
4250   // bail out to SelectionDAG.
4251   if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
4252        (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
4253       ((SrcVT !=  MVT::i1) && (SrcVT !=  MVT::i8) &&
4254        (SrcVT !=  MVT::i16) && (SrcVT !=  MVT::i32)))
4255     return 0;
4256 
4257   unsigned Opc;
4258   unsigned Imm = 0;
4259 
4260   switch (SrcVT.SimpleTy) {
4261   default:
4262     return 0;
4263   case MVT::i1:
4264     return emiti1Ext(SrcReg, DestVT, IsZExt);
4265   case MVT::i8:
4266     if (DestVT == MVT::i64)
4267       Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4268     else
4269       Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4270     Imm = 7;
4271     break;
4272   case MVT::i16:
4273     if (DestVT == MVT::i64)
4274       Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4275     else
4276       Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4277     Imm = 15;
4278     break;
4279   case MVT::i32:
4280     assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
4281     Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4282     Imm = 31;
4283     break;
4284   }
4285 
4286   // Handle i8 and i16 as i32.
4287   if (DestVT == MVT::i8 || DestVT == MVT::i16)
4288     DestVT = MVT::i32;
4289   else if (DestVT == MVT::i64) {
4290     unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4291     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4292             TII.get(AArch64::SUBREG_TO_REG), Src64)
4293         .addImm(0)
4294         .addReg(SrcReg)
4295         .addImm(AArch64::sub_32);
4296     SrcReg = Src64;
4297   }
4298 
4299   const TargetRegisterClass *RC =
4300       (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4301   return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
4302 }
4303 
4304 static bool isZExtLoad(const MachineInstr *LI) {
4305   switch (LI->getOpcode()) {
4306   default:
4307     return false;
4308   case AArch64::LDURBBi:
4309   case AArch64::LDURHHi:
4310   case AArch64::LDURWi:
4311   case AArch64::LDRBBui:
4312   case AArch64::LDRHHui:
4313   case AArch64::LDRWui:
4314   case AArch64::LDRBBroX:
4315   case AArch64::LDRHHroX:
4316   case AArch64::LDRWroX:
4317   case AArch64::LDRBBroW:
4318   case AArch64::LDRHHroW:
4319   case AArch64::LDRWroW:
4320     return true;
4321   }
4322 }
4323 
4324 static bool isSExtLoad(const MachineInstr *LI) {
4325   switch (LI->getOpcode()) {
4326   default:
4327     return false;
4328   case AArch64::LDURSBWi:
4329   case AArch64::LDURSHWi:
4330   case AArch64::LDURSBXi:
4331   case AArch64::LDURSHXi:
4332   case AArch64::LDURSWi:
4333   case AArch64::LDRSBWui:
4334   case AArch64::LDRSHWui:
4335   case AArch64::LDRSBXui:
4336   case AArch64::LDRSHXui:
4337   case AArch64::LDRSWui:
4338   case AArch64::LDRSBWroX:
4339   case AArch64::LDRSHWroX:
4340   case AArch64::LDRSBXroX:
4341   case AArch64::LDRSHXroX:
4342   case AArch64::LDRSWroX:
4343   case AArch64::LDRSBWroW:
4344   case AArch64::LDRSHWroW:
4345   case AArch64::LDRSBXroW:
4346   case AArch64::LDRSHXroW:
4347   case AArch64::LDRSWroW:
4348     return true;
4349   }
4350 }
4351 
4352 bool AArch64FastISel::optimizeIntExtLoad(const Instruction *I, MVT RetVT,
4353                                          MVT SrcVT) {
4354   const auto *LI = dyn_cast<LoadInst>(I->getOperand(0));
4355   if (!LI || !LI->hasOneUse())
4356     return false;
4357 
4358   // Check if the load instruction has already been selected.
4359   unsigned Reg = lookUpRegForValue(LI);
4360   if (!Reg)
4361     return false;
4362 
4363   MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
4364   if (!MI)
4365     return false;
4366 
4367   // Check if the correct load instruction has been emitted - SelectionDAG might
4368   // have emitted a zero-extending load, but we need a sign-extending load.
4369   bool IsZExt = isa<ZExtInst>(I);
4370   const auto *LoadMI = MI;
4371   if (LoadMI->getOpcode() == TargetOpcode::COPY &&
4372       LoadMI->getOperand(1).getSubReg() == AArch64::sub_32) {
4373     unsigned LoadReg = MI->getOperand(1).getReg();
4374     LoadMI = MRI.getUniqueVRegDef(LoadReg);
4375     assert(LoadMI && "Expected valid instruction");
4376   }
4377   if (!(IsZExt && isZExtLoad(LoadMI)) && !(!IsZExt && isSExtLoad(LoadMI)))
4378     return false;
4379 
4380   // Nothing to be done.
4381   if (RetVT != MVT::i64 || SrcVT > MVT::i32) {
4382     updateValueMap(I, Reg);
4383     return true;
4384   }
4385 
4386   if (IsZExt) {
4387     unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
4388     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4389             TII.get(AArch64::SUBREG_TO_REG), Reg64)
4390         .addImm(0)
4391         .addReg(Reg, getKillRegState(true))
4392         .addImm(AArch64::sub_32);
4393     Reg = Reg64;
4394   } else {
4395     assert((MI->getOpcode() == TargetOpcode::COPY &&
4396             MI->getOperand(1).getSubReg() == AArch64::sub_32) &&
4397            "Expected copy instruction");
4398     Reg = MI->getOperand(1).getReg();
4399     MI->eraseFromParent();
4400   }
4401   updateValueMap(I, Reg);
4402   return true;
4403 }
4404 
4405 bool AArch64FastISel::selectIntExt(const Instruction *I) {
4406   assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
4407          "Unexpected integer extend instruction.");
4408   MVT RetVT;
4409   MVT SrcVT;
4410   if (!isTypeSupported(I->getType(), RetVT))
4411     return false;
4412 
4413   if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
4414     return false;
4415 
4416   // Try to optimize already sign-/zero-extended values from load instructions.
4417   if (optimizeIntExtLoad(I, RetVT, SrcVT))
4418     return true;
4419 
4420   unsigned SrcReg = getRegForValue(I->getOperand(0));
4421   if (!SrcReg)
4422     return false;
4423   bool SrcIsKill = hasTrivialKill(I->getOperand(0));
4424 
4425   // Try to optimize already sign-/zero-extended values from function arguments.
4426   bool IsZExt = isa<ZExtInst>(I);
4427   if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0))) {
4428     if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
4429       if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
4430         unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
4431         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4432                 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
4433             .addImm(0)
4434             .addReg(SrcReg, getKillRegState(SrcIsKill))
4435             .addImm(AArch64::sub_32);
4436         SrcReg = ResultReg;
4437       }
4438       // Conservatively clear all kill flags from all uses, because we are
4439       // replacing a sign-/zero-extend instruction at IR level with a nop at MI
4440       // level. The result of the instruction at IR level might have been
4441       // trivially dead, which is now not longer true.
4442       unsigned UseReg = lookUpRegForValue(I);
4443       if (UseReg)
4444         MRI.clearKillFlags(UseReg);
4445 
4446       updateValueMap(I, SrcReg);
4447       return true;
4448     }
4449   }
4450 
4451   unsigned ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, IsZExt);
4452   if (!ResultReg)
4453     return false;
4454 
4455   updateValueMap(I, ResultReg);
4456   return true;
4457 }
4458 
4459 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
4460   EVT DestEVT = TLI.getValueType(DL, I->getType(), true);
4461   if (!DestEVT.isSimple())
4462     return false;
4463 
4464   MVT DestVT = DestEVT.getSimpleVT();
4465   if (DestVT != MVT::i64 && DestVT != MVT::i32)
4466     return false;
4467 
4468   unsigned DivOpc;
4469   bool Is64bit = (DestVT == MVT::i64);
4470   switch (ISDOpcode) {
4471   default:
4472     return false;
4473   case ISD::SREM:
4474     DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
4475     break;
4476   case ISD::UREM:
4477     DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
4478     break;
4479   }
4480   unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
4481   unsigned Src0Reg = getRegForValue(I->getOperand(0));
4482   if (!Src0Reg)
4483     return false;
4484   bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4485 
4486   unsigned Src1Reg = getRegForValue(I->getOperand(1));
4487   if (!Src1Reg)
4488     return false;
4489   bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4490 
4491   const TargetRegisterClass *RC =
4492       (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4493   unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4494                                      Src1Reg, /*IsKill=*/false);
4495   assert(QuotReg && "Unexpected DIV instruction emission failure.");
4496   // The remainder is computed as numerator - (quotient * denominator) using the
4497   // MSUB instruction.
4498   unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4499                                         Src1Reg, Src1IsKill, Src0Reg,
4500                                         Src0IsKill);
4501   updateValueMap(I, ResultReg);
4502   return true;
4503 }
4504 
4505 bool AArch64FastISel::selectMul(const Instruction *I) {
4506   MVT VT;
4507   if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4508     return false;
4509 
4510   if (VT.isVector())
4511     return selectBinaryOp(I, ISD::MUL);
4512 
4513   const Value *Src0 = I->getOperand(0);
4514   const Value *Src1 = I->getOperand(1);
4515   if (const auto *C = dyn_cast<ConstantInt>(Src0))
4516     if (C->getValue().isPowerOf2())
4517       std::swap(Src0, Src1);
4518 
4519   // Try to simplify to a shift instruction.
4520   if (const auto *C = dyn_cast<ConstantInt>(Src1))
4521     if (C->getValue().isPowerOf2()) {
4522       uint64_t ShiftVal = C->getValue().logBase2();
4523       MVT SrcVT = VT;
4524       bool IsZExt = true;
4525       if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4526         if (!isIntExtFree(ZExt)) {
4527           MVT VT;
4528           if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4529             SrcVT = VT;
4530             IsZExt = true;
4531             Src0 = ZExt->getOperand(0);
4532           }
4533         }
4534       } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4535         if (!isIntExtFree(SExt)) {
4536           MVT VT;
4537           if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4538             SrcVT = VT;
4539             IsZExt = false;
4540             Src0 = SExt->getOperand(0);
4541           }
4542         }
4543       }
4544 
4545       unsigned Src0Reg = getRegForValue(Src0);
4546       if (!Src0Reg)
4547         return false;
4548       bool Src0IsKill = hasTrivialKill(Src0);
4549 
4550       unsigned ResultReg =
4551           emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4552 
4553       if (ResultReg) {
4554         updateValueMap(I, ResultReg);
4555         return true;
4556       }
4557     }
4558 
4559   unsigned Src0Reg = getRegForValue(I->getOperand(0));
4560   if (!Src0Reg)
4561     return false;
4562   bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4563 
4564   unsigned Src1Reg = getRegForValue(I->getOperand(1));
4565   if (!Src1Reg)
4566     return false;
4567   bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4568 
4569   unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4570 
4571   if (!ResultReg)
4572     return false;
4573 
4574   updateValueMap(I, ResultReg);
4575   return true;
4576 }
4577 
4578 bool AArch64FastISel::selectShift(const Instruction *I) {
4579   MVT RetVT;
4580   if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4581     return false;
4582 
4583   if (RetVT.isVector())
4584     return selectOperator(I, I->getOpcode());
4585 
4586   if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4587     unsigned ResultReg = 0;
4588     uint64_t ShiftVal = C->getZExtValue();
4589     MVT SrcVT = RetVT;
4590     bool IsZExt = I->getOpcode() != Instruction::AShr;
4591     const Value *Op0 = I->getOperand(0);
4592     if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4593       if (!isIntExtFree(ZExt)) {
4594         MVT TmpVT;
4595         if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4596           SrcVT = TmpVT;
4597           IsZExt = true;
4598           Op0 = ZExt->getOperand(0);
4599         }
4600       }
4601     } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4602       if (!isIntExtFree(SExt)) {
4603         MVT TmpVT;
4604         if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4605           SrcVT = TmpVT;
4606           IsZExt = false;
4607           Op0 = SExt->getOperand(0);
4608         }
4609       }
4610     }
4611 
4612     unsigned Op0Reg = getRegForValue(Op0);
4613     if (!Op0Reg)
4614       return false;
4615     bool Op0IsKill = hasTrivialKill(Op0);
4616 
4617     switch (I->getOpcode()) {
4618     default: llvm_unreachable("Unexpected instruction.");
4619     case Instruction::Shl:
4620       ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4621       break;
4622     case Instruction::AShr:
4623       ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4624       break;
4625     case Instruction::LShr:
4626       ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4627       break;
4628     }
4629     if (!ResultReg)
4630       return false;
4631 
4632     updateValueMap(I, ResultReg);
4633     return true;
4634   }
4635 
4636   unsigned Op0Reg = getRegForValue(I->getOperand(0));
4637   if (!Op0Reg)
4638     return false;
4639   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4640 
4641   unsigned Op1Reg = getRegForValue(I->getOperand(1));
4642   if (!Op1Reg)
4643     return false;
4644   bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4645 
4646   unsigned ResultReg = 0;
4647   switch (I->getOpcode()) {
4648   default: llvm_unreachable("Unexpected instruction.");
4649   case Instruction::Shl:
4650     ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4651     break;
4652   case Instruction::AShr:
4653     ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4654     break;
4655   case Instruction::LShr:
4656     ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4657     break;
4658   }
4659 
4660   if (!ResultReg)
4661     return false;
4662 
4663   updateValueMap(I, ResultReg);
4664   return true;
4665 }
4666 
4667 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4668   MVT RetVT, SrcVT;
4669 
4670   if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4671     return false;
4672   if (!isTypeLegal(I->getType(), RetVT))
4673     return false;
4674 
4675   unsigned Opc;
4676   if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4677     Opc = AArch64::FMOVWSr;
4678   else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4679     Opc = AArch64::FMOVXDr;
4680   else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4681     Opc = AArch64::FMOVSWr;
4682   else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4683     Opc = AArch64::FMOVDXr;
4684   else
4685     return false;
4686 
4687   const TargetRegisterClass *RC = nullptr;
4688   switch (RetVT.SimpleTy) {
4689   default: llvm_unreachable("Unexpected value type.");
4690   case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4691   case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4692   case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4693   case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4694   }
4695   unsigned Op0Reg = getRegForValue(I->getOperand(0));
4696   if (!Op0Reg)
4697     return false;
4698   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4699   unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4700 
4701   if (!ResultReg)
4702     return false;
4703 
4704   updateValueMap(I, ResultReg);
4705   return true;
4706 }
4707 
4708 bool AArch64FastISel::selectFRem(const Instruction *I) {
4709   MVT RetVT;
4710   if (!isTypeLegal(I->getType(), RetVT))
4711     return false;
4712 
4713   RTLIB::Libcall LC;
4714   switch (RetVT.SimpleTy) {
4715   default:
4716     return false;
4717   case MVT::f32:
4718     LC = RTLIB::REM_F32;
4719     break;
4720   case MVT::f64:
4721     LC = RTLIB::REM_F64;
4722     break;
4723   }
4724 
4725   ArgListTy Args;
4726   Args.reserve(I->getNumOperands());
4727 
4728   // Populate the argument list.
4729   for (auto &Arg : I->operands()) {
4730     ArgListEntry Entry;
4731     Entry.Val = Arg;
4732     Entry.Ty = Arg->getType();
4733     Args.push_back(Entry);
4734   }
4735 
4736   CallLoweringInfo CLI;
4737   MCContext &Ctx = MF->getContext();
4738   CLI.setCallee(DL, Ctx, TLI.getLibcallCallingConv(LC), I->getType(),
4739                 TLI.getLibcallName(LC), std::move(Args));
4740   if (!lowerCallTo(CLI))
4741     return false;
4742   updateValueMap(I, CLI.ResultReg);
4743   return true;
4744 }
4745 
4746 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4747   MVT VT;
4748   if (!isTypeLegal(I->getType(), VT))
4749     return false;
4750 
4751   if (!isa<ConstantInt>(I->getOperand(1)))
4752     return selectBinaryOp(I, ISD::SDIV);
4753 
4754   const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4755   if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4756       !(C.isPowerOf2() || (-C).isPowerOf2()))
4757     return selectBinaryOp(I, ISD::SDIV);
4758 
4759   unsigned Lg2 = C.countTrailingZeros();
4760   unsigned Src0Reg = getRegForValue(I->getOperand(0));
4761   if (!Src0Reg)
4762     return false;
4763   bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4764 
4765   if (cast<BinaryOperator>(I)->isExact()) {
4766     unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4767     if (!ResultReg)
4768       return false;
4769     updateValueMap(I, ResultReg);
4770     return true;
4771   }
4772 
4773   int64_t Pow2MinusOne = (1ULL << Lg2) - 1;
4774   unsigned AddReg = emitAdd_ri_(VT, Src0Reg, /*IsKill=*/false, Pow2MinusOne);
4775   if (!AddReg)
4776     return false;
4777 
4778   // (Src0 < 0) ? Pow2 - 1 : 0;
4779   if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4780     return false;
4781 
4782   unsigned SelectOpc;
4783   const TargetRegisterClass *RC;
4784   if (VT == MVT::i64) {
4785     SelectOpc = AArch64::CSELXr;
4786     RC = &AArch64::GPR64RegClass;
4787   } else {
4788     SelectOpc = AArch64::CSELWr;
4789     RC = &AArch64::GPR32RegClass;
4790   }
4791   unsigned SelectReg =
4792       fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4793                        Src0IsKill, AArch64CC::LT);
4794   if (!SelectReg)
4795     return false;
4796 
4797   // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4798   // negate the result.
4799   unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4800   unsigned ResultReg;
4801   if (C.isNegative())
4802     ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4803                               SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4804   else
4805     ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4806 
4807   if (!ResultReg)
4808     return false;
4809 
4810   updateValueMap(I, ResultReg);
4811   return true;
4812 }
4813 
4814 /// This is mostly a copy of the existing FastISel getRegForGEPIndex code. We
4815 /// have to duplicate it for AArch64, because otherwise we would fail during the
4816 /// sign-extend emission.
4817 std::pair<unsigned, bool> AArch64FastISel::getRegForGEPIndex(const Value *Idx) {
4818   unsigned IdxN = getRegForValue(Idx);
4819   if (IdxN == 0)
4820     // Unhandled operand. Halt "fast" selection and bail.
4821     return std::pair<unsigned, bool>(0, false);
4822 
4823   bool IdxNIsKill = hasTrivialKill(Idx);
4824 
4825   // If the index is smaller or larger than intptr_t, truncate or extend it.
4826   MVT PtrVT = TLI.getPointerTy(DL);
4827   EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
4828   if (IdxVT.bitsLT(PtrVT)) {
4829     IdxN = emitIntExt(IdxVT.getSimpleVT(), IdxN, PtrVT, /*IsZExt=*/false);
4830     IdxNIsKill = true;
4831   } else if (IdxVT.bitsGT(PtrVT))
4832     llvm_unreachable("AArch64 FastISel doesn't support types larger than i64");
4833   return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
4834 }
4835 
4836 /// This is mostly a copy of the existing FastISel GEP code, but we have to
4837 /// duplicate it for AArch64, because otherwise we would bail out even for
4838 /// simple cases. This is because the standard fastEmit functions don't cover
4839 /// MUL at all and ADD is lowered very inefficientily.
4840 bool AArch64FastISel::selectGetElementPtr(const Instruction *I) {
4841   unsigned N = getRegForValue(I->getOperand(0));
4842   if (!N)
4843     return false;
4844   bool NIsKill = hasTrivialKill(I->getOperand(0));
4845 
4846   // Keep a running tab of the total offset to coalesce multiple N = N + Offset
4847   // into a single N = N + TotalOffset.
4848   uint64_t TotalOffs = 0;
4849   MVT VT = TLI.getPointerTy(DL);
4850   for (gep_type_iterator GTI = gep_type_begin(I), E = gep_type_end(I);
4851        GTI != E; ++GTI) {
4852     const Value *Idx = GTI.getOperand();
4853     if (auto *StTy = dyn_cast<StructType>(*GTI)) {
4854       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
4855       // N = N + Offset
4856       if (Field)
4857         TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
4858     } else {
4859       Type *Ty = GTI.getIndexedType();
4860 
4861       // If this is a constant subscript, handle it quickly.
4862       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
4863         if (CI->isZero())
4864           continue;
4865         // N = N + Offset
4866         TotalOffs +=
4867             DL.getTypeAllocSize(Ty) * cast<ConstantInt>(CI)->getSExtValue();
4868         continue;
4869       }
4870       if (TotalOffs) {
4871         N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4872         if (!N)
4873           return false;
4874         NIsKill = true;
4875         TotalOffs = 0;
4876       }
4877 
4878       // N = N + Idx * ElementSize;
4879       uint64_t ElementSize = DL.getTypeAllocSize(Ty);
4880       std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
4881       unsigned IdxN = Pair.first;
4882       bool IdxNIsKill = Pair.second;
4883       if (!IdxN)
4884         return false;
4885 
4886       if (ElementSize != 1) {
4887         unsigned C = fastEmit_i(VT, VT, ISD::Constant, ElementSize);
4888         if (!C)
4889           return false;
4890         IdxN = emitMul_rr(VT, IdxN, IdxNIsKill, C, true);
4891         if (!IdxN)
4892           return false;
4893         IdxNIsKill = true;
4894       }
4895       N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
4896       if (!N)
4897         return false;
4898     }
4899   }
4900   if (TotalOffs) {
4901     N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4902     if (!N)
4903       return false;
4904   }
4905   updateValueMap(I, N);
4906   return true;
4907 }
4908 
4909 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4910   switch (I->getOpcode()) {
4911   default:
4912     break;
4913   case Instruction::Add:
4914   case Instruction::Sub:
4915     return selectAddSub(I);
4916   case Instruction::Mul:
4917     return selectMul(I);
4918   case Instruction::SDiv:
4919     return selectSDiv(I);
4920   case Instruction::SRem:
4921     if (!selectBinaryOp(I, ISD::SREM))
4922       return selectRem(I, ISD::SREM);
4923     return true;
4924   case Instruction::URem:
4925     if (!selectBinaryOp(I, ISD::UREM))
4926       return selectRem(I, ISD::UREM);
4927     return true;
4928   case Instruction::Shl:
4929   case Instruction::LShr:
4930   case Instruction::AShr:
4931     return selectShift(I);
4932   case Instruction::And:
4933   case Instruction::Or:
4934   case Instruction::Xor:
4935     return selectLogicalOp(I);
4936   case Instruction::Br:
4937     return selectBranch(I);
4938   case Instruction::IndirectBr:
4939     return selectIndirectBr(I);
4940   case Instruction::BitCast:
4941     if (!FastISel::selectBitCast(I))
4942       return selectBitCast(I);
4943     return true;
4944   case Instruction::FPToSI:
4945     if (!selectCast(I, ISD::FP_TO_SINT))
4946       return selectFPToInt(I, /*Signed=*/true);
4947     return true;
4948   case Instruction::FPToUI:
4949     return selectFPToInt(I, /*Signed=*/false);
4950   case Instruction::ZExt:
4951   case Instruction::SExt:
4952     return selectIntExt(I);
4953   case Instruction::Trunc:
4954     if (!selectCast(I, ISD::TRUNCATE))
4955       return selectTrunc(I);
4956     return true;
4957   case Instruction::FPExt:
4958     return selectFPExt(I);
4959   case Instruction::FPTrunc:
4960     return selectFPTrunc(I);
4961   case Instruction::SIToFP:
4962     if (!selectCast(I, ISD::SINT_TO_FP))
4963       return selectIntToFP(I, /*Signed=*/true);
4964     return true;
4965   case Instruction::UIToFP:
4966     return selectIntToFP(I, /*Signed=*/false);
4967   case Instruction::Load:
4968     return selectLoad(I);
4969   case Instruction::Store:
4970     return selectStore(I);
4971   case Instruction::FCmp:
4972   case Instruction::ICmp:
4973     return selectCmp(I);
4974   case Instruction::Select:
4975     return selectSelect(I);
4976   case Instruction::Ret:
4977     return selectRet(I);
4978   case Instruction::FRem:
4979     return selectFRem(I);
4980   case Instruction::GetElementPtr:
4981     return selectGetElementPtr(I);
4982   }
4983 
4984   // fall-back to target-independent instruction selection.
4985   return selectOperator(I, I->getOpcode());
4986   // Silence warnings.
4987   (void)&CC_AArch64_DarwinPCS_VarArg;
4988 }
4989 
4990 namespace llvm {
4991 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4992                                         const TargetLibraryInfo *LibInfo) {
4993   return new AArch64FastISel(FuncInfo, LibInfo);
4994 }
4995 }
4996