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