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