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