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