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