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