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