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