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