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