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