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