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