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