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