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