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