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