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