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