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