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