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