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