[opaque pointer type] Allow gep_type_iterator to work with the pointee type from...
[oota-llvm.git] / lib / Target / Mips / MipsFastISel.cpp
1 //===-- MipsastISel.cpp - Mips FastISel implementation
2 //---------------------===//
3
4 #include "MipsCCState.h"
5 #include "MipsInstrInfo.h"
6 #include "MipsISelLowering.h"
7 #include "MipsMachineFunction.h"
8 #include "MipsRegisterInfo.h"
9 #include "MipsSubtarget.h"
10 #include "MipsTargetMachine.h"
11 #include "llvm/Analysis/TargetLibraryInfo.h"
12 #include "llvm/CodeGen/FastISel.h"
13 #include "llvm/CodeGen/FunctionLoweringInfo.h"
14 #include "llvm/CodeGen/MachineInstrBuilder.h"
15 #include "llvm/CodeGen/MachineRegisterInfo.h"
16 #include "llvm/IR/GetElementPtrTypeIterator.h"
17 #include "llvm/IR/GlobalAlias.h"
18 #include "llvm/IR/GlobalVariable.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20
21 using namespace llvm;
22
23 namespace {
24
25 class MipsFastISel final : public FastISel {
26
27   // All possible address modes.
28   class Address {
29   public:
30     typedef enum { RegBase, FrameIndexBase } BaseKind;
31
32   private:
33     BaseKind Kind;
34     union {
35       unsigned Reg;
36       int FI;
37     } Base;
38
39     int64_t Offset;
40
41     const GlobalValue *GV;
42
43   public:
44     // Innocuous defaults for our address.
45     Address() : Kind(RegBase), Offset(0), GV(0) { Base.Reg = 0; }
46     void setKind(BaseKind K) { Kind = K; }
47     BaseKind getKind() const { return Kind; }
48     bool isRegBase() const { return Kind == RegBase; }
49     bool isFIBase() const { return Kind == FrameIndexBase; }
50     void setReg(unsigned Reg) {
51       assert(isRegBase() && "Invalid base register access!");
52       Base.Reg = Reg;
53     }
54     unsigned getReg() const {
55       assert(isRegBase() && "Invalid base register access!");
56       return Base.Reg;
57     }
58     void setFI(unsigned FI) {
59       assert(isFIBase() && "Invalid base frame index access!");
60       Base.FI = FI;
61     }
62     unsigned getFI() const {
63       assert(isFIBase() && "Invalid base frame index access!");
64       return Base.FI;
65     }
66
67     void setOffset(int64_t Offset_) { Offset = Offset_; }
68     int64_t getOffset() const { return Offset; }
69     void setGlobalValue(const GlobalValue *G) { GV = G; }
70     const GlobalValue *getGlobalValue() { return GV; }
71   };
72
73   /// Subtarget - Keep a pointer to the MipsSubtarget around so that we can
74   /// make the right decision when generating code for different targets.
75   const TargetMachine &TM;
76   const MipsSubtarget *Subtarget;
77   const TargetInstrInfo &TII;
78   const TargetLowering &TLI;
79   MipsFunctionInfo *MFI;
80
81   // Convenience variables to avoid some queries.
82   LLVMContext *Context;
83
84   bool fastLowerCall(CallLoweringInfo &CLI) override;
85
86   bool TargetSupported;
87   bool UnsupportedFPMode; // To allow fast-isel to proceed and just not handle
88   // floating point but not reject doing fast-isel in other
89   // situations
90
91 private:
92   // Selection routines.
93   bool selectLogicalOp(const Instruction *I);
94   bool selectLoad(const Instruction *I);
95   bool selectStore(const Instruction *I);
96   bool selectBranch(const Instruction *I);
97   bool selectCmp(const Instruction *I);
98   bool selectFPExt(const Instruction *I);
99   bool selectFPTrunc(const Instruction *I);
100   bool selectFPToInt(const Instruction *I, bool IsSigned);
101   bool selectRet(const Instruction *I);
102   bool selectTrunc(const Instruction *I);
103   bool selectIntExt(const Instruction *I);
104   bool selectShift(const Instruction *I);
105
106   // Utility helper routines.
107   bool isTypeLegal(Type *Ty, MVT &VT);
108   bool isTypeSupported(Type *Ty, MVT &VT);
109   bool isLoadTypeLegal(Type *Ty, MVT &VT);
110   bool computeAddress(const Value *Obj, Address &Addr);
111   bool computeCallAddress(const Value *V, Address &Addr);
112   void simplifyAddress(Address &Addr);
113
114   // Emit helper routines.
115   bool emitCmp(unsigned DestReg, const CmpInst *CI);
116   bool emitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
117                 unsigned Alignment = 0);
118   bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
119                  MachineMemOperand *MMO = nullptr);
120   bool emitStore(MVT VT, unsigned SrcReg, Address &Addr,
121                  unsigned Alignment = 0);
122   unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
123   bool emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, unsigned DestReg,
124
125                   bool IsZExt);
126   bool emitIntZExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, unsigned DestReg);
127
128   bool emitIntSExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, unsigned DestReg);
129   bool emitIntSExt32r1(MVT SrcVT, unsigned SrcReg, MVT DestVT,
130                        unsigned DestReg);
131   bool emitIntSExt32r2(MVT SrcVT, unsigned SrcReg, MVT DestVT,
132                        unsigned DestReg);
133
134   unsigned getRegEnsuringSimpleIntegerWidening(const Value *, bool IsUnsigned);
135
136   unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
137                          const Value *RHS);
138
139   unsigned materializeFP(const ConstantFP *CFP, MVT VT);
140   unsigned materializeGV(const GlobalValue *GV, MVT VT);
141   unsigned materializeInt(const Constant *C, MVT VT);
142   unsigned materialize32BitInt(int64_t Imm, const TargetRegisterClass *RC);
143
144   MachineInstrBuilder emitInst(unsigned Opc) {
145     return BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
146   }
147   MachineInstrBuilder emitInst(unsigned Opc, unsigned DstReg) {
148     return BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
149                    DstReg);
150   }
151   MachineInstrBuilder emitInstStore(unsigned Opc, unsigned SrcReg,
152                                     unsigned MemReg, int64_t MemOffset) {
153     return emitInst(Opc).addReg(SrcReg).addReg(MemReg).addImm(MemOffset);
154   }
155   MachineInstrBuilder emitInstLoad(unsigned Opc, unsigned DstReg,
156                                    unsigned MemReg, int64_t MemOffset) {
157     return emitInst(Opc, DstReg).addReg(MemReg).addImm(MemOffset);
158   }
159   // for some reason, this default is not generated by tablegen
160   // so we explicitly generate it here.
161   //
162   unsigned fastEmitInst_riir(uint64_t inst, const TargetRegisterClass *RC,
163                              unsigned Op0, bool Op0IsKill, uint64_t imm1,
164                              uint64_t imm2, unsigned Op3, bool Op3IsKill) {
165     return 0;
166   }
167
168   // Call handling routines.
169 private:
170   CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
171   bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
172                        unsigned &NumBytes);
173   bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
174
175 public:
176   // Backend specific FastISel code.
177   explicit MipsFastISel(FunctionLoweringInfo &funcInfo,
178                         const TargetLibraryInfo *libInfo)
179       : FastISel(funcInfo, libInfo), TM(funcInfo.MF->getTarget()),
180         Subtarget(&funcInfo.MF->getSubtarget<MipsSubtarget>()),
181         TII(*Subtarget->getInstrInfo()), TLI(*Subtarget->getTargetLowering()) {
182     MFI = funcInfo.MF->getInfo<MipsFunctionInfo>();
183     Context = &funcInfo.Fn->getContext();
184     TargetSupported =
185         ((TM.getRelocationModel() == Reloc::PIC_) &&
186          ((Subtarget->hasMips32r2() || Subtarget->hasMips32()) &&
187           (static_cast<const MipsTargetMachine &>(TM).getABI().IsO32())));
188     UnsupportedFPMode = Subtarget->isFP64bit();
189   }
190
191   unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
192   unsigned fastMaterializeConstant(const Constant *C) override;
193   bool fastSelectInstruction(const Instruction *I) override;
194
195 #include "MipsGenFastISel.inc"
196 };
197 } // end anonymous namespace.
198
199 static bool CC_Mips(unsigned ValNo, MVT ValVT, MVT LocVT,
200                     CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
201                     CCState &State) LLVM_ATTRIBUTE_UNUSED;
202
203 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT, MVT LocVT,
204                             CCValAssign::LocInfo LocInfo,
205                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
206   llvm_unreachable("should not be called");
207 }
208
209 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT, MVT LocVT,
210                             CCValAssign::LocInfo LocInfo,
211                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
212   llvm_unreachable("should not be called");
213 }
214
215 #include "MipsGenCallingConv.inc"
216
217 CCAssignFn *MipsFastISel::CCAssignFnForCall(CallingConv::ID CC) const {
218   return CC_MipsO32;
219 }
220
221 unsigned MipsFastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
222                                      const Value *LHS, const Value *RHS) {
223   // Canonicalize immediates to the RHS first.
224   if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
225     std::swap(LHS, RHS);
226
227   unsigned Opc;
228   if (ISDOpc == ISD::AND) {
229     Opc = Mips::AND;
230   } else if (ISDOpc == ISD::OR) {
231     Opc = Mips::OR;
232   } else if (ISDOpc == ISD::XOR) {
233     Opc = Mips::XOR;
234   } else
235     llvm_unreachable("unexpected opcode");
236
237   unsigned LHSReg = getRegForValue(LHS);
238   unsigned ResultReg = createResultReg(&Mips::GPR32RegClass);
239   if (!ResultReg)
240     return 0;
241
242   unsigned RHSReg;
243   if (!LHSReg)
244     return 0;
245
246   if (const auto *C = dyn_cast<ConstantInt>(RHS))
247     RHSReg = materializeInt(C, MVT::i32);
248   else
249     RHSReg = getRegForValue(RHS);
250
251   if (!RHSReg)
252     return 0;
253
254   emitInst(Opc, ResultReg).addReg(LHSReg).addReg(RHSReg);
255   return ResultReg;
256 }
257
258 unsigned MipsFastISel::fastMaterializeAlloca(const AllocaInst *AI) {
259   assert(TLI.getValueType(AI->getType(), true) == MVT::i32 &&
260          "Alloca should always return a pointer.");
261
262   DenseMap<const AllocaInst *, int>::iterator SI =
263       FuncInfo.StaticAllocaMap.find(AI);
264
265   if (SI != FuncInfo.StaticAllocaMap.end()) {
266     unsigned ResultReg = createResultReg(&Mips::GPR32RegClass);
267     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Mips::LEA_ADDiu),
268             ResultReg)
269         .addFrameIndex(SI->second)
270         .addImm(0);
271     return ResultReg;
272   }
273
274   return 0;
275 }
276
277 unsigned MipsFastISel::materializeInt(const Constant *C, MVT VT) {
278   if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8 && VT != MVT::i1)
279     return 0;
280   const TargetRegisterClass *RC = &Mips::GPR32RegClass;
281   const ConstantInt *CI = cast<ConstantInt>(C);
282   int64_t Imm;
283   if ((VT != MVT::i1) && CI->isNegative())
284     Imm = CI->getSExtValue();
285   else
286     Imm = CI->getZExtValue();
287   return materialize32BitInt(Imm, RC);
288 }
289
290 unsigned MipsFastISel::materialize32BitInt(int64_t Imm,
291                                            const TargetRegisterClass *RC) {
292   unsigned ResultReg = createResultReg(RC);
293
294   if (isInt<16>(Imm)) {
295     unsigned Opc = Mips::ADDiu;
296     emitInst(Opc, ResultReg).addReg(Mips::ZERO).addImm(Imm);
297     return ResultReg;
298   } else if (isUInt<16>(Imm)) {
299     emitInst(Mips::ORi, ResultReg).addReg(Mips::ZERO).addImm(Imm);
300     return ResultReg;
301   }
302   unsigned Lo = Imm & 0xFFFF;
303   unsigned Hi = (Imm >> 16) & 0xFFFF;
304   if (Lo) {
305     // Both Lo and Hi have nonzero bits.
306     unsigned TmpReg = createResultReg(RC);
307     emitInst(Mips::LUi, TmpReg).addImm(Hi);
308     emitInst(Mips::ORi, ResultReg).addReg(TmpReg).addImm(Lo);
309   } else {
310     emitInst(Mips::LUi, ResultReg).addImm(Hi);
311   }
312   return ResultReg;
313 }
314
315 unsigned MipsFastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
316   if (UnsupportedFPMode)
317     return 0;
318   int64_t Imm = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
319   if (VT == MVT::f32) {
320     const TargetRegisterClass *RC = &Mips::FGR32RegClass;
321     unsigned DestReg = createResultReg(RC);
322     unsigned TempReg = materialize32BitInt(Imm, &Mips::GPR32RegClass);
323     emitInst(Mips::MTC1, DestReg).addReg(TempReg);
324     return DestReg;
325   } else if (VT == MVT::f64) {
326     const TargetRegisterClass *RC = &Mips::AFGR64RegClass;
327     unsigned DestReg = createResultReg(RC);
328     unsigned TempReg1 = materialize32BitInt(Imm >> 32, &Mips::GPR32RegClass);
329     unsigned TempReg2 =
330         materialize32BitInt(Imm & 0xFFFFFFFF, &Mips::GPR32RegClass);
331     emitInst(Mips::BuildPairF64, DestReg).addReg(TempReg2).addReg(TempReg1);
332     return DestReg;
333   }
334   return 0;
335 }
336
337 unsigned MipsFastISel::materializeGV(const GlobalValue *GV, MVT VT) {
338   // For now 32-bit only.
339   if (VT != MVT::i32)
340     return 0;
341   const TargetRegisterClass *RC = &Mips::GPR32RegClass;
342   unsigned DestReg = createResultReg(RC);
343   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
344   bool IsThreadLocal = GVar && GVar->isThreadLocal();
345   // TLS not supported at this time.
346   if (IsThreadLocal)
347     return 0;
348   emitInst(Mips::LW, DestReg)
349       .addReg(MFI->getGlobalBaseReg())
350       .addGlobalAddress(GV, 0, MipsII::MO_GOT);
351   if ((GV->hasInternalLinkage() ||
352        (GV->hasLocalLinkage() && !isa<Function>(GV)))) {
353     unsigned TempReg = createResultReg(RC);
354     emitInst(Mips::ADDiu, TempReg)
355         .addReg(DestReg)
356         .addGlobalAddress(GV, 0, MipsII::MO_ABS_LO);
357     DestReg = TempReg;
358   }
359   return DestReg;
360 }
361
362 // Materialize a constant into a register, and return the register
363 // number (or zero if we failed to handle it).
364 unsigned MipsFastISel::fastMaterializeConstant(const Constant *C) {
365   EVT CEVT = TLI.getValueType(C->getType(), true);
366
367   // Only handle simple types.
368   if (!CEVT.isSimple())
369     return 0;
370   MVT VT = CEVT.getSimpleVT();
371
372   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
373     return (UnsupportedFPMode) ? 0 : materializeFP(CFP, VT);
374   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
375     return materializeGV(GV, VT);
376   else if (isa<ConstantInt>(C))
377     return materializeInt(C, VT);
378
379   return 0;
380 }
381
382 bool MipsFastISel::computeAddress(const Value *Obj, Address &Addr) {
383
384   const User *U = nullptr;
385   unsigned Opcode = Instruction::UserOp1;
386   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
387     // Don't walk into other basic blocks unless the object is an alloca from
388     // another block, otherwise it may not have a virtual register assigned.
389     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
390         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
391       Opcode = I->getOpcode();
392       U = I;
393     }
394   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
395     Opcode = C->getOpcode();
396     U = C;
397   }
398   switch (Opcode) {
399   default:
400     break;
401   case Instruction::BitCast: {
402     // Look through bitcasts.
403     return computeAddress(U->getOperand(0), Addr);
404   }
405   case Instruction::GetElementPtr: {
406     Address SavedAddr = Addr;
407     uint64_t TmpOffset = Addr.getOffset();
408     // Iterate through the GEP folding the constants into offsets where
409     // we can.
410     gep_type_iterator GTI = gep_type_begin(U);
411     for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
412          ++i, ++GTI) {
413       const Value *Op = *i;
414       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
415         const StructLayout *SL = DL.getStructLayout(STy);
416         unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
417         TmpOffset += SL->getElementOffset(Idx);
418       } else {
419         uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
420         for (;;) {
421           if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
422             // Constant-offset addressing.
423             TmpOffset += CI->getSExtValue() * S;
424             break;
425           }
426           if (canFoldAddIntoGEP(U, Op)) {
427             // A compatible add with a constant operand. Fold the constant.
428             ConstantInt *CI =
429                 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
430             TmpOffset += CI->getSExtValue() * S;
431             // Iterate on the other operand.
432             Op = cast<AddOperator>(Op)->getOperand(0);
433             continue;
434           }
435           // Unsupported
436           goto unsupported_gep;
437         }
438       }
439     }
440     // Try to grab the base operand now.
441     Addr.setOffset(TmpOffset);
442     if (computeAddress(U->getOperand(0), Addr))
443       return true;
444     // We failed, restore everything and try the other options.
445     Addr = SavedAddr;
446   unsupported_gep:
447     break;
448   }
449   case Instruction::Alloca: {
450     const AllocaInst *AI = cast<AllocaInst>(Obj);
451     DenseMap<const AllocaInst *, int>::iterator SI =
452         FuncInfo.StaticAllocaMap.find(AI);
453     if (SI != FuncInfo.StaticAllocaMap.end()) {
454       Addr.setKind(Address::FrameIndexBase);
455       Addr.setFI(SI->second);
456       return true;
457     }
458     break;
459   }
460   }
461   Addr.setReg(getRegForValue(Obj));
462   return Addr.getReg() != 0;
463 }
464
465 bool MipsFastISel::computeCallAddress(const Value *V, Address &Addr) {
466   const GlobalValue *GV = dyn_cast<GlobalValue>(V);
467   if (GV && isa<Function>(GV) && cast<Function>(GV)->isIntrinsic())
468     return false;
469   if (!GV)
470     return false;
471   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
472     Addr.setGlobalValue(GV);
473     return true;
474   }
475   return false;
476 }
477
478 bool MipsFastISel::isTypeLegal(Type *Ty, MVT &VT) {
479   EVT evt = TLI.getValueType(Ty, true);
480   // Only handle simple types.
481   if (evt == MVT::Other || !evt.isSimple())
482     return false;
483   VT = evt.getSimpleVT();
484
485   // Handle all legal types, i.e. a register that will directly hold this
486   // value.
487   return TLI.isTypeLegal(VT);
488 }
489
490 bool MipsFastISel::isTypeSupported(Type *Ty, MVT &VT) {
491   if (Ty->isVectorTy())
492     return false;
493
494   if (isTypeLegal(Ty, VT))
495     return true;
496
497   // If this is a type than can be sign or zero-extended to a basic operation
498   // go ahead and accept it now.
499   if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
500     return true;
501
502   return false;
503 }
504
505 bool MipsFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
506   if (isTypeLegal(Ty, VT))
507     return true;
508   // We will extend this in a later patch:
509   //   If this is a type than can be sign or zero-extended to a basic operation
510   //   go ahead and accept it now.
511   if (VT == MVT::i8 || VT == MVT::i16)
512     return true;
513   return false;
514 }
515 // Because of how EmitCmp is called with fast-isel, you can
516 // end up with redundant "andi" instructions after the sequences emitted below.
517 // We should try and solve this issue in the future.
518 //
519 bool MipsFastISel::emitCmp(unsigned ResultReg, const CmpInst *CI) {
520   const Value *Left = CI->getOperand(0), *Right = CI->getOperand(1);
521   bool IsUnsigned = CI->isUnsigned();
522   unsigned LeftReg = getRegEnsuringSimpleIntegerWidening(Left, IsUnsigned);
523   if (LeftReg == 0)
524     return false;
525   unsigned RightReg = getRegEnsuringSimpleIntegerWidening(Right, IsUnsigned);
526   if (RightReg == 0)
527     return false;
528   CmpInst::Predicate P = CI->getPredicate();
529
530   switch (P) {
531   default:
532     return false;
533   case CmpInst::ICMP_EQ: {
534     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
535     emitInst(Mips::XOR, TempReg).addReg(LeftReg).addReg(RightReg);
536     emitInst(Mips::SLTiu, ResultReg).addReg(TempReg).addImm(1);
537     break;
538   }
539   case CmpInst::ICMP_NE: {
540     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
541     emitInst(Mips::XOR, TempReg).addReg(LeftReg).addReg(RightReg);
542     emitInst(Mips::SLTu, ResultReg).addReg(Mips::ZERO).addReg(TempReg);
543     break;
544   }
545   case CmpInst::ICMP_UGT: {
546     emitInst(Mips::SLTu, ResultReg).addReg(RightReg).addReg(LeftReg);
547     break;
548   }
549   case CmpInst::ICMP_ULT: {
550     emitInst(Mips::SLTu, ResultReg).addReg(LeftReg).addReg(RightReg);
551     break;
552   }
553   case CmpInst::ICMP_UGE: {
554     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
555     emitInst(Mips::SLTu, TempReg).addReg(LeftReg).addReg(RightReg);
556     emitInst(Mips::XORi, ResultReg).addReg(TempReg).addImm(1);
557     break;
558   }
559   case CmpInst::ICMP_ULE: {
560     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
561     emitInst(Mips::SLTu, TempReg).addReg(RightReg).addReg(LeftReg);
562     emitInst(Mips::XORi, ResultReg).addReg(TempReg).addImm(1);
563     break;
564   }
565   case CmpInst::ICMP_SGT: {
566     emitInst(Mips::SLT, ResultReg).addReg(RightReg).addReg(LeftReg);
567     break;
568   }
569   case CmpInst::ICMP_SLT: {
570     emitInst(Mips::SLT, ResultReg).addReg(LeftReg).addReg(RightReg);
571     break;
572   }
573   case CmpInst::ICMP_SGE: {
574     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
575     emitInst(Mips::SLT, TempReg).addReg(LeftReg).addReg(RightReg);
576     emitInst(Mips::XORi, ResultReg).addReg(TempReg).addImm(1);
577     break;
578   }
579   case CmpInst::ICMP_SLE: {
580     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
581     emitInst(Mips::SLT, TempReg).addReg(RightReg).addReg(LeftReg);
582     emitInst(Mips::XORi, ResultReg).addReg(TempReg).addImm(1);
583     break;
584   }
585   case CmpInst::FCMP_OEQ:
586   case CmpInst::FCMP_UNE:
587   case CmpInst::FCMP_OLT:
588   case CmpInst::FCMP_OLE:
589   case CmpInst::FCMP_OGT:
590   case CmpInst::FCMP_OGE: {
591     if (UnsupportedFPMode)
592       return false;
593     bool IsFloat = Left->getType()->isFloatTy();
594     bool IsDouble = Left->getType()->isDoubleTy();
595     if (!IsFloat && !IsDouble)
596       return false;
597     unsigned Opc, CondMovOpc;
598     switch (P) {
599     case CmpInst::FCMP_OEQ:
600       Opc = IsFloat ? Mips::C_EQ_S : Mips::C_EQ_D32;
601       CondMovOpc = Mips::MOVT_I;
602       break;
603     case CmpInst::FCMP_UNE:
604       Opc = IsFloat ? Mips::C_EQ_S : Mips::C_EQ_D32;
605       CondMovOpc = Mips::MOVF_I;
606       break;
607     case CmpInst::FCMP_OLT:
608       Opc = IsFloat ? Mips::C_OLT_S : Mips::C_OLT_D32;
609       CondMovOpc = Mips::MOVT_I;
610       break;
611     case CmpInst::FCMP_OLE:
612       Opc = IsFloat ? Mips::C_OLE_S : Mips::C_OLE_D32;
613       CondMovOpc = Mips::MOVT_I;
614       break;
615     case CmpInst::FCMP_OGT:
616       Opc = IsFloat ? Mips::C_ULE_S : Mips::C_ULE_D32;
617       CondMovOpc = Mips::MOVF_I;
618       break;
619     case CmpInst::FCMP_OGE:
620       Opc = IsFloat ? Mips::C_ULT_S : Mips::C_ULT_D32;
621       CondMovOpc = Mips::MOVF_I;
622       break;
623     default:
624       llvm_unreachable("Only switching of a subset of CCs.");
625     }
626     unsigned RegWithZero = createResultReg(&Mips::GPR32RegClass);
627     unsigned RegWithOne = createResultReg(&Mips::GPR32RegClass);
628     emitInst(Mips::ADDiu, RegWithZero).addReg(Mips::ZERO).addImm(0);
629     emitInst(Mips::ADDiu, RegWithOne).addReg(Mips::ZERO).addImm(1);
630     emitInst(Opc).addReg(LeftReg).addReg(RightReg).addReg(
631         Mips::FCC0, RegState::ImplicitDefine);
632     MachineInstrBuilder MI = emitInst(CondMovOpc, ResultReg)
633                                  .addReg(RegWithOne)
634                                  .addReg(Mips::FCC0)
635                                  .addReg(RegWithZero, RegState::Implicit);
636     MI->tieOperands(0, 3);
637     break;
638   }
639   }
640   return true;
641 }
642 bool MipsFastISel::emitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
643                             unsigned Alignment) {
644   //
645   // more cases will be handled here in following patches.
646   //
647   unsigned Opc;
648   switch (VT.SimpleTy) {
649   case MVT::i32: {
650     ResultReg = createResultReg(&Mips::GPR32RegClass);
651     Opc = Mips::LW;
652     break;
653   }
654   case MVT::i16: {
655     ResultReg = createResultReg(&Mips::GPR32RegClass);
656     Opc = Mips::LHu;
657     break;
658   }
659   case MVT::i8: {
660     ResultReg = createResultReg(&Mips::GPR32RegClass);
661     Opc = Mips::LBu;
662     break;
663   }
664   case MVT::f32: {
665     if (UnsupportedFPMode)
666       return false;
667     ResultReg = createResultReg(&Mips::FGR32RegClass);
668     Opc = Mips::LWC1;
669     break;
670   }
671   case MVT::f64: {
672     if (UnsupportedFPMode)
673       return false;
674     ResultReg = createResultReg(&Mips::AFGR64RegClass);
675     Opc = Mips::LDC1;
676     break;
677   }
678   default:
679     return false;
680   }
681   if (Addr.isRegBase()) {
682     simplifyAddress(Addr);
683     emitInstLoad(Opc, ResultReg, Addr.getReg(), Addr.getOffset());
684     return true;
685   }
686   if (Addr.isFIBase()) {
687     unsigned FI = Addr.getFI();
688     unsigned Align = 4;
689     unsigned Offset = Addr.getOffset();
690     MachineFrameInfo &MFI = *MF->getFrameInfo();
691     MachineMemOperand *MMO = MF->getMachineMemOperand(
692         MachinePointerInfo::getFixedStack(FI), MachineMemOperand::MOLoad,
693         MFI.getObjectSize(FI), Align);
694     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
695         .addFrameIndex(FI)
696         .addImm(Offset)
697         .addMemOperand(MMO);
698     return true;
699   }
700   return false;
701 }
702
703 bool MipsFastISel::emitStore(MVT VT, unsigned SrcReg, Address &Addr,
704                              unsigned Alignment) {
705   //
706   // more cases will be handled here in following patches.
707   //
708   unsigned Opc;
709   switch (VT.SimpleTy) {
710   case MVT::i8:
711     Opc = Mips::SB;
712     break;
713   case MVT::i16:
714     Opc = Mips::SH;
715     break;
716   case MVT::i32:
717     Opc = Mips::SW;
718     break;
719   case MVT::f32:
720     if (UnsupportedFPMode)
721       return false;
722     Opc = Mips::SWC1;
723     break;
724   case MVT::f64:
725     if (UnsupportedFPMode)
726       return false;
727     Opc = Mips::SDC1;
728     break;
729   default:
730     return false;
731   }
732   if (Addr.isRegBase()) {
733     simplifyAddress(Addr);
734     emitInstStore(Opc, SrcReg, Addr.getReg(), Addr.getOffset());
735     return true;
736   }
737   if (Addr.isFIBase()) {
738     unsigned FI = Addr.getFI();
739     unsigned Align = 4;
740     unsigned Offset = Addr.getOffset();
741     MachineFrameInfo &MFI = *MF->getFrameInfo();
742     MachineMemOperand *MMO = MF->getMachineMemOperand(
743         MachinePointerInfo::getFixedStack(FI), MachineMemOperand::MOLoad,
744         MFI.getObjectSize(FI), Align);
745     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
746         .addReg(SrcReg)
747         .addFrameIndex(FI)
748         .addImm(Offset)
749         .addMemOperand(MMO);
750     return true;
751   }
752   return false;
753 }
754
755 bool MipsFastISel::selectLogicalOp(const Instruction *I) {
756   MVT VT;
757   if (!isTypeSupported(I->getType(), VT))
758     return false;
759
760   unsigned ResultReg;
761   switch (I->getOpcode()) {
762   default:
763     llvm_unreachable("Unexpected instruction.");
764   case Instruction::And:
765     ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
766     break;
767   case Instruction::Or:
768     ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
769     break;
770   case Instruction::Xor:
771     ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
772     break;
773   }
774
775   if (!ResultReg)
776     return false;
777
778   updateValueMap(I, ResultReg);
779   return true;
780 }
781
782 bool MipsFastISel::selectLoad(const Instruction *I) {
783   // Atomic loads need special handling.
784   if (cast<LoadInst>(I)->isAtomic())
785     return false;
786
787   // Verify we have a legal type before going any further.
788   MVT VT;
789   if (!isLoadTypeLegal(I->getType(), VT))
790     return false;
791
792   // See if we can handle this address.
793   Address Addr;
794   if (!computeAddress(I->getOperand(0), Addr))
795     return false;
796
797   unsigned ResultReg;
798   if (!emitLoad(VT, ResultReg, Addr, cast<LoadInst>(I)->getAlignment()))
799     return false;
800   updateValueMap(I, ResultReg);
801   return true;
802 }
803
804 bool MipsFastISel::selectStore(const Instruction *I) {
805   Value *Op0 = I->getOperand(0);
806   unsigned SrcReg = 0;
807
808   // Atomic stores need special handling.
809   if (cast<StoreInst>(I)->isAtomic())
810     return false;
811
812   // Verify we have a legal type before going any further.
813   MVT VT;
814   if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
815     return false;
816
817   // Get the value to be stored into a register.
818   SrcReg = getRegForValue(Op0);
819   if (SrcReg == 0)
820     return false;
821
822   // See if we can handle this address.
823   Address Addr;
824   if (!computeAddress(I->getOperand(1), Addr))
825     return false;
826
827   if (!emitStore(VT, SrcReg, Addr, cast<StoreInst>(I)->getAlignment()))
828     return false;
829   return true;
830 }
831
832 //
833 // This can cause a redundant sltiu to be generated.
834 // FIXME: try and eliminate this in a future patch.
835 //
836 bool MipsFastISel::selectBranch(const Instruction *I) {
837   const BranchInst *BI = cast<BranchInst>(I);
838   MachineBasicBlock *BrBB = FuncInfo.MBB;
839   //
840   // TBB is the basic block for the case where the comparison is true.
841   // FBB is the basic block for the case where the comparison is false.
842   // if (cond) goto TBB
843   // goto FBB
844   // TBB:
845   //
846   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
847   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
848   BI->getCondition();
849   // For now, just try the simplest case where it's fed by a compare.
850   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
851     unsigned CondReg = createResultReg(&Mips::GPR32RegClass);
852     if (!emitCmp(CondReg, CI))
853       return false;
854     BuildMI(*BrBB, FuncInfo.InsertPt, DbgLoc, TII.get(Mips::BGTZ))
855         .addReg(CondReg)
856         .addMBB(TBB);
857     fastEmitBranch(FBB, DbgLoc);
858     FuncInfo.MBB->addSuccessor(TBB);
859     return true;
860   }
861   return false;
862 }
863
864 bool MipsFastISel::selectCmp(const Instruction *I) {
865   const CmpInst *CI = cast<CmpInst>(I);
866   unsigned ResultReg = createResultReg(&Mips::GPR32RegClass);
867   if (!emitCmp(ResultReg, CI))
868     return false;
869   updateValueMap(I, ResultReg);
870   return true;
871 }
872
873 // Attempt to fast-select a floating-point extend instruction.
874 bool MipsFastISel::selectFPExt(const Instruction *I) {
875   if (UnsupportedFPMode)
876     return false;
877   Value *Src = I->getOperand(0);
878   EVT SrcVT = TLI.getValueType(Src->getType(), true);
879   EVT DestVT = TLI.getValueType(I->getType(), true);
880
881   if (SrcVT != MVT::f32 || DestVT != MVT::f64)
882     return false;
883
884   unsigned SrcReg =
885       getRegForValue(Src); // his must be a 32 bit floating point register class
886                            // maybe we should handle this differently
887   if (!SrcReg)
888     return false;
889
890   unsigned DestReg = createResultReg(&Mips::AFGR64RegClass);
891   emitInst(Mips::CVT_D32_S, DestReg).addReg(SrcReg);
892   updateValueMap(I, DestReg);
893   return true;
894 }
895
896 // Attempt to fast-select a floating-point truncate instruction.
897 bool MipsFastISel::selectFPTrunc(const Instruction *I) {
898   if (UnsupportedFPMode)
899     return false;
900   Value *Src = I->getOperand(0);
901   EVT SrcVT = TLI.getValueType(Src->getType(), true);
902   EVT DestVT = TLI.getValueType(I->getType(), true);
903
904   if (SrcVT != MVT::f64 || DestVT != MVT::f32)
905     return false;
906
907   unsigned SrcReg = getRegForValue(Src);
908   if (!SrcReg)
909     return false;
910
911   unsigned DestReg = createResultReg(&Mips::FGR32RegClass);
912   if (!DestReg)
913     return false;
914
915   emitInst(Mips::CVT_S_D32, DestReg).addReg(SrcReg);
916   updateValueMap(I, DestReg);
917   return true;
918 }
919
920 // Attempt to fast-select a floating-point-to-integer conversion.
921 bool MipsFastISel::selectFPToInt(const Instruction *I, bool IsSigned) {
922   if (UnsupportedFPMode)
923     return false;
924   MVT DstVT, SrcVT;
925   if (!IsSigned)
926     return false; // We don't handle this case yet. There is no native
927                   // instruction for this but it can be synthesized.
928   Type *DstTy = I->getType();
929   if (!isTypeLegal(DstTy, DstVT))
930     return false;
931
932   if (DstVT != MVT::i32)
933     return false;
934
935   Value *Src = I->getOperand(0);
936   Type *SrcTy = Src->getType();
937   if (!isTypeLegal(SrcTy, SrcVT))
938     return false;
939
940   if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
941     return false;
942
943   unsigned SrcReg = getRegForValue(Src);
944   if (SrcReg == 0)
945     return false;
946
947   // Determine the opcode for the conversion, which takes place
948   // entirely within FPRs.
949   unsigned DestReg = createResultReg(&Mips::GPR32RegClass);
950   unsigned TempReg = createResultReg(&Mips::FGR32RegClass);
951   unsigned Opc;
952
953   if (SrcVT == MVT::f32)
954     Opc = Mips::TRUNC_W_S;
955   else
956     Opc = Mips::TRUNC_W_D32;
957
958   // Generate the convert.
959   emitInst(Opc, TempReg).addReg(SrcReg);
960
961   emitInst(Mips::MFC1, DestReg).addReg(TempReg);
962
963   updateValueMap(I, DestReg);
964   return true;
965 }
966 //
967 bool MipsFastISel::processCallArgs(CallLoweringInfo &CLI,
968                                    SmallVectorImpl<MVT> &OutVTs,
969                                    unsigned &NumBytes) {
970   CallingConv::ID CC = CLI.CallConv;
971   SmallVector<CCValAssign, 16> ArgLocs;
972   CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
973   CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
974   // Get a count of how many bytes are to be pushed on the stack.
975   NumBytes = CCInfo.getNextStackOffset();
976   // This is the minimum argument area used for A0-A3.
977   if (NumBytes < 16)
978     NumBytes = 16;
979
980   emitInst(Mips::ADJCALLSTACKDOWN).addImm(16);
981   // Process the args.
982   MVT firstMVT;
983   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
984     CCValAssign &VA = ArgLocs[i];
985     const Value *ArgVal = CLI.OutVals[VA.getValNo()];
986     MVT ArgVT = OutVTs[VA.getValNo()];
987
988     if (i == 0) {
989       firstMVT = ArgVT;
990       if (ArgVT == MVT::f32) {
991         VA.convertToReg(Mips::F12);
992       } else if (ArgVT == MVT::f64) {
993         VA.convertToReg(Mips::D6);
994       }
995     } else if (i == 1) {
996       if ((firstMVT == MVT::f32) || (firstMVT == MVT::f64)) {
997         if (ArgVT == MVT::f32) {
998           VA.convertToReg(Mips::F14);
999         } else if (ArgVT == MVT::f64) {
1000           VA.convertToReg(Mips::D7);
1001         }
1002       }
1003     }
1004     if (((ArgVT == MVT::i32) || (ArgVT == MVT::f32) || (ArgVT == MVT::i16) ||
1005          (ArgVT == MVT::i8)) &&
1006         VA.isMemLoc()) {
1007       switch (VA.getLocMemOffset()) {
1008       case 0:
1009         VA.convertToReg(Mips::A0);
1010         break;
1011       case 4:
1012         VA.convertToReg(Mips::A1);
1013         break;
1014       case 8:
1015         VA.convertToReg(Mips::A2);
1016         break;
1017       case 12:
1018         VA.convertToReg(Mips::A3);
1019         break;
1020       default:
1021         break;
1022       }
1023     }
1024     unsigned ArgReg = getRegForValue(ArgVal);
1025     if (!ArgReg)
1026       return false;
1027
1028     // Handle arg promotion: SExt, ZExt, AExt.
1029     switch (VA.getLocInfo()) {
1030     case CCValAssign::Full:
1031       break;
1032     case CCValAssign::AExt:
1033     case CCValAssign::SExt: {
1034       MVT DestVT = VA.getLocVT();
1035       MVT SrcVT = ArgVT;
1036       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
1037       if (!ArgReg)
1038         return false;
1039       break;
1040     }
1041     case CCValAssign::ZExt: {
1042       MVT DestVT = VA.getLocVT();
1043       MVT SrcVT = ArgVT;
1044       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
1045       if (!ArgReg)
1046         return false;
1047       break;
1048     }
1049     default:
1050       llvm_unreachable("Unknown arg promotion!");
1051     }
1052
1053     // Now copy/store arg to correct locations.
1054     if (VA.isRegLoc() && !VA.needsCustom()) {
1055       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1056               TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
1057       CLI.OutRegs.push_back(VA.getLocReg());
1058     } else if (VA.needsCustom()) {
1059       llvm_unreachable("Mips does not use custom args.");
1060       return false;
1061     } else {
1062       //
1063       // FIXME: This path will currently return false. It was copied
1064       // from the AArch64 port and should be essentially fine for Mips too.
1065       // The work to finish up this path will be done in a follow-on patch.
1066       //
1067       assert(VA.isMemLoc() && "Assuming store on stack.");
1068       // Don't emit stores for undef values.
1069       if (isa<UndefValue>(ArgVal))
1070         continue;
1071
1072       // Need to store on the stack.
1073       // FIXME: This alignment is incorrect but this path is disabled
1074       // for now (will return false). We need to determine the right alignment
1075       // based on the normal alignment for the underlying machine type.
1076       //
1077       unsigned ArgSize = RoundUpToAlignment(ArgVT.getSizeInBits(), 4);
1078
1079       unsigned BEAlign = 0;
1080       if (ArgSize < 8 && !Subtarget->isLittle())
1081         BEAlign = 8 - ArgSize;
1082
1083       Address Addr;
1084       Addr.setKind(Address::RegBase);
1085       Addr.setReg(Mips::SP);
1086       Addr.setOffset(VA.getLocMemOffset() + BEAlign);
1087
1088       unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
1089       MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
1090           MachinePointerInfo::getStack(Addr.getOffset()),
1091           MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
1092       (void)(MMO);
1093       // if (!emitStore(ArgVT, ArgReg, Addr, MMO))
1094       return false; // can't store on the stack yet.
1095     }
1096   }
1097
1098   return true;
1099 }
1100
1101 bool MipsFastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
1102                               unsigned NumBytes) {
1103   CallingConv::ID CC = CLI.CallConv;
1104   emitInst(Mips::ADJCALLSTACKUP).addImm(16);
1105   if (RetVT != MVT::isVoid) {
1106     SmallVector<CCValAssign, 16> RVLocs;
1107     CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
1108     CCInfo.AnalyzeCallResult(RetVT, RetCC_Mips);
1109
1110     // Only handle a single return value.
1111     if (RVLocs.size() != 1)
1112       return false;
1113     // Copy all of the result registers out of their specified physreg.
1114     MVT CopyVT = RVLocs[0].getValVT();
1115     // Special handling for extended integers.
1116     if (RetVT == MVT::i1 || RetVT == MVT::i8 || RetVT == MVT::i16)
1117       CopyVT = MVT::i32;
1118
1119     unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
1120     if (!ResultReg)
1121       return false;
1122     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1123             TII.get(TargetOpcode::COPY),
1124             ResultReg).addReg(RVLocs[0].getLocReg());
1125     CLI.InRegs.push_back(RVLocs[0].getLocReg());
1126
1127     CLI.ResultReg = ResultReg;
1128     CLI.NumResultRegs = 1;
1129   }
1130   return true;
1131 }
1132
1133 bool MipsFastISel::fastLowerCall(CallLoweringInfo &CLI) {
1134   CallingConv::ID CC = CLI.CallConv;
1135   bool IsTailCall = CLI.IsTailCall;
1136   bool IsVarArg = CLI.IsVarArg;
1137   const Value *Callee = CLI.Callee;
1138   // const char *SymName = CLI.SymName;
1139
1140   // Allow SelectionDAG isel to handle tail calls.
1141   if (IsTailCall)
1142     return false;
1143
1144   // Let SDISel handle vararg functions.
1145   if (IsVarArg)
1146     return false;
1147
1148   // FIXME: Only handle *simple* calls for now.
1149   MVT RetVT;
1150   if (CLI.RetTy->isVoidTy())
1151     RetVT = MVT::isVoid;
1152   else if (!isTypeSupported(CLI.RetTy, RetVT))
1153     return false;
1154
1155   for (auto Flag : CLI.OutFlags)
1156     if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
1157       return false;
1158
1159   // Set up the argument vectors.
1160   SmallVector<MVT, 16> OutVTs;
1161   OutVTs.reserve(CLI.OutVals.size());
1162
1163   for (auto *Val : CLI.OutVals) {
1164     MVT VT;
1165     if (!isTypeLegal(Val->getType(), VT) &&
1166         !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
1167       return false;
1168
1169     // We don't handle vector parameters yet.
1170     if (VT.isVector() || VT.getSizeInBits() > 64)
1171       return false;
1172
1173     OutVTs.push_back(VT);
1174   }
1175
1176   Address Addr;
1177   if (!computeCallAddress(Callee, Addr))
1178     return false;
1179
1180   // Handle the arguments now that we've gotten them.
1181   unsigned NumBytes;
1182   if (!processCallArgs(CLI, OutVTs, NumBytes))
1183     return false;
1184
1185   // Issue the call.
1186   unsigned DestAddress = materializeGV(Addr.getGlobalValue(), MVT::i32);
1187   emitInst(TargetOpcode::COPY, Mips::T9).addReg(DestAddress);
1188   MachineInstrBuilder MIB =
1189       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Mips::JALR),
1190               Mips::RA).addReg(Mips::T9);
1191
1192   // Add implicit physical register uses to the call.
1193   for (auto Reg : CLI.OutRegs)
1194     MIB.addReg(Reg, RegState::Implicit);
1195
1196   // Add a register mask with the call-preserved registers.
1197   // Proper defs for return values will be added by setPhysRegsDeadExcept().
1198   MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
1199
1200   CLI.Call = MIB;
1201
1202   // Finish off the call including any return values.
1203   return finishCall(CLI, RetVT, NumBytes);
1204 }
1205
1206 bool MipsFastISel::selectRet(const Instruction *I) {
1207   const Function &F = *I->getParent()->getParent();
1208   const ReturnInst *Ret = cast<ReturnInst>(I);
1209
1210   if (!FuncInfo.CanLowerReturn)
1211     return false;
1212
1213   // Build a list of return value registers.
1214   SmallVector<unsigned, 4> RetRegs;
1215
1216   if (Ret->getNumOperands() > 0) {
1217     CallingConv::ID CC = F.getCallingConv();
1218     SmallVector<ISD::OutputArg, 4> Outs;
1219     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1220     // Analyze operands of the call, assigning locations to each operand.
1221     SmallVector<CCValAssign, 16> ValLocs;
1222     MipsCCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs,
1223                        I->getContext());
1224     CCAssignFn *RetCC = RetCC_Mips;
1225     CCInfo.AnalyzeReturn(Outs, RetCC);
1226
1227     // Only handle a single return value for now.
1228     if (ValLocs.size() != 1)
1229       return false;
1230
1231     CCValAssign &VA = ValLocs[0];
1232     const Value *RV = Ret->getOperand(0);
1233
1234     // Don't bother handling odd stuff for now.
1235     if ((VA.getLocInfo() != CCValAssign::Full) &&
1236         (VA.getLocInfo() != CCValAssign::BCvt))
1237       return false;
1238
1239     // Only handle register returns for now.
1240     if (!VA.isRegLoc())
1241       return false;
1242
1243     unsigned Reg = getRegForValue(RV);
1244     if (Reg == 0)
1245       return false;
1246
1247     unsigned SrcReg = Reg + VA.getValNo();
1248     unsigned DestReg = VA.getLocReg();
1249     // Avoid a cross-class copy. This is very unlikely.
1250     if (!MRI.getRegClass(SrcReg)->contains(DestReg))
1251       return false;
1252
1253     EVT RVEVT = TLI.getValueType(RV->getType());
1254     if (!RVEVT.isSimple())
1255       return false;
1256
1257     if (RVEVT.isVector())
1258       return false;
1259
1260     MVT RVVT = RVEVT.getSimpleVT();
1261     if (RVVT == MVT::f128)
1262       return false;
1263
1264     MVT DestVT = VA.getValVT();
1265     // Special handling for extended integers.
1266     if (RVVT != DestVT) {
1267       if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
1268         return false;
1269
1270       if (Outs[0].Flags.isZExt() || Outs[0].Flags.isSExt()) {
1271         bool IsZExt = Outs[0].Flags.isZExt();
1272         SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
1273         if (SrcReg == 0)
1274           return false;
1275       }
1276     }
1277
1278     // Make the copy.
1279     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1280             TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
1281
1282     // Add register to return instruction.
1283     RetRegs.push_back(VA.getLocReg());
1284   }
1285   MachineInstrBuilder MIB = emitInst(Mips::RetRA);
1286   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1287     MIB.addReg(RetRegs[i], RegState::Implicit);
1288   return true;
1289 }
1290
1291 bool MipsFastISel::selectTrunc(const Instruction *I) {
1292   // The high bits for a type smaller than the register size are assumed to be
1293   // undefined.
1294   Value *Op = I->getOperand(0);
1295
1296   EVT SrcVT, DestVT;
1297   SrcVT = TLI.getValueType(Op->getType(), true);
1298   DestVT = TLI.getValueType(I->getType(), true);
1299
1300   if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
1301     return false;
1302   if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
1303     return false;
1304
1305   unsigned SrcReg = getRegForValue(Op);
1306   if (!SrcReg)
1307     return false;
1308
1309   // Because the high bits are undefined, a truncate doesn't generate
1310   // any code.
1311   updateValueMap(I, SrcReg);
1312   return true;
1313 }
1314 bool MipsFastISel::selectIntExt(const Instruction *I) {
1315   Type *DestTy = I->getType();
1316   Value *Src = I->getOperand(0);
1317   Type *SrcTy = Src->getType();
1318
1319   bool isZExt = isa<ZExtInst>(I);
1320   unsigned SrcReg = getRegForValue(Src);
1321   if (!SrcReg)
1322     return false;
1323
1324   EVT SrcEVT, DestEVT;
1325   SrcEVT = TLI.getValueType(SrcTy, true);
1326   DestEVT = TLI.getValueType(DestTy, true);
1327   if (!SrcEVT.isSimple())
1328     return false;
1329   if (!DestEVT.isSimple())
1330     return false;
1331
1332   MVT SrcVT = SrcEVT.getSimpleVT();
1333   MVT DestVT = DestEVT.getSimpleVT();
1334   unsigned ResultReg = createResultReg(&Mips::GPR32RegClass);
1335
1336   if (!emitIntExt(SrcVT, SrcReg, DestVT, ResultReg, isZExt))
1337     return false;
1338   updateValueMap(I, ResultReg);
1339   return true;
1340 }
1341 bool MipsFastISel::emitIntSExt32r1(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1342                                    unsigned DestReg) {
1343   unsigned ShiftAmt;
1344   switch (SrcVT.SimpleTy) {
1345   default:
1346     return false;
1347   case MVT::i8:
1348     ShiftAmt = 24;
1349     break;
1350   case MVT::i16:
1351     ShiftAmt = 16;
1352     break;
1353   }
1354   unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
1355   emitInst(Mips::SLL, TempReg).addReg(SrcReg).addImm(ShiftAmt);
1356   emitInst(Mips::SRA, DestReg).addReg(TempReg).addImm(ShiftAmt);
1357   return true;
1358 }
1359
1360 bool MipsFastISel::emitIntSExt32r2(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1361                                    unsigned DestReg) {
1362   switch (SrcVT.SimpleTy) {
1363   default:
1364     return false;
1365   case MVT::i8:
1366     emitInst(Mips::SEB, DestReg).addReg(SrcReg);
1367     break;
1368   case MVT::i16:
1369     emitInst(Mips::SEH, DestReg).addReg(SrcReg);
1370     break;
1371   }
1372   return true;
1373 }
1374
1375 bool MipsFastISel::emitIntSExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1376                                unsigned DestReg) {
1377   if ((DestVT != MVT::i32) && (DestVT != MVT::i16))
1378     return false;
1379   if (Subtarget->hasMips32r2())
1380     return emitIntSExt32r2(SrcVT, SrcReg, DestVT, DestReg);
1381   return emitIntSExt32r1(SrcVT, SrcReg, DestVT, DestReg);
1382 }
1383
1384 bool MipsFastISel::emitIntZExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1385                                unsigned DestReg) {
1386   switch (SrcVT.SimpleTy) {
1387   default:
1388     return false;
1389   case MVT::i1:
1390     emitInst(Mips::ANDi, DestReg).addReg(SrcReg).addImm(1);
1391     break;
1392   case MVT::i8:
1393     emitInst(Mips::ANDi, DestReg).addReg(SrcReg).addImm(0xff);
1394     break;
1395   case MVT::i16:
1396     emitInst(Mips::ANDi, DestReg).addReg(SrcReg).addImm(0xffff);
1397     break;
1398   }
1399   return true;
1400 }
1401
1402 bool MipsFastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1403                               unsigned DestReg, bool IsZExt) {
1404   // FastISel does not have plumbing to deal with extensions where the SrcVT or
1405   // DestVT are odd things, so test to make sure that they are both types we can
1406   // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
1407   // bail out to SelectionDAG.
1408   if (((DestVT != MVT::i8) && (DestVT != MVT::i16) && (DestVT != MVT::i32)) ||
1409       ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) && (SrcVT != MVT::i16)))
1410     return false;
1411   if (IsZExt)
1412     return emitIntZExt(SrcVT, SrcReg, DestVT, DestReg);
1413   return emitIntSExt(SrcVT, SrcReg, DestVT, DestReg);
1414 }
1415
1416 unsigned MipsFastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1417                                   bool isZExt) {
1418   unsigned DestReg = createResultReg(&Mips::GPR32RegClass);
1419   bool Success = emitIntExt(SrcVT, SrcReg, DestVT, DestReg, isZExt);
1420   return Success ? DestReg : 0;
1421 }
1422
1423 bool MipsFastISel::selectShift(const Instruction *I) {
1424   MVT RetVT;
1425
1426   if (!isTypeSupported(I->getType(), RetVT))
1427     return false;
1428
1429   unsigned ResultReg = createResultReg(&Mips::GPR32RegClass);
1430   if (!ResultReg)
1431     return false;
1432
1433   unsigned Opcode = I->getOpcode();
1434   const Value *Op0 = I->getOperand(0);
1435   unsigned Op0Reg = getRegForValue(Op0);
1436   if (!Op0Reg)
1437     return false;
1438
1439   // If AShr or LShr, then we need to make sure the operand0 is sign extended.
1440   if (Opcode == Instruction::AShr || Opcode == Instruction::LShr) {
1441     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
1442     if (!TempReg)
1443       return false;
1444
1445     MVT Op0MVT = TLI.getValueType(Op0->getType(), true).getSimpleVT();
1446     bool IsZExt = Opcode == Instruction::LShr;
1447     if (!emitIntExt(Op0MVT, Op0Reg, MVT::i32, TempReg, IsZExt))
1448       return false;
1449
1450     Op0Reg = TempReg;
1451   }
1452
1453   if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
1454     uint64_t ShiftVal = C->getZExtValue();
1455
1456     switch (Opcode) {
1457     default:
1458       llvm_unreachable("Unexpected instruction.");
1459     case Instruction::Shl:
1460       Opcode = Mips::SLL;
1461       break;
1462     case Instruction::AShr:
1463       Opcode = Mips::SRA;
1464       break;
1465     case Instruction::LShr:
1466       Opcode = Mips::SRL;
1467       break;
1468     }
1469
1470     emitInst(Opcode, ResultReg).addReg(Op0Reg).addImm(ShiftVal);
1471     updateValueMap(I, ResultReg);
1472     return true;
1473   }
1474
1475   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1476   if (!Op1Reg)
1477     return false;
1478
1479   switch (Opcode) {
1480   default:
1481     llvm_unreachable("Unexpected instruction.");
1482   case Instruction::Shl:
1483     Opcode = Mips::SLLV;
1484     break;
1485   case Instruction::AShr:
1486     Opcode = Mips::SRAV;
1487     break;
1488   case Instruction::LShr:
1489     Opcode = Mips::SRLV;
1490     break;
1491   }
1492
1493   emitInst(Opcode, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1494   updateValueMap(I, ResultReg);
1495   return true;
1496 }
1497
1498 bool MipsFastISel::fastSelectInstruction(const Instruction *I) {
1499   if (!TargetSupported)
1500     return false;
1501   switch (I->getOpcode()) {
1502   default:
1503     break;
1504   case Instruction::Load:
1505     return selectLoad(I);
1506   case Instruction::Store:
1507     return selectStore(I);
1508   case Instruction::Shl:
1509   case Instruction::LShr:
1510   case Instruction::AShr:
1511     return selectShift(I);
1512   case Instruction::And:
1513   case Instruction::Or:
1514   case Instruction::Xor:
1515     return selectLogicalOp(I);
1516   case Instruction::Br:
1517     return selectBranch(I);
1518   case Instruction::Ret:
1519     return selectRet(I);
1520   case Instruction::Trunc:
1521     return selectTrunc(I);
1522   case Instruction::ZExt:
1523   case Instruction::SExt:
1524     return selectIntExt(I);
1525   case Instruction::FPTrunc:
1526     return selectFPTrunc(I);
1527   case Instruction::FPExt:
1528     return selectFPExt(I);
1529   case Instruction::FPToSI:
1530     return selectFPToInt(I, /*isSigned*/ true);
1531   case Instruction::FPToUI:
1532     return selectFPToInt(I, /*isSigned*/ false);
1533   case Instruction::ICmp:
1534   case Instruction::FCmp:
1535     return selectCmp(I);
1536   }
1537   return false;
1538 }
1539
1540 unsigned MipsFastISel::getRegEnsuringSimpleIntegerWidening(const Value *V,
1541                                                            bool IsUnsigned) {
1542   unsigned VReg = getRegForValue(V);
1543   if (VReg == 0)
1544     return 0;
1545   MVT VMVT = TLI.getValueType(V->getType(), true).getSimpleVT();
1546   if ((VMVT == MVT::i8) || (VMVT == MVT::i16)) {
1547     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
1548     if (!emitIntExt(VMVT, VReg, MVT::i32, TempReg, IsUnsigned))
1549       return 0;
1550     VReg = TempReg;
1551   }
1552   return VReg;
1553 }
1554
1555 void MipsFastISel::simplifyAddress(Address &Addr) {
1556   if (!isInt<16>(Addr.getOffset())) {
1557     unsigned TempReg =
1558         materialize32BitInt(Addr.getOffset(), &Mips::GPR32RegClass);
1559     unsigned DestReg = createResultReg(&Mips::GPR32RegClass);
1560     emitInst(Mips::ADDu, DestReg).addReg(TempReg).addReg(Addr.getReg());
1561     Addr.setReg(DestReg);
1562     Addr.setOffset(0);
1563   }
1564 }
1565
1566 namespace llvm {
1567 FastISel *Mips::createFastISel(FunctionLoweringInfo &funcInfo,
1568                                const TargetLibraryInfo *libInfo) {
1569   return new MipsFastISel(funcInfo, libInfo);
1570 }
1571 }