AArch64/ARM64: move ARM64 into AArch64's place
[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 "AArch64TargetMachine.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64CallingConv.h"
20 #include "MCTargetDesc/AArch64AddressingModes.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
60   public:
61     Address() : Kind(RegBase), Offset(0) { Base.Reg = 0; }
62     void setKind(BaseKind K) { Kind = K; }
63     BaseKind getKind() const { return Kind; }
64     bool isRegBase() const { return Kind == RegBase; }
65     bool isFIBase() const { return Kind == FrameIndexBase; }
66     void setReg(unsigned Reg) {
67       assert(isRegBase() && "Invalid base register access!");
68       Base.Reg = Reg;
69     }
70     unsigned getReg() const {
71       assert(isRegBase() && "Invalid base register access!");
72       return Base.Reg;
73     }
74     void setFI(unsigned FI) {
75       assert(isFIBase() && "Invalid base frame index  access!");
76       Base.FI = FI;
77     }
78     unsigned getFI() const {
79       assert(isFIBase() && "Invalid base frame index access!");
80       return Base.FI;
81     }
82     void setOffset(int64_t O) { Offset = O; }
83     int64_t getOffset() { return Offset; }
84
85     bool isValid() { return isFIBase() || (isRegBase() && getReg() != 0); }
86   };
87
88   /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
89   /// make the right decision when generating code for different targets.
90   const AArch64Subtarget *Subtarget;
91   LLVMContext *Context;
92
93 private:
94   // Selection routines.
95   bool SelectLoad(const Instruction *I);
96   bool SelectStore(const Instruction *I);
97   bool SelectBranch(const Instruction *I);
98   bool SelectIndirectBr(const Instruction *I);
99   bool SelectCmp(const Instruction *I);
100   bool SelectSelect(const Instruction *I);
101   bool SelectFPExt(const Instruction *I);
102   bool SelectFPTrunc(const Instruction *I);
103   bool SelectFPToInt(const Instruction *I, bool Signed);
104   bool SelectIntToFP(const Instruction *I, bool Signed);
105   bool SelectRem(const Instruction *I, unsigned ISDOpcode);
106   bool SelectCall(const Instruction *I, const char *IntrMemName);
107   bool SelectIntrinsicCall(const IntrinsicInst &I);
108   bool SelectRet(const Instruction *I);
109   bool SelectTrunc(const Instruction *I);
110   bool SelectIntExt(const Instruction *I);
111   bool SelectMul(const Instruction *I);
112
113   // Utility helper routines.
114   bool isTypeLegal(Type *Ty, MVT &VT);
115   bool isLoadStoreTypeLegal(Type *Ty, MVT &VT);
116   bool ComputeAddress(const Value *Obj, Address &Addr);
117   bool SimplifyAddress(Address &Addr, MVT VT, int64_t ScaleFactor,
118                        bool UseUnscaled);
119   void AddLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
120                             unsigned Flags, bool UseUnscaled);
121   bool IsMemCpySmall(uint64_t Len, unsigned Alignment);
122   bool TryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
123                           unsigned Alignment);
124   // Emit functions.
125   bool EmitCmp(Value *Src1Value, Value *Src2Value, bool isZExt);
126   bool EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
127                 bool UseUnscaled = false);
128   bool EmitStore(MVT VT, unsigned SrcReg, Address Addr,
129                  bool UseUnscaled = false);
130   unsigned EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
131   unsigned Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
132
133   unsigned AArch64MaterializeFP(const ConstantFP *CFP, MVT VT);
134   unsigned AArch64MaterializeGV(const GlobalValue *GV);
135
136   // Call handling routines.
137 private:
138   CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
139   bool ProcessCallArgs(SmallVectorImpl<Value *> &Args,
140                        SmallVectorImpl<unsigned> &ArgRegs,
141                        SmallVectorImpl<MVT> &ArgVTs,
142                        SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
143                        SmallVectorImpl<unsigned> &RegArgs, CallingConv::ID CC,
144                        unsigned &NumBytes);
145   bool FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
146                   const Instruction *I, CallingConv::ID CC, unsigned &NumBytes);
147
148 public:
149   // Backend specific FastISel code.
150   unsigned TargetMaterializeAlloca(const AllocaInst *AI) override;
151   unsigned TargetMaterializeConstant(const Constant *C) override;
152
153   explicit AArch64FastISel(FunctionLoweringInfo &funcInfo,
154                          const TargetLibraryInfo *libInfo)
155       : FastISel(funcInfo, libInfo) {
156     Subtarget = &TM.getSubtarget<AArch64Subtarget>();
157     Context = &funcInfo.Fn->getContext();
158   }
159
160   bool TargetSelectInstruction(const Instruction *I) override;
161
162 #include "AArch64GenFastISel.inc"
163 };
164
165 } // end anonymous namespace
166
167 #include "AArch64GenCallingConv.inc"
168
169 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
170   if (CC == CallingConv::WebKit_JS)
171     return CC_AArch64_WebKit_JS;
172   return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
173 }
174
175 unsigned AArch64FastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
176   assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
177          "Alloca should always return a pointer.");
178
179   // Don't handle dynamic allocas.
180   if (!FuncInfo.StaticAllocaMap.count(AI))
181     return 0;
182
183   DenseMap<const AllocaInst *, int>::iterator SI =
184       FuncInfo.StaticAllocaMap.find(AI);
185
186   if (SI != FuncInfo.StaticAllocaMap.end()) {
187     unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
188     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
189             ResultReg)
190         .addFrameIndex(SI->second)
191         .addImm(0)
192         .addImm(0);
193     return ResultReg;
194   }
195
196   return 0;
197 }
198
199 unsigned AArch64FastISel::AArch64MaterializeFP(const ConstantFP *CFP, MVT VT) {
200   if (VT != MVT::f32 && VT != MVT::f64)
201     return 0;
202
203   const APFloat Val = CFP->getValueAPF();
204   bool is64bit = (VT == MVT::f64);
205
206   // This checks to see if we can use FMOV instructions to materialize
207   // a constant, otherwise we have to materialize via the constant pool.
208   if (TLI.isFPImmLegal(Val, VT)) {
209     int Imm;
210     unsigned Opc;
211     if (is64bit) {
212       Imm = AArch64_AM::getFP64Imm(Val);
213       Opc = AArch64::FMOVDi;
214     } else {
215       Imm = AArch64_AM::getFP32Imm(Val);
216       Opc = AArch64::FMOVSi;
217     }
218     unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
219     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
220         .addImm(Imm);
221     return ResultReg;
222   }
223
224   // Materialize via constant pool.  MachineConstantPool wants an explicit
225   // alignment.
226   unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
227   if (Align == 0)
228     Align = DL.getTypeAllocSize(CFP->getType());
229
230   unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
231   unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
232   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
233           ADRPReg).addConstantPoolIndex(Idx, 0, AArch64II::MO_PAGE);
234
235   unsigned Opc = is64bit ? AArch64::LDRDui : AArch64::LDRSui;
236   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
237   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
238       .addReg(ADRPReg)
239       .addConstantPoolIndex(Idx, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
240   return ResultReg;
241 }
242
243 unsigned AArch64FastISel::AArch64MaterializeGV(const GlobalValue *GV) {
244   // We can't handle thread-local variables quickly yet. Unfortunately we have
245   // to peer through any aliases to find out if that rule applies.
246   const GlobalValue *TLSGV = GV;
247   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
248     TLSGV = GA->getAliasee();
249
250   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(TLSGV))
251     if (GVar->isThreadLocal())
252       return 0;
253
254   unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
255
256   EVT DestEVT = TLI.getValueType(GV->getType(), true);
257   if (!DestEVT.isSimple())
258     return 0;
259
260   unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
261   unsigned ResultReg;
262
263   if (OpFlags & AArch64II::MO_GOT) {
264     // ADRP + LDRX
265     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
266             ADRPReg)
267         .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
268
269     ResultReg = createResultReg(&AArch64::GPR64RegClass);
270     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
271             ResultReg)
272         .addReg(ADRPReg)
273         .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
274                           AArch64II::MO_NC);
275   } else {
276     // ADRP + ADDX
277     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
278             ADRPReg).addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
279
280     ResultReg = createResultReg(&AArch64::GPR64spRegClass);
281     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
282             ResultReg)
283         .addReg(ADRPReg)
284         .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
285         .addImm(0);
286   }
287   return ResultReg;
288 }
289
290 unsigned AArch64FastISel::TargetMaterializeConstant(const Constant *C) {
291   EVT CEVT = TLI.getValueType(C->getType(), true);
292
293   // Only handle simple types.
294   if (!CEVT.isSimple())
295     return 0;
296   MVT VT = CEVT.getSimpleVT();
297
298   // FIXME: Handle ConstantInt.
299   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
300     return AArch64MaterializeFP(CFP, VT);
301   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
302     return AArch64MaterializeGV(GV);
303
304   return 0;
305 }
306
307 // Computes the address to get to an object.
308 bool AArch64FastISel::ComputeAddress(const Value *Obj, Address &Addr) {
309   const User *U = nullptr;
310   unsigned Opcode = Instruction::UserOp1;
311   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
312     // Don't walk into other basic blocks unless the object is an alloca from
313     // another block, otherwise it may not have a virtual register assigned.
314     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
315         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
316       Opcode = I->getOpcode();
317       U = I;
318     }
319   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
320     Opcode = C->getOpcode();
321     U = C;
322   }
323
324   if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
325     if (Ty->getAddressSpace() > 255)
326       // Fast instruction selection doesn't support the special
327       // address spaces.
328       return false;
329
330   switch (Opcode) {
331   default:
332     break;
333   case Instruction::BitCast: {
334     // Look through bitcasts.
335     return ComputeAddress(U->getOperand(0), Addr);
336   }
337   case Instruction::IntToPtr: {
338     // Look past no-op inttoptrs.
339     if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
340       return ComputeAddress(U->getOperand(0), Addr);
341     break;
342   }
343   case Instruction::PtrToInt: {
344     // Look past no-op ptrtoints.
345     if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
346       return ComputeAddress(U->getOperand(0), Addr);
347     break;
348   }
349   case Instruction::GetElementPtr: {
350     Address SavedAddr = Addr;
351     uint64_t TmpOffset = Addr.getOffset();
352
353     // Iterate through the GEP folding the constants into offsets where
354     // we can.
355     gep_type_iterator GTI = gep_type_begin(U);
356     for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
357          ++i, ++GTI) {
358       const Value *Op = *i;
359       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
360         const StructLayout *SL = DL.getStructLayout(STy);
361         unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
362         TmpOffset += SL->getElementOffset(Idx);
363       } else {
364         uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
365         for (;;) {
366           if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
367             // Constant-offset addressing.
368             TmpOffset += CI->getSExtValue() * S;
369             break;
370           }
371           if (canFoldAddIntoGEP(U, Op)) {
372             // A compatible add with a constant operand. Fold the constant.
373             ConstantInt *CI =
374                 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
375             TmpOffset += CI->getSExtValue() * S;
376             // Iterate on the other operand.
377             Op = cast<AddOperator>(Op)->getOperand(0);
378             continue;
379           }
380           // Unsupported
381           goto unsupported_gep;
382         }
383       }
384     }
385
386     // Try to grab the base operand now.
387     Addr.setOffset(TmpOffset);
388     if (ComputeAddress(U->getOperand(0), Addr))
389       return true;
390
391     // We failed, restore everything and try the other options.
392     Addr = SavedAddr;
393
394   unsupported_gep:
395     break;
396   }
397   case Instruction::Alloca: {
398     const AllocaInst *AI = cast<AllocaInst>(Obj);
399     DenseMap<const AllocaInst *, int>::iterator SI =
400         FuncInfo.StaticAllocaMap.find(AI);
401     if (SI != FuncInfo.StaticAllocaMap.end()) {
402       Addr.setKind(Address::FrameIndexBase);
403       Addr.setFI(SI->second);
404       return true;
405     }
406     break;
407   }
408   }
409
410   // Try to get this in a register if nothing else has worked.
411   if (!Addr.isValid())
412     Addr.setReg(getRegForValue(Obj));
413   return Addr.isValid();
414 }
415
416 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
417   EVT evt = TLI.getValueType(Ty, true);
418
419   // Only handle simple types.
420   if (evt == MVT::Other || !evt.isSimple())
421     return false;
422   VT = evt.getSimpleVT();
423
424   // This is a legal type, but it's not something we handle in fast-isel.
425   if (VT == MVT::f128)
426     return false;
427
428   // Handle all other legal types, i.e. a register that will directly hold this
429   // value.
430   return TLI.isTypeLegal(VT);
431 }
432
433 bool AArch64FastISel::isLoadStoreTypeLegal(Type *Ty, MVT &VT) {
434   if (isTypeLegal(Ty, VT))
435     return true;
436
437   // If this is a type than can be sign or zero-extended to a basic operation
438   // go ahead and accept it now. For stores, this reflects truncation.
439   if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
440     return true;
441
442   return false;
443 }
444
445 bool AArch64FastISel::SimplifyAddress(Address &Addr, MVT VT,
446                                       int64_t ScaleFactor, bool UseUnscaled) {
447   bool needsLowering = false;
448   int64_t Offset = Addr.getOffset();
449   switch (VT.SimpleTy) {
450   default:
451     return false;
452   case MVT::i1:
453   case MVT::i8:
454   case MVT::i16:
455   case MVT::i32:
456   case MVT::i64:
457   case MVT::f32:
458   case MVT::f64:
459     if (!UseUnscaled)
460       // Using scaled, 12-bit, unsigned immediate offsets.
461       needsLowering = ((Offset & 0xfff) != Offset);
462     else
463       // Using unscaled, 9-bit, signed immediate offsets.
464       needsLowering = (Offset > 256 || Offset < -256);
465     break;
466   }
467
468   // FIXME: If this is a stack pointer and the offset needs to be simplified
469   // then put the alloca address into a register, set the base type back to
470   // register and continue. This should almost never happen.
471   if (needsLowering && Addr.getKind() == Address::FrameIndexBase) {
472     return false;
473   }
474
475   // Since the offset is too large for the load/store instruction get the
476   // reg+offset into a register.
477   if (needsLowering) {
478     uint64_t UnscaledOffset = Addr.getOffset() * ScaleFactor;
479     unsigned ResultReg = FastEmit_ri_(MVT::i64, ISD::ADD, Addr.getReg(), false,
480                                       UnscaledOffset, MVT::i64);
481     if (ResultReg == 0)
482       return false;
483     Addr.setReg(ResultReg);
484     Addr.setOffset(0);
485   }
486   return true;
487 }
488
489 void AArch64FastISel::AddLoadStoreOperands(Address &Addr,
490                                            const MachineInstrBuilder &MIB,
491                                            unsigned Flags, bool UseUnscaled) {
492   int64_t Offset = Addr.getOffset();
493   // Frame base works a bit differently. Handle it separately.
494   if (Addr.getKind() == Address::FrameIndexBase) {
495     int FI = Addr.getFI();
496     // FIXME: We shouldn't be using getObjectSize/getObjectAlignment.  The size
497     // and alignment should be based on the VT.
498     MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
499         MachinePointerInfo::getFixedStack(FI, Offset), Flags,
500         MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
501     // Now add the rest of the operands.
502     MIB.addFrameIndex(FI).addImm(Offset).addMemOperand(MMO);
503   } else {
504     // Now add the rest of the operands.
505     MIB.addReg(Addr.getReg());
506     MIB.addImm(Offset);
507   }
508 }
509
510 bool AArch64FastISel::EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
511                                bool UseUnscaled) {
512   // Negative offsets require unscaled, 9-bit, signed immediate offsets.
513   // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
514   if (!UseUnscaled && Addr.getOffset() < 0)
515     UseUnscaled = true;
516
517   unsigned Opc;
518   const TargetRegisterClass *RC;
519   bool VTIsi1 = false;
520   int64_t ScaleFactor = 0;
521   switch (VT.SimpleTy) {
522   default:
523     return false;
524   case MVT::i1:
525     VTIsi1 = true;
526   // Intentional fall-through.
527   case MVT::i8:
528     Opc = UseUnscaled ? AArch64::LDURBBi : AArch64::LDRBBui;
529     RC = &AArch64::GPR32RegClass;
530     ScaleFactor = 1;
531     break;
532   case MVT::i16:
533     Opc = UseUnscaled ? AArch64::LDURHHi : AArch64::LDRHHui;
534     RC = &AArch64::GPR32RegClass;
535     ScaleFactor = 2;
536     break;
537   case MVT::i32:
538     Opc = UseUnscaled ? AArch64::LDURWi : AArch64::LDRWui;
539     RC = &AArch64::GPR32RegClass;
540     ScaleFactor = 4;
541     break;
542   case MVT::i64:
543     Opc = UseUnscaled ? AArch64::LDURXi : AArch64::LDRXui;
544     RC = &AArch64::GPR64RegClass;
545     ScaleFactor = 8;
546     break;
547   case MVT::f32:
548     Opc = UseUnscaled ? AArch64::LDURSi : AArch64::LDRSui;
549     RC = TLI.getRegClassFor(VT);
550     ScaleFactor = 4;
551     break;
552   case MVT::f64:
553     Opc = UseUnscaled ? AArch64::LDURDi : AArch64::LDRDui;
554     RC = TLI.getRegClassFor(VT);
555     ScaleFactor = 8;
556     break;
557   }
558   // Scale the offset.
559   if (!UseUnscaled) {
560     int64_t Offset = Addr.getOffset();
561     if (Offset & (ScaleFactor - 1))
562       // Retry using an unscaled, 9-bit, signed immediate offset.
563       return EmitLoad(VT, ResultReg, Addr, /*UseUnscaled*/ true);
564
565     Addr.setOffset(Offset / ScaleFactor);
566   }
567
568   // Simplify this down to something we can handle.
569   if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
570     return false;
571
572   // Create the base instruction, then add the operands.
573   ResultReg = createResultReg(RC);
574   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
575                                     TII.get(Opc), ResultReg);
576   AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, UseUnscaled);
577
578   // Loading an i1 requires special handling.
579   if (VTIsi1) {
580     MRI.constrainRegClass(ResultReg, &AArch64::GPR32RegClass);
581     unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
582     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
583             ANDReg)
584         .addReg(ResultReg)
585         .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
586     ResultReg = ANDReg;
587   }
588   return true;
589 }
590
591 bool AArch64FastISel::SelectLoad(const Instruction *I) {
592   MVT VT;
593   // Verify we have a legal type before going any further.  Currently, we handle
594   // simple types that will directly fit in a register (i32/f32/i64/f64) or
595   // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
596   if (!isLoadStoreTypeLegal(I->getType(), VT) || cast<LoadInst>(I)->isAtomic())
597     return false;
598
599   // See if we can handle this address.
600   Address Addr;
601   if (!ComputeAddress(I->getOperand(0), Addr))
602     return false;
603
604   unsigned ResultReg;
605   if (!EmitLoad(VT, ResultReg, Addr))
606     return false;
607
608   UpdateValueMap(I, ResultReg);
609   return true;
610 }
611
612 bool AArch64FastISel::EmitStore(MVT VT, unsigned SrcReg, Address Addr,
613                                 bool UseUnscaled) {
614   // Negative offsets require unscaled, 9-bit, signed immediate offsets.
615   // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
616   if (!UseUnscaled && Addr.getOffset() < 0)
617     UseUnscaled = true;
618
619   unsigned StrOpc;
620   bool VTIsi1 = false;
621   int64_t ScaleFactor = 0;
622   // Using scaled, 12-bit, unsigned immediate offsets.
623   switch (VT.SimpleTy) {
624   default:
625     return false;
626   case MVT::i1:
627     VTIsi1 = true;
628   case MVT::i8:
629     StrOpc = UseUnscaled ? AArch64::STURBBi : AArch64::STRBBui;
630     ScaleFactor = 1;
631     break;
632   case MVT::i16:
633     StrOpc = UseUnscaled ? AArch64::STURHHi : AArch64::STRHHui;
634     ScaleFactor = 2;
635     break;
636   case MVT::i32:
637     StrOpc = UseUnscaled ? AArch64::STURWi : AArch64::STRWui;
638     ScaleFactor = 4;
639     break;
640   case MVT::i64:
641     StrOpc = UseUnscaled ? AArch64::STURXi : AArch64::STRXui;
642     ScaleFactor = 8;
643     break;
644   case MVT::f32:
645     StrOpc = UseUnscaled ? AArch64::STURSi : AArch64::STRSui;
646     ScaleFactor = 4;
647     break;
648   case MVT::f64:
649     StrOpc = UseUnscaled ? AArch64::STURDi : AArch64::STRDui;
650     ScaleFactor = 8;
651     break;
652   }
653   // Scale the offset.
654   if (!UseUnscaled) {
655     int64_t Offset = Addr.getOffset();
656     if (Offset & (ScaleFactor - 1))
657       // Retry using an unscaled, 9-bit, signed immediate offset.
658       return EmitStore(VT, SrcReg, Addr, /*UseUnscaled*/ true);
659
660     Addr.setOffset(Offset / ScaleFactor);
661   }
662
663   // Simplify this down to something we can handle.
664   if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
665     return false;
666
667   // Storing an i1 requires special handling.
668   if (VTIsi1) {
669     MRI.constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
670     unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
671     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
672             ANDReg)
673         .addReg(SrcReg)
674         .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
675     SrcReg = ANDReg;
676   }
677   // Create the base instruction, then add the operands.
678   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
679                                     TII.get(StrOpc)).addReg(SrcReg);
680   AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, UseUnscaled);
681   return true;
682 }
683
684 bool AArch64FastISel::SelectStore(const Instruction *I) {
685   MVT VT;
686   Value *Op0 = I->getOperand(0);
687   // Verify we have a legal type before going any further.  Currently, we handle
688   // simple types that will directly fit in a register (i32/f32/i64/f64) or
689   // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
690   if (!isLoadStoreTypeLegal(Op0->getType(), VT) ||
691       cast<StoreInst>(I)->isAtomic())
692     return false;
693
694   // Get the value to be stored into a register.
695   unsigned SrcReg = getRegForValue(Op0);
696   if (SrcReg == 0)
697     return false;
698
699   // See if we can handle this address.
700   Address Addr;
701   if (!ComputeAddress(I->getOperand(1), Addr))
702     return false;
703
704   if (!EmitStore(VT, SrcReg, Addr))
705     return false;
706   return true;
707 }
708
709 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
710   switch (Pred) {
711   case CmpInst::FCMP_ONE:
712   case CmpInst::FCMP_UEQ:
713   default:
714     // AL is our "false" for now. The other two need more compares.
715     return AArch64CC::AL;
716   case CmpInst::ICMP_EQ:
717   case CmpInst::FCMP_OEQ:
718     return AArch64CC::EQ;
719   case CmpInst::ICMP_SGT:
720   case CmpInst::FCMP_OGT:
721     return AArch64CC::GT;
722   case CmpInst::ICMP_SGE:
723   case CmpInst::FCMP_OGE:
724     return AArch64CC::GE;
725   case CmpInst::ICMP_UGT:
726   case CmpInst::FCMP_UGT:
727     return AArch64CC::HI;
728   case CmpInst::FCMP_OLT:
729     return AArch64CC::MI;
730   case CmpInst::ICMP_ULE:
731   case CmpInst::FCMP_OLE:
732     return AArch64CC::LS;
733   case CmpInst::FCMP_ORD:
734     return AArch64CC::VC;
735   case CmpInst::FCMP_UNO:
736     return AArch64CC::VS;
737   case CmpInst::FCMP_UGE:
738     return AArch64CC::PL;
739   case CmpInst::ICMP_SLT:
740   case CmpInst::FCMP_ULT:
741     return AArch64CC::LT;
742   case CmpInst::ICMP_SLE:
743   case CmpInst::FCMP_ULE:
744     return AArch64CC::LE;
745   case CmpInst::FCMP_UNE:
746   case CmpInst::ICMP_NE:
747     return AArch64CC::NE;
748   case CmpInst::ICMP_UGE:
749     return AArch64CC::HS;
750   case CmpInst::ICMP_ULT:
751     return AArch64CC::LO;
752   }
753 }
754
755 bool AArch64FastISel::SelectBranch(const Instruction *I) {
756   const BranchInst *BI = cast<BranchInst>(I);
757   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
758   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
759
760   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
761     if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
762       // We may not handle every CC for now.
763       AArch64CC::CondCode CC = getCompareCC(CI->getPredicate());
764       if (CC == AArch64CC::AL)
765         return false;
766
767       // Emit the cmp.
768       if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
769         return false;
770
771       // Emit the branch.
772       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
773           .addImm(CC)
774           .addMBB(TBB);
775       FuncInfo.MBB->addSuccessor(TBB);
776
777       FastEmitBranch(FBB, DbgLoc);
778       return true;
779     }
780   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
781     MVT SrcVT;
782     if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
783         (isLoadStoreTypeLegal(TI->getOperand(0)->getType(), SrcVT))) {
784       unsigned CondReg = getRegForValue(TI->getOperand(0));
785       if (CondReg == 0)
786         return false;
787
788       // Issue an extract_subreg to get the lower 32-bits.
789       if (SrcVT == MVT::i64)
790         CondReg = FastEmitInst_extractsubreg(MVT::i32, CondReg, /*Kill=*/true,
791                                              AArch64::sub_32);
792
793       MRI.constrainRegClass(CondReg, &AArch64::GPR32RegClass);
794       unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
795       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
796               TII.get(AArch64::ANDWri), ANDReg)
797           .addReg(CondReg)
798           .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
799       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
800               TII.get(AArch64::SUBSWri))
801           .addReg(ANDReg)
802           .addReg(ANDReg)
803           .addImm(0)
804           .addImm(0);
805
806       unsigned CC = AArch64CC::NE;
807       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
808         std::swap(TBB, FBB);
809         CC = AArch64CC::EQ;
810       }
811       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
812           .addImm(CC)
813           .addMBB(TBB);
814       FuncInfo.MBB->addSuccessor(TBB);
815       FastEmitBranch(FBB, DbgLoc);
816       return true;
817     }
818   } else if (const ConstantInt *CI =
819                  dyn_cast<ConstantInt>(BI->getCondition())) {
820     uint64_t Imm = CI->getZExtValue();
821     MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
822     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
823         .addMBB(Target);
824     FuncInfo.MBB->addSuccessor(Target);
825     return true;
826   }
827
828   unsigned CondReg = getRegForValue(BI->getCondition());
829   if (CondReg == 0)
830     return false;
831
832   // We've been divorced from our compare!  Our block was split, and
833   // now our compare lives in a predecessor block.  We musn't
834   // re-compare here, as the children of the compare aren't guaranteed
835   // live across the block boundary (we *could* check for this).
836   // Regardless, the compare has been done in the predecessor block,
837   // and it left a value for us in a virtual register.  Ergo, we test
838   // the one-bit value left in the virtual register.
839   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SUBSWri),
840           AArch64::WZR)
841       .addReg(CondReg)
842       .addImm(0)
843       .addImm(0);
844
845   unsigned CC = AArch64CC::NE;
846   if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
847     std::swap(TBB, FBB);
848     CC = AArch64CC::EQ;
849   }
850
851   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
852       .addImm(CC)
853       .addMBB(TBB);
854   FuncInfo.MBB->addSuccessor(TBB);
855   FastEmitBranch(FBB, DbgLoc);
856   return true;
857 }
858
859 bool AArch64FastISel::SelectIndirectBr(const Instruction *I) {
860   const IndirectBrInst *BI = cast<IndirectBrInst>(I);
861   unsigned AddrReg = getRegForValue(BI->getOperand(0));
862   if (AddrReg == 0)
863     return false;
864
865   // Emit the indirect branch.
866   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BR))
867       .addReg(AddrReg);
868
869   // Make sure the CFG is up-to-date.
870   for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
871     FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
872
873   return true;
874 }
875
876 bool AArch64FastISel::EmitCmp(Value *Src1Value, Value *Src2Value, bool isZExt) {
877   Type *Ty = Src1Value->getType();
878   EVT SrcEVT = TLI.getValueType(Ty, true);
879   if (!SrcEVT.isSimple())
880     return false;
881   MVT SrcVT = SrcEVT.getSimpleVT();
882
883   // Check to see if the 2nd operand is a constant that we can encode directly
884   // in the compare.
885   uint64_t Imm;
886   bool UseImm = false;
887   bool isNegativeImm = false;
888   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
889     if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
890         SrcVT == MVT::i8 || SrcVT == MVT::i1) {
891       const APInt &CIVal = ConstInt->getValue();
892
893       Imm = (isZExt) ? CIVal.getZExtValue() : CIVal.getSExtValue();
894       if (CIVal.isNegative()) {
895         isNegativeImm = true;
896         Imm = -Imm;
897       }
898       // FIXME: We can handle more immediates using shifts.
899       UseImm = ((Imm & 0xfff) == Imm);
900     }
901   } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
902     if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
903       if (ConstFP->isZero() && !ConstFP->isNegative())
904         UseImm = true;
905   }
906
907   unsigned ZReg;
908   unsigned CmpOpc;
909   bool isICmp = true;
910   bool needsExt = false;
911   switch (SrcVT.SimpleTy) {
912   default:
913     return false;
914   case MVT::i1:
915   case MVT::i8:
916   case MVT::i16:
917     needsExt = true;
918   // Intentional fall-through.
919   case MVT::i32:
920     ZReg = AArch64::WZR;
921     if (UseImm)
922       CmpOpc = isNegativeImm ? AArch64::ADDSWri : AArch64::SUBSWri;
923     else
924       CmpOpc = AArch64::SUBSWrr;
925     break;
926   case MVT::i64:
927     ZReg = AArch64::XZR;
928     if (UseImm)
929       CmpOpc = isNegativeImm ? AArch64::ADDSXri : AArch64::SUBSXri;
930     else
931       CmpOpc = AArch64::SUBSXrr;
932     break;
933   case MVT::f32:
934     isICmp = false;
935     CmpOpc = UseImm ? AArch64::FCMPSri : AArch64::FCMPSrr;
936     break;
937   case MVT::f64:
938     isICmp = false;
939     CmpOpc = UseImm ? AArch64::FCMPDri : AArch64::FCMPDrr;
940     break;
941   }
942
943   unsigned SrcReg1 = getRegForValue(Src1Value);
944   if (SrcReg1 == 0)
945     return false;
946
947   unsigned SrcReg2;
948   if (!UseImm) {
949     SrcReg2 = getRegForValue(Src2Value);
950     if (SrcReg2 == 0)
951       return false;
952   }
953
954   // We have i1, i8, or i16, we need to either zero extend or sign extend.
955   if (needsExt) {
956     SrcReg1 = EmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
957     if (SrcReg1 == 0)
958       return false;
959     if (!UseImm) {
960       SrcReg2 = EmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
961       if (SrcReg2 == 0)
962         return false;
963     }
964   }
965
966   if (isICmp) {
967     if (UseImm)
968       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
969           .addReg(ZReg)
970           .addReg(SrcReg1)
971           .addImm(Imm)
972           .addImm(0);
973     else
974       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
975           .addReg(ZReg)
976           .addReg(SrcReg1)
977           .addReg(SrcReg2);
978   } else {
979     if (UseImm)
980       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
981           .addReg(SrcReg1);
982     else
983       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
984           .addReg(SrcReg1)
985           .addReg(SrcReg2);
986   }
987   return true;
988 }
989
990 bool AArch64FastISel::SelectCmp(const Instruction *I) {
991   const CmpInst *CI = cast<CmpInst>(I);
992
993   // We may not handle every CC for now.
994   AArch64CC::CondCode CC = getCompareCC(CI->getPredicate());
995   if (CC == AArch64CC::AL)
996     return false;
997
998   // Emit the cmp.
999   if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1000     return false;
1001
1002   // Now set a register based on the comparison.
1003   AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
1004   unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
1005   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
1006           ResultReg)
1007       .addReg(AArch64::WZR)
1008       .addReg(AArch64::WZR)
1009       .addImm(invertedCC);
1010
1011   UpdateValueMap(I, ResultReg);
1012   return true;
1013 }
1014
1015 bool AArch64FastISel::SelectSelect(const Instruction *I) {
1016   const SelectInst *SI = cast<SelectInst>(I);
1017
1018   EVT DestEVT = TLI.getValueType(SI->getType(), true);
1019   if (!DestEVT.isSimple())
1020     return false;
1021
1022   MVT DestVT = DestEVT.getSimpleVT();
1023   if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
1024       DestVT != MVT::f64)
1025     return false;
1026
1027   unsigned CondReg = getRegForValue(SI->getCondition());
1028   if (CondReg == 0)
1029     return false;
1030   unsigned TrueReg = getRegForValue(SI->getTrueValue());
1031   if (TrueReg == 0)
1032     return false;
1033   unsigned FalseReg = getRegForValue(SI->getFalseValue());
1034   if (FalseReg == 0)
1035     return false;
1036
1037
1038   MRI.constrainRegClass(CondReg, &AArch64::GPR32RegClass);
1039   unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
1040   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
1041           ANDReg)
1042       .addReg(CondReg)
1043       .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
1044
1045   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SUBSWri))
1046       .addReg(ANDReg)
1047       .addReg(ANDReg)
1048       .addImm(0)
1049       .addImm(0);
1050
1051   unsigned SelectOpc;
1052   switch (DestVT.SimpleTy) {
1053   default:
1054     return false;
1055   case MVT::i32:
1056     SelectOpc = AArch64::CSELWr;
1057     break;
1058   case MVT::i64:
1059     SelectOpc = AArch64::CSELXr;
1060     break;
1061   case MVT::f32:
1062     SelectOpc = AArch64::FCSELSrrr;
1063     break;
1064   case MVT::f64:
1065     SelectOpc = AArch64::FCSELDrrr;
1066     break;
1067   }
1068
1069   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1070   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SelectOpc),
1071           ResultReg)
1072       .addReg(TrueReg)
1073       .addReg(FalseReg)
1074       .addImm(AArch64CC::NE);
1075
1076   UpdateValueMap(I, ResultReg);
1077   return true;
1078 }
1079
1080 bool AArch64FastISel::SelectFPExt(const Instruction *I) {
1081   Value *V = I->getOperand(0);
1082   if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
1083     return false;
1084
1085   unsigned Op = getRegForValue(V);
1086   if (Op == 0)
1087     return false;
1088
1089   unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
1090   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
1091           ResultReg).addReg(Op);
1092   UpdateValueMap(I, ResultReg);
1093   return true;
1094 }
1095
1096 bool AArch64FastISel::SelectFPTrunc(const Instruction *I) {
1097   Value *V = I->getOperand(0);
1098   if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
1099     return false;
1100
1101   unsigned Op = getRegForValue(V);
1102   if (Op == 0)
1103     return false;
1104
1105   unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
1106   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
1107           ResultReg).addReg(Op);
1108   UpdateValueMap(I, ResultReg);
1109   return true;
1110 }
1111
1112 // FPToUI and FPToSI
1113 bool AArch64FastISel::SelectFPToInt(const Instruction *I, bool Signed) {
1114   MVT DestVT;
1115   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1116     return false;
1117
1118   unsigned SrcReg = getRegForValue(I->getOperand(0));
1119   if (SrcReg == 0)
1120     return false;
1121
1122   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1123   if (SrcVT == MVT::f128)
1124     return false;
1125
1126   unsigned Opc;
1127   if (SrcVT == MVT::f64) {
1128     if (Signed)
1129       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
1130     else
1131       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
1132   } else {
1133     if (Signed)
1134       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
1135     else
1136       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
1137   }
1138   unsigned ResultReg = createResultReg(
1139       DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
1140   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1141       .addReg(SrcReg);
1142   UpdateValueMap(I, ResultReg);
1143   return true;
1144 }
1145
1146 bool AArch64FastISel::SelectIntToFP(const Instruction *I, bool Signed) {
1147   MVT DestVT;
1148   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1149     return false;
1150   assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
1151           "Unexpected value type.");
1152
1153   unsigned SrcReg = getRegForValue(I->getOperand(0));
1154   if (SrcReg == 0)
1155     return false;
1156
1157   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1158
1159   // Handle sign-extension.
1160   if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
1161     SrcReg =
1162         EmitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
1163     if (SrcReg == 0)
1164       return false;
1165   }
1166
1167   MRI.constrainRegClass(SrcReg, SrcVT == MVT::i64 ? &AArch64::GPR64RegClass
1168                                                   : &AArch64::GPR32RegClass);
1169
1170   unsigned Opc;
1171   if (SrcVT == MVT::i64) {
1172     if (Signed)
1173       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
1174     else
1175       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
1176   } else {
1177     if (Signed)
1178       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
1179     else
1180       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
1181   }
1182
1183   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1184   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1185       .addReg(SrcReg);
1186   UpdateValueMap(I, ResultReg);
1187   return true;
1188 }
1189
1190 bool AArch64FastISel::ProcessCallArgs(
1191     SmallVectorImpl<Value *> &Args, SmallVectorImpl<unsigned> &ArgRegs,
1192     SmallVectorImpl<MVT> &ArgVTs, SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1193     SmallVectorImpl<unsigned> &RegArgs, CallingConv::ID CC,
1194     unsigned &NumBytes) {
1195   SmallVector<CCValAssign, 16> ArgLocs;
1196   CCState CCInfo(CC, false, *FuncInfo.MF, TM, ArgLocs, *Context);
1197   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC));
1198
1199   // Get a count of how many bytes are to be pushed on the stack.
1200   NumBytes = CCInfo.getNextStackOffset();
1201
1202   // Issue CALLSEQ_START
1203   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1204   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
1205       .addImm(NumBytes);
1206
1207   // Process the args.
1208   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1209     CCValAssign &VA = ArgLocs[i];
1210     unsigned Arg = ArgRegs[VA.getValNo()];
1211     MVT ArgVT = ArgVTs[VA.getValNo()];
1212
1213     // Handle arg promotion: SExt, ZExt, AExt.
1214     switch (VA.getLocInfo()) {
1215     case CCValAssign::Full:
1216       break;
1217     case CCValAssign::SExt: {
1218       MVT DestVT = VA.getLocVT();
1219       MVT SrcVT = ArgVT;
1220       Arg = EmitIntExt(SrcVT, Arg, DestVT, /*isZExt*/ false);
1221       if (Arg == 0)
1222         return false;
1223       ArgVT = DestVT;
1224       break;
1225     }
1226     case CCValAssign::AExt:
1227     // Intentional fall-through.
1228     case CCValAssign::ZExt: {
1229       MVT DestVT = VA.getLocVT();
1230       MVT SrcVT = ArgVT;
1231       Arg = EmitIntExt(SrcVT, Arg, DestVT, /*isZExt*/ true);
1232       if (Arg == 0)
1233         return false;
1234       ArgVT = DestVT;
1235       break;
1236     }
1237     default:
1238       llvm_unreachable("Unknown arg promotion!");
1239     }
1240
1241     // Now copy/store arg to correct locations.
1242     if (VA.isRegLoc() && !VA.needsCustom()) {
1243       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1244               TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
1245       RegArgs.push_back(VA.getLocReg());
1246     } else if (VA.needsCustom()) {
1247       // FIXME: Handle custom args.
1248       return false;
1249     } else {
1250       assert(VA.isMemLoc() && "Assuming store on stack.");
1251
1252       // Need to store on the stack.
1253       unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1254
1255       unsigned BEAlign = 0;
1256       if (ArgSize < 8 && !Subtarget->isLittleEndian())
1257         BEAlign = 8 - ArgSize;
1258
1259       Address Addr;
1260       Addr.setKind(Address::RegBase);
1261       Addr.setReg(AArch64::SP);
1262       Addr.setOffset(VA.getLocMemOffset() + BEAlign);
1263
1264       if (!EmitStore(ArgVT, Arg, Addr))
1265         return false;
1266     }
1267   }
1268   return true;
1269 }
1270
1271 bool AArch64FastISel::FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1272                                  const Instruction *I, CallingConv::ID CC,
1273                                  unsigned &NumBytes) {
1274   // Issue CALLSEQ_END
1275   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1276   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
1277       .addImm(NumBytes)
1278       .addImm(0);
1279
1280   // Now the return value.
1281   if (RetVT != MVT::isVoid) {
1282     SmallVector<CCValAssign, 16> RVLocs;
1283     CCState CCInfo(CC, false, *FuncInfo.MF, TM, RVLocs, *Context);
1284     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
1285
1286     // Only handle a single return value.
1287     if (RVLocs.size() != 1)
1288       return false;
1289
1290     // Copy all of the result registers out of their specified physreg.
1291     MVT CopyVT = RVLocs[0].getValVT();
1292     unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
1293     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1294             TII.get(TargetOpcode::COPY),
1295             ResultReg).addReg(RVLocs[0].getLocReg());
1296     UsedRegs.push_back(RVLocs[0].getLocReg());
1297
1298     // Finally update the result.
1299     UpdateValueMap(I, ResultReg);
1300   }
1301
1302   return true;
1303 }
1304
1305 bool AArch64FastISel::SelectCall(const Instruction *I,
1306                                  const char *IntrMemName = nullptr) {
1307   const CallInst *CI = cast<CallInst>(I);
1308   const Value *Callee = CI->getCalledValue();
1309
1310   // Don't handle inline asm or intrinsics.
1311   if (isa<InlineAsm>(Callee))
1312     return false;
1313
1314   // Only handle global variable Callees.
1315   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1316   if (!GV)
1317     return false;
1318
1319   // Check the calling convention.
1320   ImmutableCallSite CS(CI);
1321   CallingConv::ID CC = CS.getCallingConv();
1322
1323   // Let SDISel handle vararg functions.
1324   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1325   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1326   if (FTy->isVarArg())
1327     return false;
1328
1329   // Handle *simple* calls for now.
1330   MVT RetVT;
1331   Type *RetTy = I->getType();
1332   if (RetTy->isVoidTy())
1333     RetVT = MVT::isVoid;
1334   else if (!isTypeLegal(RetTy, RetVT))
1335     return false;
1336
1337   // Set up the argument vectors.
1338   SmallVector<Value *, 8> Args;
1339   SmallVector<unsigned, 8> ArgRegs;
1340   SmallVector<MVT, 8> ArgVTs;
1341   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1342   Args.reserve(CS.arg_size());
1343   ArgRegs.reserve(CS.arg_size());
1344   ArgVTs.reserve(CS.arg_size());
1345   ArgFlags.reserve(CS.arg_size());
1346
1347   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1348        i != e; ++i) {
1349     // If we're lowering a memory intrinsic instead of a regular call, skip the
1350     // last two arguments, which shouldn't be passed to the underlying function.
1351     if (IntrMemName && e - i <= 2)
1352       break;
1353
1354     unsigned Arg = getRegForValue(*i);
1355     if (Arg == 0)
1356       return false;
1357
1358     ISD::ArgFlagsTy Flags;
1359     unsigned AttrInd = i - CS.arg_begin() + 1;
1360     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1361       Flags.setSExt();
1362     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1363       Flags.setZExt();
1364
1365     // FIXME: Only handle *easy* calls for now.
1366     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1367         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1368         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1369         CS.paramHasAttr(AttrInd, Attribute::ByVal))
1370       return false;
1371
1372     MVT ArgVT;
1373     Type *ArgTy = (*i)->getType();
1374     if (!isTypeLegal(ArgTy, ArgVT) &&
1375         !(ArgVT == MVT::i1 || ArgVT == MVT::i8 || ArgVT == MVT::i16))
1376       return false;
1377
1378     // We don't handle vector parameters yet.
1379     if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64)
1380       return false;
1381
1382     unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
1383     Flags.setOrigAlign(OriginalAlignment);
1384
1385     Args.push_back(*i);
1386     ArgRegs.push_back(Arg);
1387     ArgVTs.push_back(ArgVT);
1388     ArgFlags.push_back(Flags);
1389   }
1390
1391   // Handle the arguments now that we've gotten them.
1392   SmallVector<unsigned, 4> RegArgs;
1393   unsigned NumBytes;
1394   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1395     return false;
1396
1397   // Issue the call.
1398   MachineInstrBuilder MIB;
1399   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BL));
1400   if (!IntrMemName)
1401     MIB.addGlobalAddress(GV, 0, 0);
1402   else
1403     MIB.addExternalSymbol(IntrMemName, 0);
1404
1405   // Add implicit physical register uses to the call.
1406   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1407     MIB.addReg(RegArgs[i], RegState::Implicit);
1408
1409   // Add a register mask with the call-preserved registers.
1410   // Proper defs for return values will be added by setPhysRegsDeadExcept().
1411   MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
1412
1413   // Finish off the call including any return values.
1414   SmallVector<unsigned, 4> UsedRegs;
1415   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes))
1416     return false;
1417
1418   // Set all unused physreg defs as dead.
1419   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1420
1421   return true;
1422 }
1423
1424 bool AArch64FastISel::IsMemCpySmall(uint64_t Len, unsigned Alignment) {
1425   if (Alignment)
1426     return Len / Alignment <= 4;
1427   else
1428     return Len < 32;
1429 }
1430
1431 bool AArch64FastISel::TryEmitSmallMemCpy(Address Dest, Address Src,
1432                                          uint64_t Len, unsigned Alignment) {
1433   // Make sure we don't bloat code by inlining very large memcpy's.
1434   if (!IsMemCpySmall(Len, Alignment))
1435     return false;
1436
1437   int64_t UnscaledOffset = 0;
1438   Address OrigDest = Dest;
1439   Address OrigSrc = Src;
1440
1441   while (Len) {
1442     MVT VT;
1443     if (!Alignment || Alignment >= 8) {
1444       if (Len >= 8)
1445         VT = MVT::i64;
1446       else if (Len >= 4)
1447         VT = MVT::i32;
1448       else if (Len >= 2)
1449         VT = MVT::i16;
1450       else {
1451         VT = MVT::i8;
1452       }
1453     } else {
1454       // Bound based on alignment.
1455       if (Len >= 4 && Alignment == 4)
1456         VT = MVT::i32;
1457       else if (Len >= 2 && Alignment == 2)
1458         VT = MVT::i16;
1459       else {
1460         VT = MVT::i8;
1461       }
1462     }
1463
1464     bool RV;
1465     unsigned ResultReg;
1466     RV = EmitLoad(VT, ResultReg, Src);
1467     assert(RV == true && "Should be able to handle this load.");
1468     RV = EmitStore(VT, ResultReg, Dest);
1469     assert(RV == true && "Should be able to handle this store.");
1470     (void)RV;
1471
1472     int64_t Size = VT.getSizeInBits() / 8;
1473     Len -= Size;
1474     UnscaledOffset += Size;
1475
1476     // We need to recompute the unscaled offset for each iteration.
1477     Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
1478     Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
1479   }
1480
1481   return true;
1482 }
1483
1484 bool AArch64FastISel::SelectIntrinsicCall(const IntrinsicInst &I) {
1485   // FIXME: Handle more intrinsics.
1486   switch (I.getIntrinsicID()) {
1487   default:
1488     return false;
1489   case Intrinsic::memcpy:
1490   case Intrinsic::memmove: {
1491     const MemTransferInst &MTI = cast<MemTransferInst>(I);
1492     // Don't handle volatile.
1493     if (MTI.isVolatile())
1494       return false;
1495
1496     // Disable inlining for memmove before calls to ComputeAddress.  Otherwise,
1497     // we would emit dead code because we don't currently handle memmoves.
1498     bool isMemCpy = (I.getIntrinsicID() == Intrinsic::memcpy);
1499     if (isa<ConstantInt>(MTI.getLength()) && isMemCpy) {
1500       // Small memcpy's are common enough that we want to do them without a call
1501       // if possible.
1502       uint64_t Len = cast<ConstantInt>(MTI.getLength())->getZExtValue();
1503       unsigned Alignment = MTI.getAlignment();
1504       if (IsMemCpySmall(Len, Alignment)) {
1505         Address Dest, Src;
1506         if (!ComputeAddress(MTI.getRawDest(), Dest) ||
1507             !ComputeAddress(MTI.getRawSource(), Src))
1508           return false;
1509         if (TryEmitSmallMemCpy(Dest, Src, Len, Alignment))
1510           return true;
1511       }
1512     }
1513
1514     if (!MTI.getLength()->getType()->isIntegerTy(64))
1515       return false;
1516
1517     if (MTI.getSourceAddressSpace() > 255 || MTI.getDestAddressSpace() > 255)
1518       // Fast instruction selection doesn't support the special
1519       // address spaces.
1520       return false;
1521
1522     const char *IntrMemName = isa<MemCpyInst>(I) ? "memcpy" : "memmove";
1523     return SelectCall(&I, IntrMemName);
1524   }
1525   case Intrinsic::memset: {
1526     const MemSetInst &MSI = cast<MemSetInst>(I);
1527     // Don't handle volatile.
1528     if (MSI.isVolatile())
1529       return false;
1530
1531     if (!MSI.getLength()->getType()->isIntegerTy(64))
1532       return false;
1533
1534     if (MSI.getDestAddressSpace() > 255)
1535       // Fast instruction selection doesn't support the special
1536       // address spaces.
1537       return false;
1538
1539     return SelectCall(&I, "memset");
1540   }
1541   case Intrinsic::trap: {
1542     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
1543         .addImm(1);
1544     return true;
1545   }
1546   }
1547   return false;
1548 }
1549
1550 bool AArch64FastISel::SelectRet(const Instruction *I) {
1551   const ReturnInst *Ret = cast<ReturnInst>(I);
1552   const Function &F = *I->getParent()->getParent();
1553
1554   if (!FuncInfo.CanLowerReturn)
1555     return false;
1556
1557   if (F.isVarArg())
1558     return false;
1559
1560   // Build a list of return value registers.
1561   SmallVector<unsigned, 4> RetRegs;
1562
1563   if (Ret->getNumOperands() > 0) {
1564     CallingConv::ID CC = F.getCallingConv();
1565     SmallVector<ISD::OutputArg, 4> Outs;
1566     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1567
1568     // Analyze operands of the call, assigning locations to each operand.
1569     SmallVector<CCValAssign, 16> ValLocs;
1570     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
1571                    I->getContext());
1572     CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
1573                                                      : RetCC_AArch64_AAPCS;
1574     CCInfo.AnalyzeReturn(Outs, RetCC);
1575
1576     // Only handle a single return value for now.
1577     if (ValLocs.size() != 1)
1578       return false;
1579
1580     CCValAssign &VA = ValLocs[0];
1581     const Value *RV = Ret->getOperand(0);
1582
1583     // Don't bother handling odd stuff for now.
1584     if (VA.getLocInfo() != CCValAssign::Full)
1585       return false;
1586     // Only handle register returns for now.
1587     if (!VA.isRegLoc())
1588       return false;
1589     unsigned Reg = getRegForValue(RV);
1590     if (Reg == 0)
1591       return false;
1592
1593     unsigned SrcReg = Reg + VA.getValNo();
1594     unsigned DestReg = VA.getLocReg();
1595     // Avoid a cross-class copy. This is very unlikely.
1596     if (!MRI.getRegClass(SrcReg)->contains(DestReg))
1597       return false;
1598
1599     EVT RVEVT = TLI.getValueType(RV->getType());
1600     if (!RVEVT.isSimple())
1601       return false;
1602
1603     // Vectors (of > 1 lane) in big endian need tricky handling.
1604     if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1)
1605       return false;
1606
1607     MVT RVVT = RVEVT.getSimpleVT();
1608     if (RVVT == MVT::f128)
1609       return false;
1610     MVT DestVT = VA.getValVT();
1611     // Special handling for extended integers.
1612     if (RVVT != DestVT) {
1613       if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
1614         return false;
1615
1616       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1617         return false;
1618
1619       bool isZExt = Outs[0].Flags.isZExt();
1620       SrcReg = EmitIntExt(RVVT, SrcReg, DestVT, isZExt);
1621       if (SrcReg == 0)
1622         return false;
1623     }
1624
1625     // Make the copy.
1626     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1627             TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
1628
1629     // Add register to return instruction.
1630     RetRegs.push_back(VA.getLocReg());
1631   }
1632
1633   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1634                                     TII.get(AArch64::RET_ReallyLR));
1635   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1636     MIB.addReg(RetRegs[i], RegState::Implicit);
1637   return true;
1638 }
1639
1640 bool AArch64FastISel::SelectTrunc(const Instruction *I) {
1641   Type *DestTy = I->getType();
1642   Value *Op = I->getOperand(0);
1643   Type *SrcTy = Op->getType();
1644
1645   EVT SrcEVT = TLI.getValueType(SrcTy, true);
1646   EVT DestEVT = TLI.getValueType(DestTy, true);
1647   if (!SrcEVT.isSimple())
1648     return false;
1649   if (!DestEVT.isSimple())
1650     return false;
1651
1652   MVT SrcVT = SrcEVT.getSimpleVT();
1653   MVT DestVT = DestEVT.getSimpleVT();
1654
1655   if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
1656       SrcVT != MVT::i8)
1657     return false;
1658   if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
1659       DestVT != MVT::i1)
1660     return false;
1661
1662   unsigned SrcReg = getRegForValue(Op);
1663   if (!SrcReg)
1664     return false;
1665
1666   // If we're truncating from i64 to a smaller non-legal type then generate an
1667   // AND.  Otherwise, we know the high bits are undefined and a truncate doesn't
1668   // generate any code.
1669   if (SrcVT == MVT::i64) {
1670     uint64_t Mask = 0;
1671     switch (DestVT.SimpleTy) {
1672     default:
1673       // Trunc i64 to i32 is handled by the target-independent fast-isel.
1674       return false;
1675     case MVT::i1:
1676       Mask = 0x1;
1677       break;
1678     case MVT::i8:
1679       Mask = 0xff;
1680       break;
1681     case MVT::i16:
1682       Mask = 0xffff;
1683       break;
1684     }
1685     // Issue an extract_subreg to get the lower 32-bits.
1686     unsigned Reg32 = FastEmitInst_extractsubreg(MVT::i32, SrcReg, /*Kill=*/true,
1687                                                 AArch64::sub_32);
1688     MRI.constrainRegClass(Reg32, &AArch64::GPR32RegClass);
1689     // Create the AND instruction which performs the actual truncation.
1690     unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
1691     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
1692             ANDReg)
1693         .addReg(Reg32)
1694         .addImm(AArch64_AM::encodeLogicalImmediate(Mask, 32));
1695     SrcReg = ANDReg;
1696   }
1697
1698   UpdateValueMap(I, SrcReg);
1699   return true;
1700 }
1701
1702 unsigned AArch64FastISel::Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt) {
1703   assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
1704           DestVT == MVT::i64) &&
1705          "Unexpected value type.");
1706   // Handle i8 and i16 as i32.
1707   if (DestVT == MVT::i8 || DestVT == MVT::i16)
1708     DestVT = MVT::i32;
1709
1710   if (isZExt) {
1711     MRI.constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
1712     unsigned ResultReg = createResultReg(&AArch64::GPR32spRegClass);
1713     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
1714             ResultReg)
1715         .addReg(SrcReg)
1716         .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
1717
1718     if (DestVT == MVT::i64) {
1719       // We're ZExt i1 to i64.  The ANDWri Wd, Ws, #1 implicitly clears the
1720       // upper 32 bits.  Emit a SUBREG_TO_REG to extend from Wd to Xd.
1721       unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1722       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1723               TII.get(AArch64::SUBREG_TO_REG), Reg64)
1724           .addImm(0)
1725           .addReg(ResultReg)
1726           .addImm(AArch64::sub_32);
1727       ResultReg = Reg64;
1728     }
1729     return ResultReg;
1730   } else {
1731     if (DestVT == MVT::i64) {
1732       // FIXME: We're SExt i1 to i64.
1733       return 0;
1734     }
1735     unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
1736     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SBFMWri),
1737             ResultReg)
1738         .addReg(SrcReg)
1739         .addImm(0)
1740         .addImm(0);
1741     return ResultReg;
1742   }
1743 }
1744
1745 unsigned AArch64FastISel::EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1746                                      bool isZExt) {
1747   assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
1748   unsigned Opc;
1749   unsigned Imm = 0;
1750
1751   switch (SrcVT.SimpleTy) {
1752   default:
1753     return 0;
1754   case MVT::i1:
1755     return Emiti1Ext(SrcReg, DestVT, isZExt);
1756   case MVT::i8:
1757     if (DestVT == MVT::i64)
1758       Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
1759     else
1760       Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
1761     Imm = 7;
1762     break;
1763   case MVT::i16:
1764     if (DestVT == MVT::i64)
1765       Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
1766     else
1767       Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
1768     Imm = 15;
1769     break;
1770   case MVT::i32:
1771     assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
1772     Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
1773     Imm = 31;
1774     break;
1775   }
1776
1777   // Handle i8 and i16 as i32.
1778   if (DestVT == MVT::i8 || DestVT == MVT::i16)
1779     DestVT = MVT::i32;
1780   else if (DestVT == MVT::i64) {
1781     unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1782     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1783             TII.get(AArch64::SUBREG_TO_REG), Src64)
1784         .addImm(0)
1785         .addReg(SrcReg)
1786         .addImm(AArch64::sub_32);
1787     SrcReg = Src64;
1788   }
1789
1790   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1791   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1792       .addReg(SrcReg)
1793       .addImm(0)
1794       .addImm(Imm);
1795
1796   return ResultReg;
1797 }
1798
1799 bool AArch64FastISel::SelectIntExt(const Instruction *I) {
1800   // On ARM, in general, integer casts don't involve legal types; this code
1801   // handles promotable integers.  The high bits for a type smaller than
1802   // the register size are assumed to be undefined.
1803   Type *DestTy = I->getType();
1804   Value *Src = I->getOperand(0);
1805   Type *SrcTy = Src->getType();
1806
1807   bool isZExt = isa<ZExtInst>(I);
1808   unsigned SrcReg = getRegForValue(Src);
1809   if (!SrcReg)
1810     return false;
1811
1812   EVT SrcEVT = TLI.getValueType(SrcTy, true);
1813   EVT DestEVT = TLI.getValueType(DestTy, true);
1814   if (!SrcEVT.isSimple())
1815     return false;
1816   if (!DestEVT.isSimple())
1817     return false;
1818
1819   MVT SrcVT = SrcEVT.getSimpleVT();
1820   MVT DestVT = DestEVT.getSimpleVT();
1821   unsigned ResultReg = EmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
1822   if (ResultReg == 0)
1823     return false;
1824   UpdateValueMap(I, ResultReg);
1825   return true;
1826 }
1827
1828 bool AArch64FastISel::SelectRem(const Instruction *I, unsigned ISDOpcode) {
1829   EVT DestEVT = TLI.getValueType(I->getType(), true);
1830   if (!DestEVT.isSimple())
1831     return false;
1832
1833   MVT DestVT = DestEVT.getSimpleVT();
1834   if (DestVT != MVT::i64 && DestVT != MVT::i32)
1835     return false;
1836
1837   unsigned DivOpc;
1838   bool is64bit = (DestVT == MVT::i64);
1839   switch (ISDOpcode) {
1840   default:
1841     return false;
1842   case ISD::SREM:
1843     DivOpc = is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
1844     break;
1845   case ISD::UREM:
1846     DivOpc = is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
1847     break;
1848   }
1849   unsigned MSubOpc = is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
1850   unsigned Src0Reg = getRegForValue(I->getOperand(0));
1851   if (!Src0Reg)
1852     return false;
1853
1854   unsigned Src1Reg = getRegForValue(I->getOperand(1));
1855   if (!Src1Reg)
1856     return false;
1857
1858   unsigned QuotReg = createResultReg(TLI.getRegClassFor(DestVT));
1859   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(DivOpc), QuotReg)
1860       .addReg(Src0Reg)
1861       .addReg(Src1Reg);
1862   // The remainder is computed as numerator - (quotient * denominator) using the
1863   // MSUB instruction.
1864   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1865   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MSubOpc), ResultReg)
1866       .addReg(QuotReg)
1867       .addReg(Src1Reg)
1868       .addReg(Src0Reg);
1869   UpdateValueMap(I, ResultReg);
1870   return true;
1871 }
1872
1873 bool AArch64FastISel::SelectMul(const Instruction *I) {
1874   EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1875   if (!SrcEVT.isSimple())
1876     return false;
1877   MVT SrcVT = SrcEVT.getSimpleVT();
1878
1879   // Must be simple value type.  Don't handle vectors.
1880   if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
1881       SrcVT != MVT::i8)
1882     return false;
1883
1884   unsigned Opc;
1885   unsigned ZReg;
1886   switch (SrcVT.SimpleTy) {
1887   default:
1888     return false;
1889   case MVT::i8:
1890   case MVT::i16:
1891   case MVT::i32:
1892     ZReg = AArch64::WZR;
1893     Opc = AArch64::MADDWrrr;
1894     break;
1895   case MVT::i64:
1896     ZReg = AArch64::XZR;
1897     Opc = AArch64::MADDXrrr;
1898     break;
1899   }
1900
1901   unsigned Src0Reg = getRegForValue(I->getOperand(0));
1902   if (!Src0Reg)
1903     return false;
1904
1905   unsigned Src1Reg = getRegForValue(I->getOperand(1));
1906   if (!Src1Reg)
1907     return false;
1908
1909   // Create the base instruction, then add the operands.
1910   unsigned ResultReg = createResultReg(TLI.getRegClassFor(SrcVT));
1911   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1912       .addReg(Src0Reg)
1913       .addReg(Src1Reg)
1914       .addReg(ZReg);
1915   UpdateValueMap(I, ResultReg);
1916   return true;
1917 }
1918
1919 bool AArch64FastISel::TargetSelectInstruction(const Instruction *I) {
1920   switch (I->getOpcode()) {
1921   default:
1922     break;
1923   case Instruction::Load:
1924     return SelectLoad(I);
1925   case Instruction::Store:
1926     return SelectStore(I);
1927   case Instruction::Br:
1928     return SelectBranch(I);
1929   case Instruction::IndirectBr:
1930     return SelectIndirectBr(I);
1931   case Instruction::FCmp:
1932   case Instruction::ICmp:
1933     return SelectCmp(I);
1934   case Instruction::Select:
1935     return SelectSelect(I);
1936   case Instruction::FPExt:
1937     return SelectFPExt(I);
1938   case Instruction::FPTrunc:
1939     return SelectFPTrunc(I);
1940   case Instruction::FPToSI:
1941     return SelectFPToInt(I, /*Signed=*/true);
1942   case Instruction::FPToUI:
1943     return SelectFPToInt(I, /*Signed=*/false);
1944   case Instruction::SIToFP:
1945     return SelectIntToFP(I, /*Signed=*/true);
1946   case Instruction::UIToFP:
1947     return SelectIntToFP(I, /*Signed=*/false);
1948   case Instruction::SRem:
1949     return SelectRem(I, ISD::SREM);
1950   case Instruction::URem:
1951     return SelectRem(I, ISD::UREM);
1952   case Instruction::Call:
1953     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1954       return SelectIntrinsicCall(*II);
1955     return SelectCall(I);
1956   case Instruction::Ret:
1957     return SelectRet(I);
1958   case Instruction::Trunc:
1959     return SelectTrunc(I);
1960   case Instruction::ZExt:
1961   case Instruction::SExt:
1962     return SelectIntExt(I);
1963   case Instruction::Mul:
1964     // FIXME: This really should be handled by the target-independent selector.
1965     return SelectMul(I);
1966   }
1967   return false;
1968   // Silence warnings.
1969   (void)&CC_AArch64_DarwinPCS_VarArg;
1970 }
1971
1972 namespace llvm {
1973 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &funcInfo,
1974                                         const TargetLibraryInfo *libInfo) {
1975   return new AArch64FastISel(funcInfo, libInfo);
1976 }
1977 }