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