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