LLVM API Documentation

MipsISelLowering.cpp
Go to the documentation of this file.
00001 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the interfaces that Mips uses to lower LLVM code into a
00011 // selection DAG.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 #include "MipsISelLowering.h"
00015 #include "InstPrinter/MipsInstPrinter.h"
00016 #include "MCTargetDesc/MipsBaseInfo.h"
00017 #include "MipsMachineFunction.h"
00018 #include "MipsSubtarget.h"
00019 #include "MipsTargetMachine.h"
00020 #include "MipsTargetObjectFile.h"
00021 #include "llvm/ADT/Statistic.h"
00022 #include "llvm/ADT/StringSwitch.h"
00023 #include "llvm/CodeGen/CallingConvLower.h"
00024 #include "llvm/CodeGen/MachineFrameInfo.h"
00025 #include "llvm/CodeGen/MachineFunction.h"
00026 #include "llvm/CodeGen/MachineInstrBuilder.h"
00027 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00028 #include "llvm/CodeGen/MachineRegisterInfo.h"
00029 #include "llvm/CodeGen/SelectionDAGISel.h"
00030 #include "llvm/CodeGen/ValueTypes.h"
00031 #include "llvm/IR/CallingConv.h"
00032 #include "llvm/IR/DerivedTypes.h"
00033 #include "llvm/IR/GlobalVariable.h"
00034 #include "llvm/Support/CommandLine.h"
00035 #include "llvm/Support/Debug.h"
00036 #include "llvm/Support/ErrorHandling.h"
00037 #include "llvm/Support/raw_ostream.h"
00038 #include <cctype>
00039 
00040 using namespace llvm;
00041 
00042 #define DEBUG_TYPE "mips-lower"
00043 
00044 STATISTIC(NumTailCalls, "Number of tail calls");
00045 
00046 static cl::opt<bool>
00047 LargeGOT("mxgot", cl::Hidden,
00048          cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
00049 
00050 static cl::opt<bool>
00051 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
00052                cl::desc("MIPS: Don't trap on integer division by zero."),
00053                cl::init(false));
00054 
00055 cl::opt<bool>
00056 EnableMipsFastISel("mips-fast-isel", cl::Hidden,
00057   cl::desc("Allow mips-fast-isel to be used"),
00058   cl::init(false));
00059 
00060 static const MCPhysReg O32IntRegs[4] = {
00061   Mips::A0, Mips::A1, Mips::A2, Mips::A3
00062 };
00063 
00064 static const MCPhysReg Mips64IntRegs[8] = {
00065   Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
00066   Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
00067 };
00068 
00069 static const MCPhysReg Mips64DPRegs[8] = {
00070   Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
00071   Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
00072 };
00073 
00074 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode);
00075 
00076 namespace {
00077 class MipsCCState : public CCState {
00078 private:
00079   /// Identify lowered values that originated from f128 arguments and record
00080   /// this for use by RetCC_MipsN.
00081   void
00082   PreAnalyzeCallResultForF128(const SmallVectorImpl<ISD::InputArg> &Ins,
00083                               const TargetLowering::CallLoweringInfo &CLI) {
00084     for (unsigned i = 0; i < Ins.size(); ++i)
00085       OriginalArgWasF128.push_back(
00086           originalTypeIsF128(CLI.RetTy, CLI.Callee.getNode()));
00087   }
00088 
00089   /// Identify lowered values that originated from f128 arguments and record
00090   /// this for use by RetCC_MipsN.
00091   void PreAnalyzeReturnForF128(const SmallVectorImpl<ISD::OutputArg> &Outs) {
00092     const MachineFunction &MF = getMachineFunction();
00093     for (unsigned i = 0; i < Outs.size(); ++i)
00094       OriginalArgWasF128.push_back(
00095           originalTypeIsF128(MF.getFunction()->getReturnType(), nullptr));
00096   }
00097 
00098   /// Records whether the value has been lowered from an f128.
00099   SmallVector<bool, 4> OriginalArgWasF128;
00100 
00101 public:
00102   MipsCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
00103               SmallVectorImpl<CCValAssign> &locs, LLVMContext &C)
00104       : CCState(CC, isVarArg, MF, locs, C) {}
00105 
00106   void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins,
00107                          CCAssignFn Fn,
00108                          const TargetLowering::CallLoweringInfo &CLI) {
00109     PreAnalyzeCallResultForF128(Ins, CLI);
00110     CCState::AnalyzeCallResult(Ins, Fn);
00111     OriginalArgWasF128.clear();
00112   }
00113 
00114   void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
00115                      CCAssignFn Fn) {
00116     PreAnalyzeReturnForF128(Outs);
00117     CCState::AnalyzeReturn(Outs, Fn);
00118     OriginalArgWasF128.clear();
00119   }
00120 
00121   bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &ArgsFlags,
00122                    CCAssignFn Fn) {
00123     PreAnalyzeReturnForF128(ArgsFlags);
00124     bool Return = CCState::CheckReturn(ArgsFlags, Fn);
00125     OriginalArgWasF128.clear();
00126     return Return;
00127   }
00128 
00129   bool WasOriginalArgF128(unsigned ValNo) { return OriginalArgWasF128[ValNo]; }
00130 };
00131 }
00132 
00133 // If I is a shifted mask, set the size (Size) and the first bit of the
00134 // mask (Pos), and return true.
00135 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
00136 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
00137   if (!isShiftedMask_64(I))
00138     return false;
00139 
00140   Size = CountPopulation_64(I);
00141   Pos = countTrailingZeros(I);
00142   return true;
00143 }
00144 
00145 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
00146   MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
00147   return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
00148 }
00149 
00150 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
00151                                           SelectionDAG &DAG,
00152                                           unsigned Flag) const {
00153   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
00154 }
00155 
00156 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
00157                                           SelectionDAG &DAG,
00158                                           unsigned Flag) const {
00159   return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
00160 }
00161 
00162 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
00163                                           SelectionDAG &DAG,
00164                                           unsigned Flag) const {
00165   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
00166 }
00167 
00168 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
00169                                           SelectionDAG &DAG,
00170                                           unsigned Flag) const {
00171   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
00172 }
00173 
00174 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
00175                                           SelectionDAG &DAG,
00176                                           unsigned Flag) const {
00177   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
00178                                    N->getOffset(), Flag);
00179 }
00180 
00181 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
00182   switch (Opcode) {
00183   case MipsISD::JmpLink:           return "MipsISD::JmpLink";
00184   case MipsISD::TailCall:          return "MipsISD::TailCall";
00185   case MipsISD::Hi:                return "MipsISD::Hi";
00186   case MipsISD::Lo:                return "MipsISD::Lo";
00187   case MipsISD::GPRel:             return "MipsISD::GPRel";
00188   case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
00189   case MipsISD::Ret:               return "MipsISD::Ret";
00190   case MipsISD::EH_RETURN:         return "MipsISD::EH_RETURN";
00191   case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
00192   case MipsISD::FPCmp:             return "MipsISD::FPCmp";
00193   case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
00194   case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
00195   case MipsISD::TruncIntFP:        return "MipsISD::TruncIntFP";
00196   case MipsISD::MFHI:              return "MipsISD::MFHI";
00197   case MipsISD::MFLO:              return "MipsISD::MFLO";
00198   case MipsISD::MTLOHI:            return "MipsISD::MTLOHI";
00199   case MipsISD::Mult:              return "MipsISD::Mult";
00200   case MipsISD::Multu:             return "MipsISD::Multu";
00201   case MipsISD::MAdd:              return "MipsISD::MAdd";
00202   case MipsISD::MAddu:             return "MipsISD::MAddu";
00203   case MipsISD::MSub:              return "MipsISD::MSub";
00204   case MipsISD::MSubu:             return "MipsISD::MSubu";
00205   case MipsISD::DivRem:            return "MipsISD::DivRem";
00206   case MipsISD::DivRemU:           return "MipsISD::DivRemU";
00207   case MipsISD::DivRem16:          return "MipsISD::DivRem16";
00208   case MipsISD::DivRemU16:         return "MipsISD::DivRemU16";
00209   case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
00210   case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
00211   case MipsISD::Wrapper:           return "MipsISD::Wrapper";
00212   case MipsISD::Sync:              return "MipsISD::Sync";
00213   case MipsISD::Ext:               return "MipsISD::Ext";
00214   case MipsISD::Ins:               return "MipsISD::Ins";
00215   case MipsISD::LWL:               return "MipsISD::LWL";
00216   case MipsISD::LWR:               return "MipsISD::LWR";
00217   case MipsISD::SWL:               return "MipsISD::SWL";
00218   case MipsISD::SWR:               return "MipsISD::SWR";
00219   case MipsISD::LDL:               return "MipsISD::LDL";
00220   case MipsISD::LDR:               return "MipsISD::LDR";
00221   case MipsISD::SDL:               return "MipsISD::SDL";
00222   case MipsISD::SDR:               return "MipsISD::SDR";
00223   case MipsISD::EXTP:              return "MipsISD::EXTP";
00224   case MipsISD::EXTPDP:            return "MipsISD::EXTPDP";
00225   case MipsISD::EXTR_S_H:          return "MipsISD::EXTR_S_H";
00226   case MipsISD::EXTR_W:            return "MipsISD::EXTR_W";
00227   case MipsISD::EXTR_R_W:          return "MipsISD::EXTR_R_W";
00228   case MipsISD::EXTR_RS_W:         return "MipsISD::EXTR_RS_W";
00229   case MipsISD::SHILO:             return "MipsISD::SHILO";
00230   case MipsISD::MTHLIP:            return "MipsISD::MTHLIP";
00231   case MipsISD::MULT:              return "MipsISD::MULT";
00232   case MipsISD::MULTU:             return "MipsISD::MULTU";
00233   case MipsISD::MADD_DSP:          return "MipsISD::MADD_DSP";
00234   case MipsISD::MADDU_DSP:         return "MipsISD::MADDU_DSP";
00235   case MipsISD::MSUB_DSP:          return "MipsISD::MSUB_DSP";
00236   case MipsISD::MSUBU_DSP:         return "MipsISD::MSUBU_DSP";
00237   case MipsISD::SHLL_DSP:          return "MipsISD::SHLL_DSP";
00238   case MipsISD::SHRA_DSP:          return "MipsISD::SHRA_DSP";
00239   case MipsISD::SHRL_DSP:          return "MipsISD::SHRL_DSP";
00240   case MipsISD::SETCC_DSP:         return "MipsISD::SETCC_DSP";
00241   case MipsISD::SELECT_CC_DSP:     return "MipsISD::SELECT_CC_DSP";
00242   case MipsISD::VALL_ZERO:         return "MipsISD::VALL_ZERO";
00243   case MipsISD::VANY_ZERO:         return "MipsISD::VANY_ZERO";
00244   case MipsISD::VALL_NONZERO:      return "MipsISD::VALL_NONZERO";
00245   case MipsISD::VANY_NONZERO:      return "MipsISD::VANY_NONZERO";
00246   case MipsISD::VCEQ:              return "MipsISD::VCEQ";
00247   case MipsISD::VCLE_S:            return "MipsISD::VCLE_S";
00248   case MipsISD::VCLE_U:            return "MipsISD::VCLE_U";
00249   case MipsISD::VCLT_S:            return "MipsISD::VCLT_S";
00250   case MipsISD::VCLT_U:            return "MipsISD::VCLT_U";
00251   case MipsISD::VSMAX:             return "MipsISD::VSMAX";
00252   case MipsISD::VSMIN:             return "MipsISD::VSMIN";
00253   case MipsISD::VUMAX:             return "MipsISD::VUMAX";
00254   case MipsISD::VUMIN:             return "MipsISD::VUMIN";
00255   case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
00256   case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
00257   case MipsISD::VNOR:              return "MipsISD::VNOR";
00258   case MipsISD::VSHF:              return "MipsISD::VSHF";
00259   case MipsISD::SHF:               return "MipsISD::SHF";
00260   case MipsISD::ILVEV:             return "MipsISD::ILVEV";
00261   case MipsISD::ILVOD:             return "MipsISD::ILVOD";
00262   case MipsISD::ILVL:              return "MipsISD::ILVL";
00263   case MipsISD::ILVR:              return "MipsISD::ILVR";
00264   case MipsISD::PCKEV:             return "MipsISD::PCKEV";
00265   case MipsISD::PCKOD:             return "MipsISD::PCKOD";
00266   case MipsISD::INSVE:             return "MipsISD::INSVE";
00267   default:                         return nullptr;
00268   }
00269 }
00270 
00271 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
00272                                        const MipsSubtarget &STI)
00273     : TargetLowering(TM, new MipsTargetObjectFile()), Subtarget(STI) {
00274   // Mips does not have i1 type, so use i32 for
00275   // setcc operations results (slt, sgt, ...).
00276   setBooleanContents(ZeroOrOneBooleanContent);
00277   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
00278   // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
00279   // does. Integer booleans still use 0 and 1.
00280   if (Subtarget.hasMips32r6())
00281     setBooleanContents(ZeroOrOneBooleanContent,
00282                        ZeroOrNegativeOneBooleanContent);
00283 
00284   // Load extented operations for i1 types must be promoted
00285   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
00286   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
00287   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
00288 
00289   // MIPS doesn't have extending float->double load/store
00290   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
00291   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
00292 
00293   // Used by legalize types to correctly generate the setcc result.
00294   // Without this, every float setcc comes with a AND/OR with the result,
00295   // we don't want this, since the fpcmp result goes to a flag register,
00296   // which is used implicitly by brcond and select operations.
00297   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
00298 
00299   // Mips Custom Operations
00300   setOperationAction(ISD::BR_JT,              MVT::Other, Custom);
00301   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
00302   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
00303   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
00304   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
00305   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
00306   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
00307   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
00308   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
00309   setOperationAction(ISD::SELECT_CC,          MVT::f32,   Custom);
00310   setOperationAction(ISD::SELECT_CC,          MVT::f64,   Custom);
00311   setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
00312   setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
00313   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
00314   setOperationAction(ISD::FCOPYSIGN,          MVT::f32,   Custom);
00315   setOperationAction(ISD::FCOPYSIGN,          MVT::f64,   Custom);
00316   setOperationAction(ISD::FP_TO_SINT,         MVT::i32,   Custom);
00317 
00318   if (Subtarget.isGP64bit()) {
00319     setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
00320     setOperationAction(ISD::BlockAddress,       MVT::i64,   Custom);
00321     setOperationAction(ISD::GlobalTLSAddress,   MVT::i64,   Custom);
00322     setOperationAction(ISD::JumpTable,          MVT::i64,   Custom);
00323     setOperationAction(ISD::ConstantPool,       MVT::i64,   Custom);
00324     setOperationAction(ISD::SELECT,             MVT::i64,   Custom);
00325     setOperationAction(ISD::LOAD,               MVT::i64,   Custom);
00326     setOperationAction(ISD::STORE,              MVT::i64,   Custom);
00327     setOperationAction(ISD::FP_TO_SINT,         MVT::i64,   Custom);
00328   }
00329 
00330   if (!Subtarget.isGP64bit()) {
00331     setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Custom);
00332     setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Custom);
00333     setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Custom);
00334   }
00335 
00336   setOperationAction(ISD::ADD,                MVT::i32,   Custom);
00337   if (Subtarget.isGP64bit())
00338     setOperationAction(ISD::ADD,                MVT::i64,   Custom);
00339 
00340   setOperationAction(ISD::SDIV, MVT::i32, Expand);
00341   setOperationAction(ISD::SREM, MVT::i32, Expand);
00342   setOperationAction(ISD::UDIV, MVT::i32, Expand);
00343   setOperationAction(ISD::UREM, MVT::i32, Expand);
00344   setOperationAction(ISD::SDIV, MVT::i64, Expand);
00345   setOperationAction(ISD::SREM, MVT::i64, Expand);
00346   setOperationAction(ISD::UDIV, MVT::i64, Expand);
00347   setOperationAction(ISD::UREM, MVT::i64, Expand);
00348 
00349   // Operations not directly supported by Mips.
00350   setOperationAction(ISD::BR_CC,             MVT::f32,   Expand);
00351   setOperationAction(ISD::BR_CC,             MVT::f64,   Expand);
00352   setOperationAction(ISD::BR_CC,             MVT::i32,   Expand);
00353   setOperationAction(ISD::BR_CC,             MVT::i64,   Expand);
00354   setOperationAction(ISD::SELECT_CC,         MVT::i32,   Expand);
00355   setOperationAction(ISD::SELECT_CC,         MVT::i64,   Expand);
00356   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
00357   setOperationAction(ISD::UINT_TO_FP,        MVT::i64,   Expand);
00358   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
00359   setOperationAction(ISD::FP_TO_UINT,        MVT::i64,   Expand);
00360   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
00361   if (Subtarget.hasCnMips()) {
00362     setOperationAction(ISD::CTPOP,           MVT::i32,   Legal);
00363     setOperationAction(ISD::CTPOP,           MVT::i64,   Legal);
00364   } else {
00365     setOperationAction(ISD::CTPOP,           MVT::i32,   Expand);
00366     setOperationAction(ISD::CTPOP,           MVT::i64,   Expand);
00367   }
00368   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
00369   setOperationAction(ISD::CTTZ,              MVT::i64,   Expand);
00370   setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i32,   Expand);
00371   setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i64,   Expand);
00372   setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i32,   Expand);
00373   setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i64,   Expand);
00374   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
00375   setOperationAction(ISD::ROTL,              MVT::i64,   Expand);
00376   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,  Expand);
00377   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64,  Expand);
00378 
00379   if (!Subtarget.hasMips32r2())
00380     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
00381 
00382   if (!Subtarget.hasMips64r2())
00383     setOperationAction(ISD::ROTR, MVT::i64,   Expand);
00384 
00385   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
00386   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
00387   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
00388   setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
00389   setOperationAction(ISD::FSINCOS,           MVT::f32,   Expand);
00390   setOperationAction(ISD::FSINCOS,           MVT::f64,   Expand);
00391   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
00392   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
00393   setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
00394   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
00395   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
00396   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
00397   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
00398   setOperationAction(ISD::FMA,               MVT::f32,   Expand);
00399   setOperationAction(ISD::FMA,               MVT::f64,   Expand);
00400   setOperationAction(ISD::FREM,              MVT::f32,   Expand);
00401   setOperationAction(ISD::FREM,              MVT::f64,   Expand);
00402 
00403   setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
00404 
00405   setOperationAction(ISD::VASTART,           MVT::Other, Custom);
00406   setOperationAction(ISD::VAARG,             MVT::Other, Custom);
00407   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
00408   setOperationAction(ISD::VAEND,             MVT::Other, Expand);
00409 
00410   // Use the default for now
00411   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
00412   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
00413 
00414   setOperationAction(ISD::ATOMIC_LOAD,       MVT::i32,    Expand);
00415   setOperationAction(ISD::ATOMIC_LOAD,       MVT::i64,    Expand);
00416   setOperationAction(ISD::ATOMIC_STORE,      MVT::i32,    Expand);
00417   setOperationAction(ISD::ATOMIC_STORE,      MVT::i64,    Expand);
00418 
00419   setInsertFencesForAtomic(true);
00420 
00421   if (!Subtarget.hasMips32r2()) {
00422     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
00423     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
00424   }
00425 
00426   // MIPS16 lacks MIPS32's clz and clo instructions.
00427   if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
00428     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
00429   if (!Subtarget.hasMips64())
00430     setOperationAction(ISD::CTLZ, MVT::i64, Expand);
00431 
00432   if (!Subtarget.hasMips32r2())
00433     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
00434   if (!Subtarget.hasMips64r2())
00435     setOperationAction(ISD::BSWAP, MVT::i64, Expand);
00436 
00437   if (Subtarget.isGP64bit()) {
00438     setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
00439     setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
00440     setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
00441     setTruncStoreAction(MVT::i64, MVT::i32, Custom);
00442   }
00443 
00444   setOperationAction(ISD::TRAP, MVT::Other, Legal);
00445 
00446   setTargetDAGCombine(ISD::SDIVREM);
00447   setTargetDAGCombine(ISD::UDIVREM);
00448   setTargetDAGCombine(ISD::SELECT);
00449   setTargetDAGCombine(ISD::AND);
00450   setTargetDAGCombine(ISD::OR);
00451   setTargetDAGCombine(ISD::ADD);
00452 
00453   setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
00454 
00455   // The arguments on the stack are defined in terms of 4-byte slots on O32
00456   // and 8-byte slots on N32/N64.
00457   setMinStackArgumentAlignment(
00458       (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4);
00459 
00460   setStackPointerRegisterToSaveRestore(Subtarget.isABI_N64() ? Mips::SP_64
00461                                                              : Mips::SP);
00462 
00463   setExceptionPointerRegister(Subtarget.isABI_N64() ? Mips::A0_64 : Mips::A0);
00464   setExceptionSelectorRegister(Subtarget.isABI_N64() ? Mips::A1_64 : Mips::A1);
00465 
00466   MaxStoresPerMemcpy = 16;
00467 
00468   isMicroMips = Subtarget.inMicroMipsMode();
00469 }
00470 
00471 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
00472                                                      const MipsSubtarget &STI) {
00473   if (STI.inMips16Mode())
00474     return llvm::createMips16TargetLowering(TM, STI);
00475 
00476   return llvm::createMipsSETargetLowering(TM, STI);
00477 }
00478 
00479 // Create a fast isel object.
00480 FastISel *
00481 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
00482                                   const TargetLibraryInfo *libInfo) const {
00483   if (!EnableMipsFastISel)
00484     return TargetLowering::createFastISel(funcInfo, libInfo);
00485   return Mips::createFastISel(funcInfo, libInfo);
00486 }
00487 
00488 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
00489   if (!VT.isVector())
00490     return MVT::i32;
00491   return VT.changeVectorElementTypeToInteger();
00492 }
00493 
00494 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
00495                                     TargetLowering::DAGCombinerInfo &DCI,
00496                                     const MipsSubtarget &Subtarget) {
00497   if (DCI.isBeforeLegalizeOps())
00498     return SDValue();
00499 
00500   EVT Ty = N->getValueType(0);
00501   unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
00502   unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
00503   unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
00504                                                   MipsISD::DivRemU16;
00505   SDLoc DL(N);
00506 
00507   SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
00508                                N->getOperand(0), N->getOperand(1));
00509   SDValue InChain = DAG.getEntryNode();
00510   SDValue InGlue = DivRem;
00511 
00512   // insert MFLO
00513   if (N->hasAnyUseOfValue(0)) {
00514     SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
00515                                             InGlue);
00516     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
00517     InChain = CopyFromLo.getValue(1);
00518     InGlue = CopyFromLo.getValue(2);
00519   }
00520 
00521   // insert MFHI
00522   if (N->hasAnyUseOfValue(1)) {
00523     SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
00524                                             HI, Ty, InGlue);
00525     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
00526   }
00527 
00528   return SDValue();
00529 }
00530 
00531 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
00532   switch (CC) {
00533   default: llvm_unreachable("Unknown fp condition code!");
00534   case ISD::SETEQ:
00535   case ISD::SETOEQ: return Mips::FCOND_OEQ;
00536   case ISD::SETUNE: return Mips::FCOND_UNE;
00537   case ISD::SETLT:
00538   case ISD::SETOLT: return Mips::FCOND_OLT;
00539   case ISD::SETGT:
00540   case ISD::SETOGT: return Mips::FCOND_OGT;
00541   case ISD::SETLE:
00542   case ISD::SETOLE: return Mips::FCOND_OLE;
00543   case ISD::SETGE:
00544   case ISD::SETOGE: return Mips::FCOND_OGE;
00545   case ISD::SETULT: return Mips::FCOND_ULT;
00546   case ISD::SETULE: return Mips::FCOND_ULE;
00547   case ISD::SETUGT: return Mips::FCOND_UGT;
00548   case ISD::SETUGE: return Mips::FCOND_UGE;
00549   case ISD::SETUO:  return Mips::FCOND_UN;
00550   case ISD::SETO:   return Mips::FCOND_OR;
00551   case ISD::SETNE:
00552   case ISD::SETONE: return Mips::FCOND_ONE;
00553   case ISD::SETUEQ: return Mips::FCOND_UEQ;
00554   }
00555 }
00556 
00557 
00558 /// This function returns true if the floating point conditional branches and
00559 /// conditional moves which use condition code CC should be inverted.
00560 static bool invertFPCondCodeUser(Mips::CondCode CC) {
00561   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
00562     return false;
00563 
00564   assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
00565          "Illegal Condition Code");
00566 
00567   return true;
00568 }
00569 
00570 // Creates and returns an FPCmp node from a setcc node.
00571 // Returns Op if setcc is not a floating point comparison.
00572 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
00573   // must be a SETCC node
00574   if (Op.getOpcode() != ISD::SETCC)
00575     return Op;
00576 
00577   SDValue LHS = Op.getOperand(0);
00578 
00579   if (!LHS.getValueType().isFloatingPoint())
00580     return Op;
00581 
00582   SDValue RHS = Op.getOperand(1);
00583   SDLoc DL(Op);
00584 
00585   // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
00586   // node if necessary.
00587   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
00588 
00589   return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
00590                      DAG.getConstant(condCodeToFCC(CC), MVT::i32));
00591 }
00592 
00593 // Creates and returns a CMovFPT/F node.
00594 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
00595                             SDValue False, SDLoc DL) {
00596   ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
00597   bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
00598   SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
00599 
00600   return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
00601                      True.getValueType(), True, FCC0, False, Cond);
00602 }
00603 
00604 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
00605                                     TargetLowering::DAGCombinerInfo &DCI,
00606                                     const MipsSubtarget &Subtarget) {
00607   if (DCI.isBeforeLegalizeOps())
00608     return SDValue();
00609 
00610   SDValue SetCC = N->getOperand(0);
00611 
00612   if ((SetCC.getOpcode() != ISD::SETCC) ||
00613       !SetCC.getOperand(0).getValueType().isInteger())
00614     return SDValue();
00615 
00616   SDValue False = N->getOperand(2);
00617   EVT FalseTy = False.getValueType();
00618 
00619   if (!FalseTy.isInteger())
00620     return SDValue();
00621 
00622   ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
00623 
00624   // If the RHS (False) is 0, we swap the order of the operands
00625   // of ISD::SELECT (obviously also inverting the condition) so that we can
00626   // take advantage of conditional moves using the $0 register.
00627   // Example:
00628   //   return (a != 0) ? x : 0;
00629   //     load $reg, x
00630   //     movz $reg, $0, a
00631   if (!FalseC)
00632     return SDValue();
00633 
00634   const SDLoc DL(N);
00635 
00636   if (!FalseC->getZExtValue()) {
00637     ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
00638     SDValue True = N->getOperand(1);
00639 
00640     SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
00641                          SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
00642 
00643     return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
00644   }
00645 
00646   // If both operands are integer constants there's a possibility that we
00647   // can do some interesting optimizations.
00648   SDValue True = N->getOperand(1);
00649   ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
00650 
00651   if (!TrueC || !True.getValueType().isInteger())
00652     return SDValue();
00653 
00654   // We'll also ignore MVT::i64 operands as this optimizations proves
00655   // to be ineffective because of the required sign extensions as the result
00656   // of a SETCC operator is always MVT::i32 for non-vector types.
00657   if (True.getValueType() == MVT::i64)
00658     return SDValue();
00659 
00660   int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
00661 
00662   // 1)  (a < x) ? y : y-1
00663   //  slti $reg1, a, x
00664   //  addiu $reg2, $reg1, y-1
00665   if (Diff == 1)
00666     return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
00667 
00668   // 2)  (a < x) ? y-1 : y
00669   //  slti $reg1, a, x
00670   //  xor $reg1, $reg1, 1
00671   //  addiu $reg2, $reg1, y-1
00672   if (Diff == -1) {
00673     ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
00674     SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
00675                          SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
00676     return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
00677   }
00678 
00679   // Couldn't optimize.
00680   return SDValue();
00681 }
00682 
00683 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
00684                                  TargetLowering::DAGCombinerInfo &DCI,
00685                                  const MipsSubtarget &Subtarget) {
00686   // Pattern match EXT.
00687   //  $dst = and ((sra or srl) $src , pos), (2**size - 1)
00688   //  => ext $dst, $src, size, pos
00689   if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
00690     return SDValue();
00691 
00692   SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
00693   unsigned ShiftRightOpc = ShiftRight.getOpcode();
00694 
00695   // Op's first operand must be a shift right.
00696   if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
00697     return SDValue();
00698 
00699   // The second operand of the shift must be an immediate.
00700   ConstantSDNode *CN;
00701   if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
00702     return SDValue();
00703 
00704   uint64_t Pos = CN->getZExtValue();
00705   uint64_t SMPos, SMSize;
00706 
00707   // Op's second operand must be a shifted mask.
00708   if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
00709       !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
00710     return SDValue();
00711 
00712   // Return if the shifted mask does not start at bit 0 or the sum of its size
00713   // and Pos exceeds the word's size.
00714   EVT ValTy = N->getValueType(0);
00715   if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
00716     return SDValue();
00717 
00718   return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
00719                      ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
00720                      DAG.getConstant(SMSize, MVT::i32));
00721 }
00722 
00723 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
00724                                 TargetLowering::DAGCombinerInfo &DCI,
00725                                 const MipsSubtarget &Subtarget) {
00726   // Pattern match INS.
00727   //  $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
00728   //  where mask1 = (2**size - 1) << pos, mask0 = ~mask1
00729   //  => ins $dst, $src, size, pos, $src1
00730   if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
00731     return SDValue();
00732 
00733   SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
00734   uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
00735   ConstantSDNode *CN;
00736 
00737   // See if Op's first operand matches (and $src1 , mask0).
00738   if (And0.getOpcode() != ISD::AND)
00739     return SDValue();
00740 
00741   if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
00742       !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
00743     return SDValue();
00744 
00745   // See if Op's second operand matches (and (shl $src, pos), mask1).
00746   if (And1.getOpcode() != ISD::AND)
00747     return SDValue();
00748 
00749   if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
00750       !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
00751     return SDValue();
00752 
00753   // The shift masks must have the same position and size.
00754   if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
00755     return SDValue();
00756 
00757   SDValue Shl = And1.getOperand(0);
00758   if (Shl.getOpcode() != ISD::SHL)
00759     return SDValue();
00760 
00761   if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
00762     return SDValue();
00763 
00764   unsigned Shamt = CN->getZExtValue();
00765 
00766   // Return if the shift amount and the first bit position of mask are not the
00767   // same.
00768   EVT ValTy = N->getValueType(0);
00769   if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
00770     return SDValue();
00771 
00772   return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
00773                      DAG.getConstant(SMPos0, MVT::i32),
00774                      DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
00775 }
00776 
00777 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
00778                                  TargetLowering::DAGCombinerInfo &DCI,
00779                                  const MipsSubtarget &Subtarget) {
00780   // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
00781 
00782   if (DCI.isBeforeLegalizeOps())
00783     return SDValue();
00784 
00785   SDValue Add = N->getOperand(1);
00786 
00787   if (Add.getOpcode() != ISD::ADD)
00788     return SDValue();
00789 
00790   SDValue Lo = Add.getOperand(1);
00791 
00792   if ((Lo.getOpcode() != MipsISD::Lo) ||
00793       (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
00794     return SDValue();
00795 
00796   EVT ValTy = N->getValueType(0);
00797   SDLoc DL(N);
00798 
00799   SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
00800                              Add.getOperand(0));
00801   return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
00802 }
00803 
00804 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
00805   const {
00806   SelectionDAG &DAG = DCI.DAG;
00807   unsigned Opc = N->getOpcode();
00808 
00809   switch (Opc) {
00810   default: break;
00811   case ISD::SDIVREM:
00812   case ISD::UDIVREM:
00813     return performDivRemCombine(N, DAG, DCI, Subtarget);
00814   case ISD::SELECT:
00815     return performSELECTCombine(N, DAG, DCI, Subtarget);
00816   case ISD::AND:
00817     return performANDCombine(N, DAG, DCI, Subtarget);
00818   case ISD::OR:
00819     return performORCombine(N, DAG, DCI, Subtarget);
00820   case ISD::ADD:
00821     return performADDCombine(N, DAG, DCI, Subtarget);
00822   }
00823 
00824   return SDValue();
00825 }
00826 
00827 void
00828 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
00829                                           SmallVectorImpl<SDValue> &Results,
00830                                           SelectionDAG &DAG) const {
00831   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
00832 
00833   for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
00834     Results.push_back(Res.getValue(I));
00835 }
00836 
00837 void
00838 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
00839                                        SmallVectorImpl<SDValue> &Results,
00840                                        SelectionDAG &DAG) const {
00841   return LowerOperationWrapper(N, Results, DAG);
00842 }
00843 
00844 SDValue MipsTargetLowering::
00845 LowerOperation(SDValue Op, SelectionDAG &DAG) const
00846 {
00847   switch (Op.getOpcode())
00848   {
00849   case ISD::BR_JT:              return lowerBR_JT(Op, DAG);
00850   case ISD::BRCOND:             return lowerBRCOND(Op, DAG);
00851   case ISD::ConstantPool:       return lowerConstantPool(Op, DAG);
00852   case ISD::GlobalAddress:      return lowerGlobalAddress(Op, DAG);
00853   case ISD::BlockAddress:       return lowerBlockAddress(Op, DAG);
00854   case ISD::GlobalTLSAddress:   return lowerGlobalTLSAddress(Op, DAG);
00855   case ISD::JumpTable:          return lowerJumpTable(Op, DAG);
00856   case ISD::SELECT:             return lowerSELECT(Op, DAG);
00857   case ISD::SELECT_CC:          return lowerSELECT_CC(Op, DAG);
00858   case ISD::SETCC:              return lowerSETCC(Op, DAG);
00859   case ISD::VASTART:            return lowerVASTART(Op, DAG);
00860   case ISD::VAARG:              return lowerVAARG(Op, DAG);
00861   case ISD::FCOPYSIGN:          return lowerFCOPYSIGN(Op, DAG);
00862   case ISD::FRAMEADDR:          return lowerFRAMEADDR(Op, DAG);
00863   case ISD::RETURNADDR:         return lowerRETURNADDR(Op, DAG);
00864   case ISD::EH_RETURN:          return lowerEH_RETURN(Op, DAG);
00865   case ISD::ATOMIC_FENCE:       return lowerATOMIC_FENCE(Op, DAG);
00866   case ISD::SHL_PARTS:          return lowerShiftLeftParts(Op, DAG);
00867   case ISD::SRA_PARTS:          return lowerShiftRightParts(Op, DAG, true);
00868   case ISD::SRL_PARTS:          return lowerShiftRightParts(Op, DAG, false);
00869   case ISD::LOAD:               return lowerLOAD(Op, DAG);
00870   case ISD::STORE:              return lowerSTORE(Op, DAG);
00871   case ISD::ADD:                return lowerADD(Op, DAG);
00872   case ISD::FP_TO_SINT:         return lowerFP_TO_SINT(Op, DAG);
00873   }
00874   return SDValue();
00875 }
00876 
00877 //===----------------------------------------------------------------------===//
00878 //  Lower helper functions
00879 //===----------------------------------------------------------------------===//
00880 
00881 // addLiveIn - This helper function adds the specified physical register to the
00882 // MachineFunction as a live in value.  It also creates a corresponding
00883 // virtual register for it.
00884 static unsigned
00885 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
00886 {
00887   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
00888   MF.getRegInfo().addLiveIn(PReg, VReg);
00889   return VReg;
00890 }
00891 
00892 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
00893                                               MachineBasicBlock &MBB,
00894                                               const TargetInstrInfo &TII,
00895                                               bool Is64Bit) {
00896   if (NoZeroDivCheck)
00897     return &MBB;
00898 
00899   // Insert instruction "teq $divisor_reg, $zero, 7".
00900   MachineBasicBlock::iterator I(MI);
00901   MachineInstrBuilder MIB;
00902   MachineOperand &Divisor = MI->getOperand(2);
00903   MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
00904     .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
00905     .addReg(Mips::ZERO).addImm(7);
00906 
00907   // Use the 32-bit sub-register if this is a 64-bit division.
00908   if (Is64Bit)
00909     MIB->getOperand(0).setSubReg(Mips::sub_32);
00910 
00911   // Clear Divisor's kill flag.
00912   Divisor.setIsKill(false);
00913 
00914   // We would normally delete the original instruction here but in this case
00915   // we only needed to inject an additional instruction rather than replace it.
00916 
00917   return &MBB;
00918 }
00919 
00920 MachineBasicBlock *
00921 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
00922                                                 MachineBasicBlock *BB) const {
00923   switch (MI->getOpcode()) {
00924   default:
00925     llvm_unreachable("Unexpected instr type to insert");
00926   case Mips::ATOMIC_LOAD_ADD_I8:
00927     return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
00928   case Mips::ATOMIC_LOAD_ADD_I16:
00929     return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
00930   case Mips::ATOMIC_LOAD_ADD_I32:
00931     return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
00932   case Mips::ATOMIC_LOAD_ADD_I64:
00933     return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
00934 
00935   case Mips::ATOMIC_LOAD_AND_I8:
00936     return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
00937   case Mips::ATOMIC_LOAD_AND_I16:
00938     return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
00939   case Mips::ATOMIC_LOAD_AND_I32:
00940     return emitAtomicBinary(MI, BB, 4, Mips::AND);
00941   case Mips::ATOMIC_LOAD_AND_I64:
00942     return emitAtomicBinary(MI, BB, 8, Mips::AND64);
00943 
00944   case Mips::ATOMIC_LOAD_OR_I8:
00945     return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
00946   case Mips::ATOMIC_LOAD_OR_I16:
00947     return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
00948   case Mips::ATOMIC_LOAD_OR_I32:
00949     return emitAtomicBinary(MI, BB, 4, Mips::OR);
00950   case Mips::ATOMIC_LOAD_OR_I64:
00951     return emitAtomicBinary(MI, BB, 8, Mips::OR64);
00952 
00953   case Mips::ATOMIC_LOAD_XOR_I8:
00954     return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
00955   case Mips::ATOMIC_LOAD_XOR_I16:
00956     return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
00957   case Mips::ATOMIC_LOAD_XOR_I32:
00958     return emitAtomicBinary(MI, BB, 4, Mips::XOR);
00959   case Mips::ATOMIC_LOAD_XOR_I64:
00960     return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
00961 
00962   case Mips::ATOMIC_LOAD_NAND_I8:
00963     return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
00964   case Mips::ATOMIC_LOAD_NAND_I16:
00965     return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
00966   case Mips::ATOMIC_LOAD_NAND_I32:
00967     return emitAtomicBinary(MI, BB, 4, 0, true);
00968   case Mips::ATOMIC_LOAD_NAND_I64:
00969     return emitAtomicBinary(MI, BB, 8, 0, true);
00970 
00971   case Mips::ATOMIC_LOAD_SUB_I8:
00972     return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
00973   case Mips::ATOMIC_LOAD_SUB_I16:
00974     return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
00975   case Mips::ATOMIC_LOAD_SUB_I32:
00976     return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
00977   case Mips::ATOMIC_LOAD_SUB_I64:
00978     return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
00979 
00980   case Mips::ATOMIC_SWAP_I8:
00981     return emitAtomicBinaryPartword(MI, BB, 1, 0);
00982   case Mips::ATOMIC_SWAP_I16:
00983     return emitAtomicBinaryPartword(MI, BB, 2, 0);
00984   case Mips::ATOMIC_SWAP_I32:
00985     return emitAtomicBinary(MI, BB, 4, 0);
00986   case Mips::ATOMIC_SWAP_I64:
00987     return emitAtomicBinary(MI, BB, 8, 0);
00988 
00989   case Mips::ATOMIC_CMP_SWAP_I8:
00990     return emitAtomicCmpSwapPartword(MI, BB, 1);
00991   case Mips::ATOMIC_CMP_SWAP_I16:
00992     return emitAtomicCmpSwapPartword(MI, BB, 2);
00993   case Mips::ATOMIC_CMP_SWAP_I32:
00994     return emitAtomicCmpSwap(MI, BB, 4);
00995   case Mips::ATOMIC_CMP_SWAP_I64:
00996     return emitAtomicCmpSwap(MI, BB, 8);
00997   case Mips::PseudoSDIV:
00998   case Mips::PseudoUDIV:
00999   case Mips::DIV:
01000   case Mips::DIVU:
01001   case Mips::MOD:
01002   case Mips::MODU:
01003     return insertDivByZeroTrap(
01004         MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), false);
01005   case Mips::PseudoDSDIV:
01006   case Mips::PseudoDUDIV:
01007   case Mips::DDIV:
01008   case Mips::DDIVU:
01009   case Mips::DMOD:
01010   case Mips::DMODU:
01011     return insertDivByZeroTrap(
01012         MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), true);
01013   case Mips::SEL_D:
01014     return emitSEL_D(MI, BB);
01015   }
01016 }
01017 
01018 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
01019 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
01020 MachineBasicBlock *
01021 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
01022                                      unsigned Size, unsigned BinOpcode,
01023                                      bool Nand) const {
01024   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
01025 
01026   MachineFunction *MF = BB->getParent();
01027   MachineRegisterInfo &RegInfo = MF->getRegInfo();
01028   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
01029   const TargetInstrInfo *TII =
01030       getTargetMachine().getSubtargetImpl()->getInstrInfo();
01031   DebugLoc DL = MI->getDebugLoc();
01032   unsigned LL, SC, AND, NOR, ZERO, BEQ;
01033 
01034   if (Size == 4) {
01035     if (isMicroMips) {
01036       LL = Mips::LL_MM;
01037       SC = Mips::SC_MM;
01038     } else {
01039       LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
01040       SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
01041     }
01042     AND = Mips::AND;
01043     NOR = Mips::NOR;
01044     ZERO = Mips::ZERO;
01045     BEQ = Mips::BEQ;
01046   } else {
01047     LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
01048     SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
01049     AND = Mips::AND64;
01050     NOR = Mips::NOR64;
01051     ZERO = Mips::ZERO_64;
01052     BEQ = Mips::BEQ64;
01053   }
01054 
01055   unsigned OldVal = MI->getOperand(0).getReg();
01056   unsigned Ptr = MI->getOperand(1).getReg();
01057   unsigned Incr = MI->getOperand(2).getReg();
01058 
01059   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
01060   unsigned AndRes = RegInfo.createVirtualRegister(RC);
01061   unsigned Success = RegInfo.createVirtualRegister(RC);
01062 
01063   // insert new blocks after the current block
01064   const BasicBlock *LLVM_BB = BB->getBasicBlock();
01065   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01066   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01067   MachineFunction::iterator It = BB;
01068   ++It;
01069   MF->insert(It, loopMBB);
01070   MF->insert(It, exitMBB);
01071 
01072   // Transfer the remainder of BB and its successor edges to exitMBB.
01073   exitMBB->splice(exitMBB->begin(), BB,
01074                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
01075   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
01076 
01077   //  thisMBB:
01078   //    ...
01079   //    fallthrough --> loopMBB
01080   BB->addSuccessor(loopMBB);
01081   loopMBB->addSuccessor(loopMBB);
01082   loopMBB->addSuccessor(exitMBB);
01083 
01084   //  loopMBB:
01085   //    ll oldval, 0(ptr)
01086   //    <binop> storeval, oldval, incr
01087   //    sc success, storeval, 0(ptr)
01088   //    beq success, $0, loopMBB
01089   BB = loopMBB;
01090   BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
01091   if (Nand) {
01092     //  and andres, oldval, incr
01093     //  nor storeval, $0, andres
01094     BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
01095     BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
01096   } else if (BinOpcode) {
01097     //  <binop> storeval, oldval, incr
01098     BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
01099   } else {
01100     StoreVal = Incr;
01101   }
01102   BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
01103   BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
01104 
01105   MI->eraseFromParent(); // The instruction is gone now.
01106 
01107   return exitMBB;
01108 }
01109 
01110 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
01111     MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
01112     unsigned SrcReg) const {
01113   const TargetInstrInfo *TII =
01114       getTargetMachine().getSubtargetImpl()->getInstrInfo();
01115   DebugLoc DL = MI->getDebugLoc();
01116 
01117   if (Subtarget.hasMips32r2() && Size == 1) {
01118     BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
01119     return BB;
01120   }
01121 
01122   if (Subtarget.hasMips32r2() && Size == 2) {
01123     BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
01124     return BB;
01125   }
01126 
01127   MachineFunction *MF = BB->getParent();
01128   MachineRegisterInfo &RegInfo = MF->getRegInfo();
01129   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
01130   unsigned ScrReg = RegInfo.createVirtualRegister(RC);
01131 
01132   assert(Size < 32);
01133   int64_t ShiftImm = 32 - (Size * 8);
01134 
01135   BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
01136   BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
01137 
01138   return BB;
01139 }
01140 
01141 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
01142     MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
01143     bool Nand) const {
01144   assert((Size == 1 || Size == 2) &&
01145          "Unsupported size for EmitAtomicBinaryPartial.");
01146 
01147   MachineFunction *MF = BB->getParent();
01148   MachineRegisterInfo &RegInfo = MF->getRegInfo();
01149   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
01150   const TargetInstrInfo *TII =
01151       getTargetMachine().getSubtargetImpl()->getInstrInfo();
01152   DebugLoc DL = MI->getDebugLoc();
01153 
01154   unsigned Dest = MI->getOperand(0).getReg();
01155   unsigned Ptr = MI->getOperand(1).getReg();
01156   unsigned Incr = MI->getOperand(2).getReg();
01157 
01158   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
01159   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
01160   unsigned Mask = RegInfo.createVirtualRegister(RC);
01161   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
01162   unsigned NewVal = RegInfo.createVirtualRegister(RC);
01163   unsigned OldVal = RegInfo.createVirtualRegister(RC);
01164   unsigned Incr2 = RegInfo.createVirtualRegister(RC);
01165   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
01166   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
01167   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
01168   unsigned AndRes = RegInfo.createVirtualRegister(RC);
01169   unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
01170   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
01171   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
01172   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
01173   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
01174   unsigned Success = RegInfo.createVirtualRegister(RC);
01175 
01176   // insert new blocks after the current block
01177   const BasicBlock *LLVM_BB = BB->getBasicBlock();
01178   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01179   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01180   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01181   MachineFunction::iterator It = BB;
01182   ++It;
01183   MF->insert(It, loopMBB);
01184   MF->insert(It, sinkMBB);
01185   MF->insert(It, exitMBB);
01186 
01187   // Transfer the remainder of BB and its successor edges to exitMBB.
01188   exitMBB->splice(exitMBB->begin(), BB,
01189                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
01190   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
01191 
01192   BB->addSuccessor(loopMBB);
01193   loopMBB->addSuccessor(loopMBB);
01194   loopMBB->addSuccessor(sinkMBB);
01195   sinkMBB->addSuccessor(exitMBB);
01196 
01197   //  thisMBB:
01198   //    addiu   masklsb2,$0,-4                # 0xfffffffc
01199   //    and     alignedaddr,ptr,masklsb2
01200   //    andi    ptrlsb2,ptr,3
01201   //    sll     shiftamt,ptrlsb2,3
01202   //    ori     maskupper,$0,255               # 0xff
01203   //    sll     mask,maskupper,shiftamt
01204   //    nor     mask2,$0,mask
01205   //    sll     incr2,incr,shiftamt
01206 
01207   int64_t MaskImm = (Size == 1) ? 255 : 65535;
01208   BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
01209     .addReg(Mips::ZERO).addImm(-4);
01210   BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
01211     .addReg(Ptr).addReg(MaskLSB2);
01212   BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
01213   if (Subtarget.isLittle()) {
01214     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
01215   } else {
01216     unsigned Off = RegInfo.createVirtualRegister(RC);
01217     BuildMI(BB, DL, TII->get(Mips::XORi), Off)
01218       .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
01219     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
01220   }
01221   BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
01222     .addReg(Mips::ZERO).addImm(MaskImm);
01223   BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
01224     .addReg(MaskUpper).addReg(ShiftAmt);
01225   BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
01226   BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
01227 
01228   // atomic.load.binop
01229   // loopMBB:
01230   //   ll      oldval,0(alignedaddr)
01231   //   binop   binopres,oldval,incr2
01232   //   and     newval,binopres,mask
01233   //   and     maskedoldval0,oldval,mask2
01234   //   or      storeval,maskedoldval0,newval
01235   //   sc      success,storeval,0(alignedaddr)
01236   //   beq     success,$0,loopMBB
01237 
01238   // atomic.swap
01239   // loopMBB:
01240   //   ll      oldval,0(alignedaddr)
01241   //   and     newval,incr2,mask
01242   //   and     maskedoldval0,oldval,mask2
01243   //   or      storeval,maskedoldval0,newval
01244   //   sc      success,storeval,0(alignedaddr)
01245   //   beq     success,$0,loopMBB
01246 
01247   BB = loopMBB;
01248   BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
01249   if (Nand) {
01250     //  and andres, oldval, incr2
01251     //  nor binopres, $0, andres
01252     //  and newval, binopres, mask
01253     BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
01254     BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
01255       .addReg(Mips::ZERO).addReg(AndRes);
01256     BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
01257   } else if (BinOpcode) {
01258     //  <binop> binopres, oldval, incr2
01259     //  and newval, binopres, mask
01260     BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
01261     BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
01262   } else { // atomic.swap
01263     //  and newval, incr2, mask
01264     BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
01265   }
01266 
01267   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
01268     .addReg(OldVal).addReg(Mask2);
01269   BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
01270     .addReg(MaskedOldVal0).addReg(NewVal);
01271   BuildMI(BB, DL, TII->get(Mips::SC), Success)
01272     .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
01273   BuildMI(BB, DL, TII->get(Mips::BEQ))
01274     .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
01275 
01276   //  sinkMBB:
01277   //    and     maskedoldval1,oldval,mask
01278   //    srl     srlres,maskedoldval1,shiftamt
01279   //    sign_extend dest,srlres
01280   BB = sinkMBB;
01281 
01282   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
01283     .addReg(OldVal).addReg(Mask);
01284   BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
01285       .addReg(MaskedOldVal1).addReg(ShiftAmt);
01286   BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
01287 
01288   MI->eraseFromParent(); // The instruction is gone now.
01289 
01290   return exitMBB;
01291 }
01292 
01293 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
01294                                                           MachineBasicBlock *BB,
01295                                                           unsigned Size) const {
01296   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
01297 
01298   MachineFunction *MF = BB->getParent();
01299   MachineRegisterInfo &RegInfo = MF->getRegInfo();
01300   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
01301   const TargetInstrInfo *TII =
01302       getTargetMachine().getSubtargetImpl()->getInstrInfo();
01303   DebugLoc DL = MI->getDebugLoc();
01304   unsigned LL, SC, ZERO, BNE, BEQ;
01305 
01306   if (Size == 4) {
01307     LL = isMicroMips ? Mips::LL_MM : Mips::LL;
01308     SC = isMicroMips ? Mips::SC_MM : Mips::SC;
01309     ZERO = Mips::ZERO;
01310     BNE = Mips::BNE;
01311     BEQ = Mips::BEQ;
01312   } else {
01313     LL = Mips::LLD;
01314     SC = Mips::SCD;
01315     ZERO = Mips::ZERO_64;
01316     BNE = Mips::BNE64;
01317     BEQ = Mips::BEQ64;
01318   }
01319 
01320   unsigned Dest    = MI->getOperand(0).getReg();
01321   unsigned Ptr     = MI->getOperand(1).getReg();
01322   unsigned OldVal  = MI->getOperand(2).getReg();
01323   unsigned NewVal  = MI->getOperand(3).getReg();
01324 
01325   unsigned Success = RegInfo.createVirtualRegister(RC);
01326 
01327   // insert new blocks after the current block
01328   const BasicBlock *LLVM_BB = BB->getBasicBlock();
01329   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
01330   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
01331   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01332   MachineFunction::iterator It = BB;
01333   ++It;
01334   MF->insert(It, loop1MBB);
01335   MF->insert(It, loop2MBB);
01336   MF->insert(It, exitMBB);
01337 
01338   // Transfer the remainder of BB and its successor edges to exitMBB.
01339   exitMBB->splice(exitMBB->begin(), BB,
01340                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
01341   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
01342 
01343   //  thisMBB:
01344   //    ...
01345   //    fallthrough --> loop1MBB
01346   BB->addSuccessor(loop1MBB);
01347   loop1MBB->addSuccessor(exitMBB);
01348   loop1MBB->addSuccessor(loop2MBB);
01349   loop2MBB->addSuccessor(loop1MBB);
01350   loop2MBB->addSuccessor(exitMBB);
01351 
01352   // loop1MBB:
01353   //   ll dest, 0(ptr)
01354   //   bne dest, oldval, exitMBB
01355   BB = loop1MBB;
01356   BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
01357   BuildMI(BB, DL, TII->get(BNE))
01358     .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
01359 
01360   // loop2MBB:
01361   //   sc success, newval, 0(ptr)
01362   //   beq success, $0, loop1MBB
01363   BB = loop2MBB;
01364   BuildMI(BB, DL, TII->get(SC), Success)
01365     .addReg(NewVal).addReg(Ptr).addImm(0);
01366   BuildMI(BB, DL, TII->get(BEQ))
01367     .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
01368 
01369   MI->eraseFromParent(); // The instruction is gone now.
01370 
01371   return exitMBB;
01372 }
01373 
01374 MachineBasicBlock *
01375 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
01376                                               MachineBasicBlock *BB,
01377                                               unsigned Size) const {
01378   assert((Size == 1 || Size == 2) &&
01379       "Unsupported size for EmitAtomicCmpSwapPartial.");
01380 
01381   MachineFunction *MF = BB->getParent();
01382   MachineRegisterInfo &RegInfo = MF->getRegInfo();
01383   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
01384   const TargetInstrInfo *TII =
01385       getTargetMachine().getSubtargetImpl()->getInstrInfo();
01386   DebugLoc DL = MI->getDebugLoc();
01387 
01388   unsigned Dest    = MI->getOperand(0).getReg();
01389   unsigned Ptr     = MI->getOperand(1).getReg();
01390   unsigned CmpVal  = MI->getOperand(2).getReg();
01391   unsigned NewVal  = MI->getOperand(3).getReg();
01392 
01393   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
01394   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
01395   unsigned Mask = RegInfo.createVirtualRegister(RC);
01396   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
01397   unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
01398   unsigned OldVal = RegInfo.createVirtualRegister(RC);
01399   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
01400   unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
01401   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
01402   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
01403   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
01404   unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
01405   unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
01406   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
01407   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
01408   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
01409   unsigned Success = RegInfo.createVirtualRegister(RC);
01410 
01411   // insert new blocks after the current block
01412   const BasicBlock *LLVM_BB = BB->getBasicBlock();
01413   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
01414   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
01415   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01416   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01417   MachineFunction::iterator It = BB;
01418   ++It;
01419   MF->insert(It, loop1MBB);
01420   MF->insert(It, loop2MBB);
01421   MF->insert(It, sinkMBB);
01422   MF->insert(It, exitMBB);
01423 
01424   // Transfer the remainder of BB and its successor edges to exitMBB.
01425   exitMBB->splice(exitMBB->begin(), BB,
01426                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
01427   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
01428 
01429   BB->addSuccessor(loop1MBB);
01430   loop1MBB->addSuccessor(sinkMBB);
01431   loop1MBB->addSuccessor(loop2MBB);
01432   loop2MBB->addSuccessor(loop1MBB);
01433   loop2MBB->addSuccessor(sinkMBB);
01434   sinkMBB->addSuccessor(exitMBB);
01435 
01436   // FIXME: computation of newval2 can be moved to loop2MBB.
01437   //  thisMBB:
01438   //    addiu   masklsb2,$0,-4                # 0xfffffffc
01439   //    and     alignedaddr,ptr,masklsb2
01440   //    andi    ptrlsb2,ptr,3
01441   //    sll     shiftamt,ptrlsb2,3
01442   //    ori     maskupper,$0,255               # 0xff
01443   //    sll     mask,maskupper,shiftamt
01444   //    nor     mask2,$0,mask
01445   //    andi    maskedcmpval,cmpval,255
01446   //    sll     shiftedcmpval,maskedcmpval,shiftamt
01447   //    andi    maskednewval,newval,255
01448   //    sll     shiftednewval,maskednewval,shiftamt
01449   int64_t MaskImm = (Size == 1) ? 255 : 65535;
01450   BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
01451     .addReg(Mips::ZERO).addImm(-4);
01452   BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
01453     .addReg(Ptr).addReg(MaskLSB2);
01454   BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
01455   if (Subtarget.isLittle()) {
01456     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
01457   } else {
01458     unsigned Off = RegInfo.createVirtualRegister(RC);
01459     BuildMI(BB, DL, TII->get(Mips::XORi), Off)
01460       .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
01461     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
01462   }
01463   BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
01464     .addReg(Mips::ZERO).addImm(MaskImm);
01465   BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
01466     .addReg(MaskUpper).addReg(ShiftAmt);
01467   BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
01468   BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
01469     .addReg(CmpVal).addImm(MaskImm);
01470   BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
01471     .addReg(MaskedCmpVal).addReg(ShiftAmt);
01472   BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
01473     .addReg(NewVal).addImm(MaskImm);
01474   BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
01475     .addReg(MaskedNewVal).addReg(ShiftAmt);
01476 
01477   //  loop1MBB:
01478   //    ll      oldval,0(alginedaddr)
01479   //    and     maskedoldval0,oldval,mask
01480   //    bne     maskedoldval0,shiftedcmpval,sinkMBB
01481   BB = loop1MBB;
01482   BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
01483   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
01484     .addReg(OldVal).addReg(Mask);
01485   BuildMI(BB, DL, TII->get(Mips::BNE))
01486     .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
01487 
01488   //  loop2MBB:
01489   //    and     maskedoldval1,oldval,mask2
01490   //    or      storeval,maskedoldval1,shiftednewval
01491   //    sc      success,storeval,0(alignedaddr)
01492   //    beq     success,$0,loop1MBB
01493   BB = loop2MBB;
01494   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
01495     .addReg(OldVal).addReg(Mask2);
01496   BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
01497     .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
01498   BuildMI(BB, DL, TII->get(Mips::SC), Success)
01499       .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
01500   BuildMI(BB, DL, TII->get(Mips::BEQ))
01501       .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
01502 
01503   //  sinkMBB:
01504   //    srl     srlres,maskedoldval0,shiftamt
01505   //    sign_extend dest,srlres
01506   BB = sinkMBB;
01507 
01508   BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
01509       .addReg(MaskedOldVal0).addReg(ShiftAmt);
01510   BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
01511 
01512   MI->eraseFromParent();   // The instruction is gone now.
01513 
01514   return exitMBB;
01515 }
01516 
01517 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
01518                                                  MachineBasicBlock *BB) const {
01519   MachineFunction *MF = BB->getParent();
01520   const TargetRegisterInfo *TRI =
01521       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
01522   const TargetInstrInfo *TII =
01523       getTargetMachine().getSubtargetImpl()->getInstrInfo();
01524   MachineRegisterInfo &RegInfo = MF->getRegInfo();
01525   DebugLoc DL = MI->getDebugLoc();
01526   MachineBasicBlock::iterator II(MI);
01527 
01528   unsigned Fc = MI->getOperand(1).getReg();
01529   const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
01530 
01531   unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
01532 
01533   BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
01534       .addImm(0)
01535       .addReg(Fc)
01536       .addImm(Mips::sub_lo);
01537 
01538   // We don't erase the original instruction, we just replace the condition
01539   // register with the 64-bit super-register.
01540   MI->getOperand(1).setReg(Fc2);
01541 
01542   return BB;
01543 }
01544 
01545 //===----------------------------------------------------------------------===//
01546 //  Misc Lower Operation implementation
01547 //===----------------------------------------------------------------------===//
01548 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
01549   SDValue Chain = Op.getOperand(0);
01550   SDValue Table = Op.getOperand(1);
01551   SDValue Index = Op.getOperand(2);
01552   SDLoc DL(Op);
01553   EVT PTy = getPointerTy();
01554   unsigned EntrySize =
01555     DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
01556 
01557   Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
01558                       DAG.getConstant(EntrySize, PTy));
01559   SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
01560 
01561   EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
01562   Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
01563                         MachinePointerInfo::getJumpTable(), MemVT, false, false,
01564                         false, 0);
01565   Chain = Addr.getValue(1);
01566 
01567   if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) ||
01568       Subtarget.isABI_N64()) {
01569     // For PIC, the sequence is:
01570     // BRIND(load(Jumptable + index) + RelocBase)
01571     // RelocBase can be JumpTable, GOT or some sort of global base.
01572     Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
01573                        getPICJumpTableRelocBase(Table, DAG));
01574   }
01575 
01576   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
01577 }
01578 
01579 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
01580   // The first operand is the chain, the second is the condition, the third is
01581   // the block to branch to if the condition is true.
01582   SDValue Chain = Op.getOperand(0);
01583   SDValue Dest = Op.getOperand(2);
01584   SDLoc DL(Op);
01585 
01586   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
01587   SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
01588 
01589   // Return if flag is not set by a floating point comparison.
01590   if (CondRes.getOpcode() != MipsISD::FPCmp)
01591     return Op;
01592 
01593   SDValue CCNode  = CondRes.getOperand(2);
01594   Mips::CondCode CC =
01595     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
01596   unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
01597   SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
01598   SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
01599   return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
01600                      FCC0, Dest, CondRes);
01601 }
01602 
01603 SDValue MipsTargetLowering::
01604 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
01605 {
01606   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
01607   SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
01608 
01609   // Return if flag is not set by a floating point comparison.
01610   if (Cond.getOpcode() != MipsISD::FPCmp)
01611     return Op;
01612 
01613   return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
01614                       SDLoc(Op));
01615 }
01616 
01617 SDValue MipsTargetLowering::
01618 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
01619 {
01620   SDLoc DL(Op);
01621   EVT Ty = Op.getOperand(0).getValueType();
01622   SDValue Cond = DAG.getNode(ISD::SETCC, DL,
01623                              getSetCCResultType(*DAG.getContext(), Ty),
01624                              Op.getOperand(0), Op.getOperand(1),
01625                              Op.getOperand(4));
01626 
01627   return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
01628                      Op.getOperand(3));
01629 }
01630 
01631 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
01632   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
01633   SDValue Cond = createFPCmp(DAG, Op);
01634 
01635   assert(Cond.getOpcode() == MipsISD::FPCmp &&
01636          "Floating point operand expected.");
01637 
01638   SDValue True  = DAG.getConstant(1, MVT::i32);
01639   SDValue False = DAG.getConstant(0, MVT::i32);
01640 
01641   return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
01642 }
01643 
01644 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
01645                                                SelectionDAG &DAG) const {
01646   // FIXME there isn't actually debug info here
01647   SDLoc DL(Op);
01648   EVT Ty = Op.getValueType();
01649   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
01650   const GlobalValue *GV = N->getGlobal();
01651 
01652   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
01653       !Subtarget.isABI_N64()) {
01654     const MipsTargetObjectFile &TLOF =
01655       (const MipsTargetObjectFile&)getObjFileLowering();
01656 
01657     // %gp_rel relocation
01658     if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
01659       SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
01660                                               MipsII::MO_GPREL);
01661       SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
01662                                       DAG.getVTList(MVT::i32), GA);
01663       SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
01664       return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
01665     }
01666 
01667     // %hi/%lo relocation
01668     return getAddrNonPIC(N, Ty, DAG);
01669   }
01670 
01671   if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
01672     return getAddrLocal(N, Ty, DAG,
01673                         Subtarget.isABI_N32() || Subtarget.isABI_N64());
01674 
01675   if (LargeGOT)
01676     return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
01677                                  MipsII::MO_GOT_LO16, DAG.getEntryNode(),
01678                                  MachinePointerInfo::getGOT());
01679 
01680   return getAddrGlobal(N, Ty, DAG,
01681                        (Subtarget.isABI_N32() || Subtarget.isABI_N64())
01682                            ? MipsII::MO_GOT_DISP
01683                            : MipsII::MO_GOT16,
01684                        DAG.getEntryNode(), MachinePointerInfo::getGOT());
01685 }
01686 
01687 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
01688                                               SelectionDAG &DAG) const {
01689   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
01690   EVT Ty = Op.getValueType();
01691 
01692   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
01693       !Subtarget.isABI_N64())
01694     return getAddrNonPIC(N, Ty, DAG);
01695 
01696   return getAddrLocal(N, Ty, DAG,
01697                       Subtarget.isABI_N32() || Subtarget.isABI_N64());
01698 }
01699 
01700 SDValue MipsTargetLowering::
01701 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
01702 {
01703   // If the relocation model is PIC, use the General Dynamic TLS Model or
01704   // Local Dynamic TLS model, otherwise use the Initial Exec or
01705   // Local Exec TLS Model.
01706 
01707   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
01708   SDLoc DL(GA);
01709   const GlobalValue *GV = GA->getGlobal();
01710   EVT PtrVT = getPointerTy();
01711 
01712   TLSModel::Model model = getTargetMachine().getTLSModel(GV);
01713 
01714   if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
01715     // General Dynamic and Local Dynamic TLS Model.
01716     unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
01717                                                       : MipsII::MO_TLSGD;
01718 
01719     SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
01720     SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
01721                                    getGlobalReg(DAG, PtrVT), TGA);
01722     unsigned PtrSize = PtrVT.getSizeInBits();
01723     IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
01724 
01725     SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
01726 
01727     ArgListTy Args;
01728     ArgListEntry Entry;
01729     Entry.Node = Argument;
01730     Entry.Ty = PtrTy;
01731     Args.push_back(Entry);
01732 
01733     TargetLowering::CallLoweringInfo CLI(DAG);
01734     CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
01735       .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
01736     std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
01737 
01738     SDValue Ret = CallResult.first;
01739 
01740     if (model != TLSModel::LocalDynamic)
01741       return Ret;
01742 
01743     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
01744                                                MipsII::MO_DTPREL_HI);
01745     SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
01746     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
01747                                                MipsII::MO_DTPREL_LO);
01748     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
01749     SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
01750     return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
01751   }
01752 
01753   SDValue Offset;
01754   if (model == TLSModel::InitialExec) {
01755     // Initial Exec TLS Model
01756     SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
01757                                              MipsII::MO_GOTTPREL);
01758     TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
01759                       TGA);
01760     Offset = DAG.getLoad(PtrVT, DL,
01761                          DAG.getEntryNode(), TGA, MachinePointerInfo(),
01762                          false, false, false, 0);
01763   } else {
01764     // Local Exec TLS Model
01765     assert(model == TLSModel::LocalExec);
01766     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
01767                                                MipsII::MO_TPREL_HI);
01768     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
01769                                                MipsII::MO_TPREL_LO);
01770     SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
01771     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
01772     Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
01773   }
01774 
01775   SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
01776   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
01777 }
01778 
01779 SDValue MipsTargetLowering::
01780 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
01781 {
01782   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
01783   EVT Ty = Op.getValueType();
01784 
01785   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
01786       !Subtarget.isABI_N64())
01787     return getAddrNonPIC(N, Ty, DAG);
01788 
01789   return getAddrLocal(N, Ty, DAG,
01790                       Subtarget.isABI_N32() || Subtarget.isABI_N64());
01791 }
01792 
01793 SDValue MipsTargetLowering::
01794 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
01795 {
01796   // gp_rel relocation
01797   // FIXME: we should reference the constant pool using small data sections,
01798   // but the asm printer currently doesn't support this feature without
01799   // hacking it. This feature should come soon so we can uncomment the
01800   // stuff below.
01801   //if (IsInSmallSection(C->getType())) {
01802   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
01803   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
01804   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
01805   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
01806   EVT Ty = Op.getValueType();
01807 
01808   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
01809       !Subtarget.isABI_N64())
01810     return getAddrNonPIC(N, Ty, DAG);
01811 
01812   return getAddrLocal(N, Ty, DAG,
01813                       Subtarget.isABI_N32() || Subtarget.isABI_N64());
01814 }
01815 
01816 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
01817   MachineFunction &MF = DAG.getMachineFunction();
01818   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
01819 
01820   SDLoc DL(Op);
01821   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
01822                                  getPointerTy());
01823 
01824   // vastart just stores the address of the VarArgsFrameIndex slot into the
01825   // memory location argument.
01826   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
01827   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
01828                       MachinePointerInfo(SV), false, false, 0);
01829 }
01830 
01831 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
01832   SDNode *Node = Op.getNode();
01833   EVT VT = Node->getValueType(0);
01834   SDValue Chain = Node->getOperand(0);
01835   SDValue VAListPtr = Node->getOperand(1);
01836   unsigned Align = Node->getConstantOperandVal(3);
01837   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
01838   SDLoc DL(Node);
01839   unsigned ArgSlotSizeInBytes =
01840       (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4;
01841 
01842   SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
01843                                    MachinePointerInfo(SV), false, false, false,
01844                                    0);
01845   SDValue VAList = VAListLoad;
01846 
01847   // Re-align the pointer if necessary.
01848   // It should only ever be necessary for 64-bit types on O32 since the minimum
01849   // argument alignment is the same as the maximum type alignment for N32/N64.
01850   //
01851   // FIXME: We currently align too often. The code generator doesn't notice
01852   //        when the pointer is still aligned from the last va_arg (or pair of
01853   //        va_args for the i64 on O32 case).
01854   if (Align > getMinStackArgumentAlignment()) {
01855     assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
01856 
01857     VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
01858                          DAG.getConstant(Align - 1,
01859                                          VAList.getValueType()));
01860 
01861     VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
01862                          DAG.getConstant(-(int64_t)Align,
01863                                          VAList.getValueType()));
01864   }
01865 
01866   // Increment the pointer, VAList, to the next vaarg.
01867   unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
01868   SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
01869                              DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes, ArgSlotSizeInBytes),
01870                                              VAList.getValueType()));
01871   // Store the incremented VAList to the legalized pointer
01872   Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
01873                       MachinePointerInfo(SV), false, false, 0);
01874 
01875   // In big-endian mode we must adjust the pointer when the load size is smaller
01876   // than the argument slot size. We must also reduce the known alignment to
01877   // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
01878   // the correct half of the slot, and reduce the alignment from 8 (slot
01879   // alignment) down to 4 (type alignment).
01880   if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
01881     unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
01882     VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
01883                          DAG.getIntPtrConstant(Adjustment));
01884   }
01885   // Load the actual argument out of the pointer VAList
01886   return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
01887                      false, 0);
01888 }
01889 
01890 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
01891                                 bool HasExtractInsert) {
01892   EVT TyX = Op.getOperand(0).getValueType();
01893   EVT TyY = Op.getOperand(1).getValueType();
01894   SDValue Const1 = DAG.getConstant(1, MVT::i32);
01895   SDValue Const31 = DAG.getConstant(31, MVT::i32);
01896   SDLoc DL(Op);
01897   SDValue Res;
01898 
01899   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
01900   // to i32.
01901   SDValue X = (TyX == MVT::f32) ?
01902     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
01903     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
01904                 Const1);
01905   SDValue Y = (TyY == MVT::f32) ?
01906     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
01907     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
01908                 Const1);
01909 
01910   if (HasExtractInsert) {
01911     // ext  E, Y, 31, 1  ; extract bit31 of Y
01912     // ins  X, E, 31, 1  ; insert extracted bit at bit31 of X
01913     SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
01914     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
01915   } else {
01916     // sll SllX, X, 1
01917     // srl SrlX, SllX, 1
01918     // srl SrlY, Y, 31
01919     // sll SllY, SrlX, 31
01920     // or  Or, SrlX, SllY
01921     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
01922     SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
01923     SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
01924     SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
01925     Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
01926   }
01927 
01928   if (TyX == MVT::f32)
01929     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
01930 
01931   SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
01932                              Op.getOperand(0), DAG.getConstant(0, MVT::i32));
01933   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
01934 }
01935 
01936 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
01937                                 bool HasExtractInsert) {
01938   unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
01939   unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
01940   EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
01941   SDValue Const1 = DAG.getConstant(1, MVT::i32);
01942   SDLoc DL(Op);
01943 
01944   // Bitcast to integer nodes.
01945   SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
01946   SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
01947 
01948   if (HasExtractInsert) {
01949     // ext  E, Y, width(Y) - 1, 1  ; extract bit width(Y)-1 of Y
01950     // ins  X, E, width(X) - 1, 1  ; insert extracted bit at bit width(X)-1 of X
01951     SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
01952                             DAG.getConstant(WidthY - 1, MVT::i32), Const1);
01953 
01954     if (WidthX > WidthY)
01955       E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
01956     else if (WidthY > WidthX)
01957       E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
01958 
01959     SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
01960                             DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
01961     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
01962   }
01963 
01964   // (d)sll SllX, X, 1
01965   // (d)srl SrlX, SllX, 1
01966   // (d)srl SrlY, Y, width(Y)-1
01967   // (d)sll SllY, SrlX, width(Y)-1
01968   // or     Or, SrlX, SllY
01969   SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
01970   SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
01971   SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
01972                              DAG.getConstant(WidthY - 1, MVT::i32));
01973 
01974   if (WidthX > WidthY)
01975     SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
01976   else if (WidthY > WidthX)
01977     SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
01978 
01979   SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
01980                              DAG.getConstant(WidthX - 1, MVT::i32));
01981   SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
01982   return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
01983 }
01984 
01985 SDValue
01986 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
01987   if (Subtarget.isGP64bit())
01988     return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
01989 
01990   return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
01991 }
01992 
01993 SDValue MipsTargetLowering::
01994 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
01995   // check the depth
01996   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
01997          "Frame address can only be determined for current frame.");
01998 
01999   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
02000   MFI->setFrameAddressIsTaken(true);
02001   EVT VT = Op.getValueType();
02002   SDLoc DL(Op);
02003   SDValue FrameAddr =
02004       DAG.getCopyFromReg(DAG.getEntryNode(), DL,
02005                          Subtarget.isABI_N64() ? Mips::FP_64 : Mips::FP, VT);
02006   return FrameAddr;
02007 }
02008 
02009 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
02010                                             SelectionDAG &DAG) const {
02011   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
02012     return SDValue();
02013 
02014   // check the depth
02015   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
02016          "Return address can be determined only for current frame.");
02017 
02018   MachineFunction &MF = DAG.getMachineFunction();
02019   MachineFrameInfo *MFI = MF.getFrameInfo();
02020   MVT VT = Op.getSimpleValueType();
02021   unsigned RA = Subtarget.isABI_N64() ? Mips::RA_64 : Mips::RA;
02022   MFI->setReturnAddressIsTaken(true);
02023 
02024   // Return RA, which contains the return address. Mark it an implicit live-in.
02025   unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
02026   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
02027 }
02028 
02029 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
02030 // generated from __builtin_eh_return (offset, handler)
02031 // The effect of this is to adjust the stack pointer by "offset"
02032 // and then branch to "handler".
02033 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
02034                                                                      const {
02035   MachineFunction &MF = DAG.getMachineFunction();
02036   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
02037 
02038   MipsFI->setCallsEhReturn();
02039   SDValue Chain     = Op.getOperand(0);
02040   SDValue Offset    = Op.getOperand(1);
02041   SDValue Handler   = Op.getOperand(2);
02042   SDLoc DL(Op);
02043   EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
02044 
02045   // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
02046   // EH_RETURN nodes, so that instructions are emitted back-to-back.
02047   unsigned OffsetReg = Subtarget.isABI_N64() ? Mips::V1_64 : Mips::V1;
02048   unsigned AddrReg = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
02049   Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
02050   Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
02051   return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
02052                      DAG.getRegister(OffsetReg, Ty),
02053                      DAG.getRegister(AddrReg, getPointerTy()),
02054                      Chain.getValue(1));
02055 }
02056 
02057 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
02058                                               SelectionDAG &DAG) const {
02059   // FIXME: Need pseudo-fence for 'singlethread' fences
02060   // FIXME: Set SType for weaker fences where supported/appropriate.
02061   unsigned SType = 0;
02062   SDLoc DL(Op);
02063   return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
02064                      DAG.getConstant(SType, MVT::i32));
02065 }
02066 
02067 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
02068                                                 SelectionDAG &DAG) const {
02069   SDLoc DL(Op);
02070   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
02071   SDValue Shamt = Op.getOperand(2);
02072 
02073   // if shamt < 32:
02074   //  lo = (shl lo, shamt)
02075   //  hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
02076   // else:
02077   //  lo = 0
02078   //  hi = (shl lo, shamt[4:0])
02079   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
02080                             DAG.getConstant(-1, MVT::i32));
02081   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
02082                                       DAG.getConstant(1, MVT::i32));
02083   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
02084                                      Not);
02085   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
02086   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
02087   SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
02088   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
02089                              DAG.getConstant(0x20, MVT::i32));
02090   Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
02091                    DAG.getConstant(0, MVT::i32), ShiftLeftLo);
02092   Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
02093 
02094   SDValue Ops[2] = {Lo, Hi};
02095   return DAG.getMergeValues(Ops, DL);
02096 }
02097 
02098 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
02099                                                  bool IsSRA) const {
02100   SDLoc DL(Op);
02101   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
02102   SDValue Shamt = Op.getOperand(2);
02103 
02104   // if shamt < 32:
02105   //  lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
02106   //  if isSRA:
02107   //    hi = (sra hi, shamt)
02108   //  else:
02109   //    hi = (srl hi, shamt)
02110   // else:
02111   //  if isSRA:
02112   //   lo = (sra hi, shamt[4:0])
02113   //   hi = (sra hi, 31)
02114   //  else:
02115   //   lo = (srl hi, shamt[4:0])
02116   //   hi = 0
02117   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
02118                             DAG.getConstant(-1, MVT::i32));
02119   SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
02120                                      DAG.getConstant(1, MVT::i32));
02121   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
02122   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
02123   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
02124   SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
02125                                      Hi, Shamt);
02126   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
02127                              DAG.getConstant(0x20, MVT::i32));
02128   SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
02129                                 DAG.getConstant(31, MVT::i32));
02130   Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
02131   Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
02132                    IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
02133                    ShiftRightHi);
02134 
02135   SDValue Ops[2] = {Lo, Hi};
02136   return DAG.getMergeValues(Ops, DL);
02137 }
02138 
02139 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
02140                             SDValue Chain, SDValue Src, unsigned Offset) {
02141   SDValue Ptr = LD->getBasePtr();
02142   EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
02143   EVT BasePtrVT = Ptr.getValueType();
02144   SDLoc DL(LD);
02145   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
02146 
02147   if (Offset)
02148     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
02149                       DAG.getConstant(Offset, BasePtrVT));
02150 
02151   SDValue Ops[] = { Chain, Ptr, Src };
02152   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
02153                                  LD->getMemOperand());
02154 }
02155 
02156 // Expand an unaligned 32 or 64-bit integer load node.
02157 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
02158   LoadSDNode *LD = cast<LoadSDNode>(Op);
02159   EVT MemVT = LD->getMemoryVT();
02160 
02161   if (Subtarget.systemSupportsUnalignedAccess())
02162     return Op;
02163 
02164   // Return if load is aligned or if MemVT is neither i32 nor i64.
02165   if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
02166       ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
02167     return SDValue();
02168 
02169   bool IsLittle = Subtarget.isLittle();
02170   EVT VT = Op.getValueType();
02171   ISD::LoadExtType ExtType = LD->getExtensionType();
02172   SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
02173 
02174   assert((VT == MVT::i32) || (VT == MVT::i64));
02175 
02176   // Expand
02177   //  (set dst, (i64 (load baseptr)))
02178   // to
02179   //  (set tmp, (ldl (add baseptr, 7), undef))
02180   //  (set dst, (ldr baseptr, tmp))
02181   if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
02182     SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
02183                                IsLittle ? 7 : 0);
02184     return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
02185                         IsLittle ? 0 : 7);
02186   }
02187 
02188   SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
02189                              IsLittle ? 3 : 0);
02190   SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
02191                              IsLittle ? 0 : 3);
02192 
02193   // Expand
02194   //  (set dst, (i32 (load baseptr))) or
02195   //  (set dst, (i64 (sextload baseptr))) or
02196   //  (set dst, (i64 (extload baseptr)))
02197   // to
02198   //  (set tmp, (lwl (add baseptr, 3), undef))
02199   //  (set dst, (lwr baseptr, tmp))
02200   if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
02201       (ExtType == ISD::EXTLOAD))
02202     return LWR;
02203 
02204   assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
02205 
02206   // Expand
02207   //  (set dst, (i64 (zextload baseptr)))
02208   // to
02209   //  (set tmp0, (lwl (add baseptr, 3), undef))
02210   //  (set tmp1, (lwr baseptr, tmp0))
02211   //  (set tmp2, (shl tmp1, 32))
02212   //  (set dst, (srl tmp2, 32))
02213   SDLoc DL(LD);
02214   SDValue Const32 = DAG.getConstant(32, MVT::i32);
02215   SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
02216   SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
02217   SDValue Ops[] = { SRL, LWR.getValue(1) };
02218   return DAG.getMergeValues(Ops, DL);
02219 }
02220 
02221 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
02222                              SDValue Chain, unsigned Offset) {
02223   SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
02224   EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
02225   SDLoc DL(SD);
02226   SDVTList VTList = DAG.getVTList(MVT::Other);
02227 
02228   if (Offset)
02229     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
02230                       DAG.getConstant(Offset, BasePtrVT));
02231 
02232   SDValue Ops[] = { Chain, Value, Ptr };
02233   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
02234                                  SD->getMemOperand());
02235 }
02236 
02237 // Expand an unaligned 32 or 64-bit integer store node.
02238 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
02239                                       bool IsLittle) {
02240   SDValue Value = SD->getValue(), Chain = SD->getChain();
02241   EVT VT = Value.getValueType();
02242 
02243   // Expand
02244   //  (store val, baseptr) or
02245   //  (truncstore val, baseptr)
02246   // to
02247   //  (swl val, (add baseptr, 3))
02248   //  (swr val, baseptr)
02249   if ((VT == MVT::i32) || SD->isTruncatingStore()) {
02250     SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
02251                                 IsLittle ? 3 : 0);
02252     return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
02253   }
02254 
02255   assert(VT == MVT::i64);
02256 
02257   // Expand
02258   //  (store val, baseptr)
02259   // to
02260   //  (sdl val, (add baseptr, 7))
02261   //  (sdr val, baseptr)
02262   SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
02263   return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
02264 }
02265 
02266 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
02267 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
02268   SDValue Val = SD->getValue();
02269 
02270   if (Val.getOpcode() != ISD::FP_TO_SINT)
02271     return SDValue();
02272 
02273   EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
02274   SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
02275                            Val.getOperand(0));
02276 
02277   return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
02278                       SD->getPointerInfo(), SD->isVolatile(),
02279                       SD->isNonTemporal(), SD->getAlignment());
02280 }
02281 
02282 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
02283   StoreSDNode *SD = cast<StoreSDNode>(Op);
02284   EVT MemVT = SD->getMemoryVT();
02285 
02286   // Lower unaligned integer stores.
02287   if (!Subtarget.systemSupportsUnalignedAccess() &&
02288       (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
02289       ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
02290     return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
02291 
02292   return lowerFP_TO_SINT_STORE(SD, DAG);
02293 }
02294 
02295 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
02296   if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
02297       || cast<ConstantSDNode>
02298         (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
02299       || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
02300     return SDValue();
02301 
02302   // The pattern
02303   //   (add (frameaddr 0), (frame_to_args_offset))
02304   // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
02305   //   (add FrameObject, 0)
02306   // where FrameObject is a fixed StackObject with offset 0 which points to
02307   // the old stack pointer.
02308   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
02309   EVT ValTy = Op->getValueType(0);
02310   int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
02311   SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
02312   return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
02313                      DAG.getConstant(0, ValTy));
02314 }
02315 
02316 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
02317                                             SelectionDAG &DAG) const {
02318   EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
02319   SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
02320                               Op.getOperand(0));
02321   return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
02322 }
02323 
02324 //===----------------------------------------------------------------------===//
02325 //                      Calling Convention Implementation
02326 //===----------------------------------------------------------------------===//
02327 
02328 //===----------------------------------------------------------------------===//
02329 // TODO: Implement a generic logic using tblgen that can support this.
02330 // Mips O32 ABI rules:
02331 // ---
02332 // i32 - Passed in A0, A1, A2, A3 and stack
02333 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
02334 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
02335 // f64 - Only passed in two aliased f32 registers if no int reg has been used
02336 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
02337 //       not used, it must be shadowed. If only A3 is available, shadow it and
02338 //       go to stack.
02339 //
02340 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
02341 //===----------------------------------------------------------------------===//
02342 
02343 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
02344                        CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
02345                        CCState &State, const MCPhysReg *F64Regs) {
02346 
02347   static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
02348 
02349   static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
02350   static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
02351 
02352   // Do not process byval args here.
02353   if (ArgFlags.isByVal())
02354     return true;
02355 
02356   // Promote i8 and i16
02357   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
02358     LocVT = MVT::i32;
02359     if (ArgFlags.isSExt())
02360       LocInfo = CCValAssign::SExt;
02361     else if (ArgFlags.isZExt())
02362       LocInfo = CCValAssign::ZExt;
02363     else
02364       LocInfo = CCValAssign::AExt;
02365   }
02366 
02367   unsigned Reg;
02368 
02369   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
02370   // is true: function is vararg, argument is 3rd or higher, there is previous
02371   // argument which is not f32 or f64.
02372   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
02373       || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
02374   unsigned OrigAlign = ArgFlags.getOrigAlign();
02375   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
02376 
02377   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
02378     Reg = State.AllocateReg(IntRegs, IntRegsSize);
02379     // If this is the first part of an i64 arg,
02380     // the allocated register must be either A0 or A2.
02381     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
02382       Reg = State.AllocateReg(IntRegs, IntRegsSize);
02383     LocVT = MVT::i32;
02384   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
02385     // Allocate int register and shadow next int register. If first
02386     // available register is Mips::A1 or Mips::A3, shadow it too.
02387     Reg = State.AllocateReg(IntRegs, IntRegsSize);
02388     if (Reg == Mips::A1 || Reg == Mips::A3)
02389       Reg = State.AllocateReg(IntRegs, IntRegsSize);
02390     State.AllocateReg(IntRegs, IntRegsSize);
02391     LocVT = MVT::i32;
02392   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
02393     // we are guaranteed to find an available float register
02394     if (ValVT == MVT::f32) {
02395       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
02396       // Shadow int register
02397       State.AllocateReg(IntRegs, IntRegsSize);
02398     } else {
02399       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
02400       // Shadow int registers
02401       unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
02402       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
02403         State.AllocateReg(IntRegs, IntRegsSize);
02404       State.AllocateReg(IntRegs, IntRegsSize);
02405     }
02406   } else
02407     llvm_unreachable("Cannot handle this ValVT.");
02408 
02409   if (!Reg) {
02410     unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
02411                                           OrigAlign);
02412     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
02413   } else
02414     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
02415 
02416   return false;
02417 }
02418 
02419 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
02420                             MVT LocVT, CCValAssign::LocInfo LocInfo,
02421                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
02422   static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
02423 
02424   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
02425 }
02426 
02427 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
02428                             MVT LocVT, CCValAssign::LocInfo LocInfo,
02429                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
02430   static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
02431 
02432   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
02433 }
02434 
02435 #include "MipsGenCallingConv.inc"
02436 
02437 //===----------------------------------------------------------------------===//
02438 //                  Call Calling Convention Implementation
02439 //===----------------------------------------------------------------------===//
02440 
02441 // Return next O32 integer argument register.
02442 static unsigned getNextIntArgReg(unsigned Reg) {
02443   assert((Reg == Mips::A0) || (Reg == Mips::A2));
02444   return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
02445 }
02446 
02447 SDValue
02448 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
02449                                    SDValue Chain, SDValue Arg, SDLoc DL,
02450                                    bool IsTailCall, SelectionDAG &DAG) const {
02451   if (!IsTailCall) {
02452     SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
02453                                  DAG.getIntPtrConstant(Offset));
02454     return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
02455                         false, 0);
02456   }
02457 
02458   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
02459   int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
02460   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
02461   return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
02462                       /*isVolatile=*/ true, false, 0);
02463 }
02464 
02465 void MipsTargetLowering::
02466 getOpndList(SmallVectorImpl<SDValue> &Ops,
02467             std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
02468             bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
02469             bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
02470             SDValue Chain) const {
02471   // Insert node "GP copy globalreg" before call to function.
02472   //
02473   // R_MIPS_CALL* operators (emitted when non-internal functions are called
02474   // in PIC mode) allow symbols to be resolved via lazy binding.
02475   // The lazy binding stub requires GP to point to the GOT.
02476   // Note that we don't need GP to point to the GOT for indirect calls
02477   // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
02478   // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
02479   // used for the function (that is, Mips linker doesn't generate lazy binding
02480   // stub for a function whose address is taken in the program).
02481   if (IsPICCall && !InternalLinkage && IsCallReloc) {
02482     unsigned GPReg = Subtarget.isABI_N64() ? Mips::GP_64 : Mips::GP;
02483     EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
02484     RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
02485   }
02486 
02487   // Build a sequence of copy-to-reg nodes chained together with token
02488   // chain and flag operands which copy the outgoing args into registers.
02489   // The InFlag in necessary since all emitted instructions must be
02490   // stuck together.
02491   SDValue InFlag;
02492 
02493   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
02494     Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
02495                                  RegsToPass[i].second, InFlag);
02496     InFlag = Chain.getValue(1);
02497   }
02498 
02499   // Add argument registers to the end of the list so that they are
02500   // known live into the call.
02501   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
02502     Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
02503                                       RegsToPass[i].second.getValueType()));
02504 
02505   // Add a register mask operand representing the call-preserved registers.
02506   const TargetRegisterInfo *TRI =
02507       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
02508   const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
02509   assert(Mask && "Missing call preserved mask for calling convention");
02510   if (Subtarget.inMips16HardFloat()) {
02511     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
02512       llvm::StringRef Sym = G->getGlobal()->getName();
02513       Function *F = G->getGlobal()->getParent()->getFunction(Sym);
02514       if (F && F->hasFnAttribute("__Mips16RetHelper")) {
02515         Mask = MipsRegisterInfo::getMips16RetHelperMask();
02516       }
02517     }
02518   }
02519   Ops.push_back(CLI.DAG.getRegisterMask(Mask));
02520 
02521   if (InFlag.getNode())
02522     Ops.push_back(InFlag);
02523 }
02524 
02525 /// LowerCall - functions arguments are copied from virtual regs to
02526 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
02527 SDValue
02528 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
02529                               SmallVectorImpl<SDValue> &InVals) const {
02530   SelectionDAG &DAG                     = CLI.DAG;
02531   SDLoc DL                              = CLI.DL;
02532   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
02533   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
02534   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
02535   SDValue Chain                         = CLI.Chain;
02536   SDValue Callee                        = CLI.Callee;
02537   bool &IsTailCall                      = CLI.IsTailCall;
02538   CallingConv::ID CallConv              = CLI.CallConv;
02539   bool IsVarArg                         = CLI.IsVarArg;
02540 
02541   MachineFunction &MF = DAG.getMachineFunction();
02542   MachineFrameInfo *MFI = MF.getFrameInfo();
02543   const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
02544   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
02545   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
02546 
02547   // Analyze operands of the call, assigning locations to each operand.
02548   SmallVector<CCValAssign, 16> ArgLocs;
02549   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
02550                  *DAG.getContext());
02551   MipsCC::SpecialCallingConvType SpecialCallingConv =
02552     getSpecialCallingConv(Callee);
02553   MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo, SpecialCallingConv);
02554 
02555   MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
02556                                  Subtarget.abiUsesSoftFloat(),
02557                                  Callee.getNode(), CLI.getArgs());
02558 
02559   // Get a count of how many bytes are to be pushed on the stack.
02560   unsigned NextStackOffset = CCInfo.getNextStackOffset();
02561 
02562   // Check if it's really possible to do a tail call.
02563   if (IsTailCall)
02564     IsTailCall =
02565       isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
02566                                         *MF.getInfo<MipsFunctionInfo>());
02567 
02568   if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
02569     report_fatal_error("failed to perform tail call elimination on a call "
02570                        "site marked musttail");
02571 
02572   if (IsTailCall)
02573     ++NumTailCalls;
02574 
02575   // Chain is the output chain of the last Load/Store or CopyToReg node.
02576   // ByValChain is the output chain of the last Memcpy node created for copying
02577   // byval arguments to the stack.
02578   unsigned StackAlignment = TFL->getStackAlignment();
02579   NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
02580   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
02581 
02582   if (!IsTailCall)
02583     Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
02584 
02585   SDValue StackPtr = DAG.getCopyFromReg(
02586       Chain, DL, Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP,
02587       getPointerTy());
02588 
02589   // With EABI is it possible to have 16 args on registers.
02590   std::deque< std::pair<unsigned, SDValue> > RegsToPass;
02591   SmallVector<SDValue, 8> MemOpChains;
02592   MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
02593 
02594   // Walk the register/memloc assignments, inserting copies/loads.
02595   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
02596     SDValue Arg = OutVals[i];
02597     CCValAssign &VA = ArgLocs[i];
02598     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
02599     ISD::ArgFlagsTy Flags = Outs[i].Flags;
02600 
02601     // ByVal Arg.
02602     if (Flags.isByVal()) {
02603       assert(Flags.getByValSize() &&
02604              "ByVal args of size 0 should have been ignored by front-end.");
02605       assert(ByValArg != MipsCCInfo.byval_end());
02606       assert(!IsTailCall &&
02607              "Do not tail-call optimize if there is a byval argument.");
02608       passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
02609                    MipsCCInfo, *ByValArg, Flags, Subtarget.isLittle());
02610       ++ByValArg;
02611       continue;
02612     }
02613 
02614     // Promote the value if needed.
02615     switch (VA.getLocInfo()) {
02616     default: llvm_unreachable("Unknown loc info!");
02617     case CCValAssign::Full:
02618       if (VA.isRegLoc()) {
02619         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
02620             (ValVT == MVT::f64 && LocVT == MVT::i64) ||
02621             (ValVT == MVT::i64 && LocVT == MVT::f64))
02622           Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
02623         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
02624           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
02625                                    Arg, DAG.getConstant(0, MVT::i32));
02626           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
02627                                    Arg, DAG.getConstant(1, MVT::i32));
02628           if (!Subtarget.isLittle())
02629             std::swap(Lo, Hi);
02630           unsigned LocRegLo = VA.getLocReg();
02631           unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
02632           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
02633           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
02634           continue;
02635         }
02636       }
02637       break;
02638     case CCValAssign::SExt:
02639       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
02640       break;
02641     case CCValAssign::ZExt:
02642       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
02643       break;
02644     case CCValAssign::AExt:
02645       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
02646       break;
02647     }
02648 
02649     // Arguments that can be passed on register must be kept at
02650     // RegsToPass vector
02651     if (VA.isRegLoc()) {
02652       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
02653       continue;
02654     }
02655 
02656     // Register can't get to this point...
02657     assert(VA.isMemLoc());
02658 
02659     // emit ISD::STORE whichs stores the
02660     // parameter value to a stack Location
02661     MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
02662                                          Chain, Arg, DL, IsTailCall, DAG));
02663   }
02664 
02665   // Transform all store nodes into one single node because all store
02666   // nodes are independent of each other.
02667   if (!MemOpChains.empty())
02668     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
02669 
02670   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
02671   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
02672   // node so that legalize doesn't hack it.
02673   bool IsPICCall =
02674       (Subtarget.isABI_N64() || IsPIC); // true if calls are translated to
02675                                          // jalr $25
02676   bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
02677   SDValue CalleeLo;
02678   EVT Ty = Callee.getValueType();
02679 
02680   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
02681     if (IsPICCall) {
02682       const GlobalValue *Val = G->getGlobal();
02683       InternalLinkage = Val->hasInternalLinkage();
02684 
02685       if (InternalLinkage)
02686         Callee = getAddrLocal(G, Ty, DAG,
02687                               Subtarget.isABI_N32() || Subtarget.isABI_N64());
02688       else if (LargeGOT) {
02689         Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
02690                                        MipsII::MO_CALL_LO16, Chain,
02691                                        FuncInfo->callPtrInfo(Val));
02692         IsCallReloc = true;
02693       } else {
02694         Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
02695                                FuncInfo->callPtrInfo(Val));
02696         IsCallReloc = true;
02697       }
02698     } else
02699       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
02700                                           MipsII::MO_NO_FLAG);
02701     GlobalOrExternal = true;
02702   }
02703   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
02704     const char *Sym = S->getSymbol();
02705 
02706     if (!Subtarget.isABI_N64() && !IsPIC) // !N64 && static
02707       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
02708                                             MipsII::MO_NO_FLAG);
02709     else if (LargeGOT) {
02710       Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
02711                                      MipsII::MO_CALL_LO16, Chain,
02712                                      FuncInfo->callPtrInfo(Sym));
02713       IsCallReloc = true;
02714     } else { // N64 || PIC
02715       Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
02716                              FuncInfo->callPtrInfo(Sym));
02717       IsCallReloc = true;
02718     }
02719 
02720     GlobalOrExternal = true;
02721   }
02722 
02723   SmallVector<SDValue, 8> Ops(1, Chain);
02724   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
02725 
02726   getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
02727               IsCallReloc, CLI, Callee, Chain);
02728 
02729   if (IsTailCall)
02730     return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
02731 
02732   Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
02733   SDValue InFlag = Chain.getValue(1);
02734 
02735   // Create the CALLSEQ_END node.
02736   Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
02737                              DAG.getIntPtrConstant(0, true), InFlag, DL);
02738   InFlag = Chain.getValue(1);
02739 
02740   // Handle result values, copying them out of physregs into vregs that we
02741   // return.
02742   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
02743                          InVals, CLI);
02744 }
02745 
02746 /// LowerCallResult - Lower the result values of a call into the
02747 /// appropriate copies out of appropriate physical registers.
02748 SDValue MipsTargetLowering::LowerCallResult(
02749     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
02750     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
02751     SmallVectorImpl<SDValue> &InVals,
02752     TargetLowering::CallLoweringInfo &CLI) const {
02753   // Assign locations to each value returned by this call.
02754   SmallVector<CCValAssign, 16> RVLocs;
02755   MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
02756                      *DAG.getContext());
02757   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
02758 
02759   // Copy all of the result registers out of their specified physreg.
02760   for (unsigned i = 0; i != RVLocs.size(); ++i) {
02761     CCValAssign &VA = RVLocs[i];
02762     assert(VA.isRegLoc() && "Can only return in registers!");
02763 
02764     SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
02765                                      RVLocs[i].getLocVT(), InFlag);
02766     Chain = Val.getValue(1);
02767     InFlag = Val.getValue(2);
02768 
02769     if (VA.isUpperBitsInLoc()) {
02770       unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
02771       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
02772       unsigned Shift =
02773           VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
02774       Val = DAG.getNode(
02775           Shift, DL, VA.getLocVT(), Val,
02776           DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
02777     }
02778 
02779     switch (VA.getLocInfo()) {
02780     default:
02781       llvm_unreachable("Unknown loc info!");
02782     case CCValAssign::Full:
02783       break;
02784     case CCValAssign::BCvt:
02785       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
02786       break;
02787     case CCValAssign::AExt:
02788     case CCValAssign::AExtUpper:
02789       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
02790       break;
02791     case CCValAssign::ZExt:
02792     case CCValAssign::ZExtUpper:
02793       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
02794                         DAG.getValueType(VA.getValVT()));
02795       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
02796       break;
02797     case CCValAssign::SExt:
02798     case CCValAssign::SExtUpper:
02799       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
02800                         DAG.getValueType(VA.getValVT()));
02801       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
02802       break;
02803     }
02804 
02805     InVals.push_back(Val);
02806   }
02807 
02808   return Chain;
02809 }
02810 
02811 //===----------------------------------------------------------------------===//
02812 //             Formal Arguments Calling Convention Implementation
02813 //===----------------------------------------------------------------------===//
02814 /// LowerFormalArguments - transform physical registers into virtual registers
02815 /// and generate load operations for arguments places on the stack.
02816 SDValue
02817 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
02818                                          CallingConv::ID CallConv,
02819                                          bool IsVarArg,
02820                                       const SmallVectorImpl<ISD::InputArg> &Ins,
02821                                          SDLoc DL, SelectionDAG &DAG,
02822                                          SmallVectorImpl<SDValue> &InVals)
02823                                           const {
02824   MachineFunction &MF = DAG.getMachineFunction();
02825   MachineFrameInfo *MFI = MF.getFrameInfo();
02826   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
02827 
02828   MipsFI->setVarArgsFrameIndex(0);
02829 
02830   // Used with vargs to acumulate store chains.
02831   std::vector<SDValue> OutChains;
02832 
02833   // Assign locations to all of the incoming arguments.
02834   SmallVector<CCValAssign, 16> ArgLocs;
02835   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
02836                  *DAG.getContext());
02837   MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
02838   Function::const_arg_iterator FuncArg =
02839     DAG.getMachineFunction().getFunction()->arg_begin();
02840   bool UseSoftFloat = Subtarget.abiUsesSoftFloat();
02841 
02842   MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
02843   MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
02844                            MipsCCInfo.hasByValArg());
02845 
02846   unsigned CurArgIdx = 0;
02847   MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
02848 
02849   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
02850     CCValAssign &VA = ArgLocs[i];
02851     std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
02852     CurArgIdx = Ins[i].OrigArgIndex;
02853     EVT ValVT = VA.getValVT();
02854     ISD::ArgFlagsTy Flags = Ins[i].Flags;
02855     bool IsRegLoc = VA.isRegLoc();
02856 
02857     if (Flags.isByVal()) {
02858       assert(Flags.getByValSize() &&
02859              "ByVal args of size 0 should have been ignored by front-end.");
02860       assert(ByValArg != MipsCCInfo.byval_end());
02861       copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
02862                     MipsCCInfo, *ByValArg);
02863       ++ByValArg;
02864       continue;
02865     }
02866 
02867     // Arguments stored on registers
02868     if (IsRegLoc) {
02869       MVT RegVT = VA.getLocVT();
02870       unsigned ArgReg = VA.getLocReg();
02871       const TargetRegisterClass *RC = getRegClassFor(RegVT);
02872 
02873       // Transform the arguments stored on
02874       // physical registers into virtual ones
02875       unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
02876       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
02877 
02878       // If this is an 8 or 16-bit value, it has been passed promoted
02879       // to 32 bits.  Insert an assert[sz]ext to capture this, then
02880       // truncate to the right size.
02881       if (VA.getLocInfo() != CCValAssign::Full) {
02882         unsigned Opcode = 0;
02883         if (VA.getLocInfo() == CCValAssign::SExt)
02884           Opcode = ISD::AssertSext;
02885         else if (VA.getLocInfo() == CCValAssign::ZExt)
02886           Opcode = ISD::AssertZext;
02887         if (Opcode)
02888           ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
02889                                  DAG.getValueType(ValVT));
02890         ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
02891       }
02892 
02893       // Handle floating point arguments passed in integer registers and
02894       // long double arguments passed in floating point registers.
02895       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
02896           (RegVT == MVT::i64 && ValVT == MVT::f64) ||
02897           (RegVT == MVT::f64 && ValVT == MVT::i64))
02898         ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
02899       else if (Subtarget.isABI_O32() && RegVT == MVT::i32 &&
02900                ValVT == MVT::f64) {
02901         unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
02902                                   getNextIntArgReg(ArgReg), RC);
02903         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
02904         if (!Subtarget.isLittle())
02905           std::swap(ArgValue, ArgValue2);
02906         ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
02907                                ArgValue, ArgValue2);
02908       }
02909 
02910       InVals.push_back(ArgValue);
02911     } else { // VA.isRegLoc()
02912 
02913       // sanity check
02914       assert(VA.isMemLoc());
02915 
02916       // The stack pointer offset is relative to the caller stack frame.
02917       int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
02918                                       VA.getLocMemOffset(), true);
02919 
02920       // Create load nodes to retrieve arguments from the stack
02921       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
02922       SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
02923                                  MachinePointerInfo::getFixedStack(FI),
02924                                  false, false, false, 0);
02925       InVals.push_back(Load);
02926       OutChains.push_back(Load.getValue(1));
02927     }
02928   }
02929 
02930   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
02931     // The mips ABIs for returning structs by value requires that we copy
02932     // the sret argument into $v0 for the return. Save the argument into
02933     // a virtual register so that we can access it from the return points.
02934     if (Ins[i].Flags.isSRet()) {
02935       unsigned Reg = MipsFI->getSRetReturnReg();
02936       if (!Reg) {
02937         Reg = MF.getRegInfo().createVirtualRegister(
02938             getRegClassFor(Subtarget.isABI_N64() ? MVT::i64 : MVT::i32));
02939         MipsFI->setSRetReturnReg(Reg);
02940       }
02941       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
02942       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
02943       break;
02944     }
02945   }
02946 
02947   if (IsVarArg)
02948     writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
02949 
02950   // All stores are grouped in one node to allow the matching between
02951   // the size of Ins and InVals. This only happens when on varg functions
02952   if (!OutChains.empty()) {
02953     OutChains.push_back(Chain);
02954     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
02955   }
02956 
02957   return Chain;
02958 }
02959 
02960 //===----------------------------------------------------------------------===//
02961 //               Return Value Calling Convention Implementation
02962 //===----------------------------------------------------------------------===//
02963 
02964 bool
02965 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
02966                                    MachineFunction &MF, bool IsVarArg,
02967                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
02968                                    LLVMContext &Context) const {
02969   SmallVector<CCValAssign, 16> RVLocs;
02970   MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
02971   return CCInfo.CheckReturn(Outs, RetCC_Mips);
02972 }
02973 
02974 SDValue
02975 MipsTargetLowering::LowerReturn(SDValue Chain,
02976                                 CallingConv::ID CallConv, bool IsVarArg,
02977                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
02978                                 const SmallVectorImpl<SDValue> &OutVals,
02979                                 SDLoc DL, SelectionDAG &DAG) const {
02980   // CCValAssign - represent the assignment of
02981   // the return value to a location
02982   SmallVector<CCValAssign, 16> RVLocs;
02983   MachineFunction &MF = DAG.getMachineFunction();
02984 
02985   // CCState - Info about the registers and stack slot.
02986   MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
02987   MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
02988 
02989   // Analyze return values.
02990   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
02991 
02992   SDValue Flag;
02993   SmallVector<SDValue, 4> RetOps(1, Chain);
02994 
02995   // Copy the result values into the output registers.
02996   for (unsigned i = 0; i != RVLocs.size(); ++i) {
02997     SDValue Val = OutVals[i];
02998     CCValAssign &VA = RVLocs[i];
02999     assert(VA.isRegLoc() && "Can only return in registers!");
03000     bool UseUpperBits = false;
03001 
03002     switch (VA.getLocInfo()) {
03003     default:
03004       llvm_unreachable("Unknown loc info!");
03005     case CCValAssign::Full:
03006       break;
03007     case CCValAssign::BCvt:
03008       Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
03009       break;
03010     case CCValAssign::AExtUpper:
03011       UseUpperBits = true;
03012       // Fallthrough
03013     case CCValAssign::AExt:
03014       Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
03015       break;
03016     case CCValAssign::ZExtUpper:
03017       UseUpperBits = true;
03018       // Fallthrough
03019     case CCValAssign::ZExt:
03020       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
03021       break;
03022     case CCValAssign::SExtUpper:
03023       UseUpperBits = true;
03024       // Fallthrough
03025     case CCValAssign::SExt:
03026       Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
03027       break;
03028     }
03029 
03030     if (UseUpperBits) {
03031       unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
03032       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
03033       Val = DAG.getNode(
03034           ISD::SHL, DL, VA.getLocVT(), Val,
03035           DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
03036     }
03037 
03038     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
03039 
03040     // Guarantee that all emitted copies are stuck together with flags.
03041     Flag = Chain.getValue(1);
03042     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
03043   }
03044 
03045   // The mips ABIs for returning structs by value requires that we copy
03046   // the sret argument into $v0 for the return. We saved the argument into
03047   // a virtual register in the entry block, so now we copy the value out
03048   // and into $v0.
03049   if (MF.getFunction()->hasStructRetAttr()) {
03050     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
03051     unsigned Reg = MipsFI->getSRetReturnReg();
03052 
03053     if (!Reg)
03054       llvm_unreachable("sret virtual register not created in the entry block");
03055     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
03056     unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
03057 
03058     Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
03059     Flag = Chain.getValue(1);
03060     RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
03061   }
03062 
03063   RetOps[0] = Chain;  // Update chain.
03064 
03065   // Add the flag if we have it.
03066   if (Flag.getNode())
03067     RetOps.push_back(Flag);
03068 
03069   // Return on Mips is always a "jr $ra"
03070   return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
03071 }
03072 
03073 //===----------------------------------------------------------------------===//
03074 //                           Mips Inline Assembly Support
03075 //===----------------------------------------------------------------------===//
03076 
03077 /// getConstraintType - Given a constraint letter, return the type of
03078 /// constraint it is for this target.
03079 MipsTargetLowering::ConstraintType MipsTargetLowering::
03080 getConstraintType(const std::string &Constraint) const
03081 {
03082   // Mips specific constraints
03083   // GCC config/mips/constraints.md
03084   //
03085   // 'd' : An address register. Equivalent to r
03086   //       unless generating MIPS16 code.
03087   // 'y' : Equivalent to r; retained for
03088   //       backwards compatibility.
03089   // 'c' : A register suitable for use in an indirect
03090   //       jump. This will always be $25 for -mabicalls.
03091   // 'l' : The lo register. 1 word storage.
03092   // 'x' : The hilo register pair. Double word storage.
03093   if (Constraint.size() == 1) {
03094     switch (Constraint[0]) {
03095       default : break;
03096       case 'd':
03097       case 'y':
03098       case 'f':
03099       case 'c':
03100       case 'l':
03101       case 'x':
03102         return C_RegisterClass;
03103       case 'R':
03104         return C_Memory;
03105     }
03106   }
03107   return TargetLowering::getConstraintType(Constraint);
03108 }
03109 
03110 /// Examine constraint type and operand type and determine a weight value.
03111 /// This object must already have been set up with the operand type
03112 /// and the current alternative constraint selected.
03113 TargetLowering::ConstraintWeight
03114 MipsTargetLowering::getSingleConstraintMatchWeight(
03115     AsmOperandInfo &info, const char *constraint) const {
03116   ConstraintWeight weight = CW_Invalid;
03117   Value *CallOperandVal = info.CallOperandVal;
03118     // If we don't have a value, we can't do a match,
03119     // but allow it at the lowest weight.
03120   if (!CallOperandVal)
03121     return CW_Default;
03122   Type *type = CallOperandVal->getType();
03123   // Look at the constraint type.
03124   switch (*constraint) {
03125   default:
03126     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
03127     break;
03128   case 'd':
03129   case 'y':
03130     if (type->isIntegerTy())
03131       weight = CW_Register;
03132     break;
03133   case 'f': // FPU or MSA register
03134     if (Subtarget.hasMSA() && type->isVectorTy() &&
03135         cast<VectorType>(type)->getBitWidth() == 128)
03136       weight = CW_Register;
03137     else if (type->isFloatTy())
03138       weight = CW_Register;
03139     break;
03140   case 'c': // $25 for indirect jumps
03141   case 'l': // lo register
03142   case 'x': // hilo register pair
03143     if (type->isIntegerTy())
03144       weight = CW_SpecificReg;
03145     break;
03146   case 'I': // signed 16 bit immediate
03147   case 'J': // integer zero
03148   case 'K': // unsigned 16 bit immediate
03149   case 'L': // signed 32 bit immediate where lower 16 bits are 0
03150   case 'N': // immediate in the range of -65535 to -1 (inclusive)
03151   case 'O': // signed 15 bit immediate (+- 16383)
03152   case 'P': // immediate in the range of 65535 to 1 (inclusive)
03153     if (isa<ConstantInt>(CallOperandVal))
03154       weight = CW_Constant;
03155     break;
03156   case 'R':
03157     weight = CW_Memory;
03158     break;
03159   }
03160   return weight;
03161 }
03162 
03163 /// This is a helper function to parse a physical register string and split it
03164 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
03165 /// that is returned indicates whether parsing was successful. The second flag
03166 /// is true if the numeric part exists.
03167 static std::pair<bool, bool>
03168 parsePhysicalReg(StringRef C, std::string &Prefix,
03169                  unsigned long long &Reg) {
03170   if (C.front() != '{' || C.back() != '}')
03171     return std::make_pair(false, false);
03172 
03173   // Search for the first numeric character.
03174   StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
03175   I = std::find_if(B, E, std::ptr_fun(isdigit));
03176 
03177   Prefix.assign(B, I - B);
03178 
03179   // The second flag is set to false if no numeric characters were found.
03180   if (I == E)
03181     return std::make_pair(true, false);
03182 
03183   // Parse the numeric characters.
03184   return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
03185                         true);
03186 }
03187 
03188 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
03189 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
03190   const TargetRegisterInfo *TRI =
03191       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
03192   const TargetRegisterClass *RC;
03193   std::string Prefix;
03194   unsigned long long Reg;
03195 
03196   std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
03197 
03198   if (!R.first)
03199     return std::make_pair(0U, nullptr);
03200 
03201   if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
03202     // No numeric characters follow "hi" or "lo".
03203     if (R.second)
03204       return std::make_pair(0U, nullptr);
03205 
03206     RC = TRI->getRegClass(Prefix == "hi" ?
03207                           Mips::HI32RegClassID : Mips::LO32RegClassID);
03208     return std::make_pair(*(RC->begin()), RC);
03209   } else if (Prefix.compare(0, 4, "$msa") == 0) {
03210     // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
03211 
03212     // No numeric characters follow the name.
03213     if (R.second)
03214       return std::make_pair(0U, nullptr);
03215 
03216     Reg = StringSwitch<unsigned long long>(Prefix)
03217               .Case("$msair", Mips::MSAIR)
03218               .Case("$msacsr", Mips::MSACSR)
03219               .Case("$msaaccess", Mips::MSAAccess)
03220               .Case("$msasave", Mips::MSASave)
03221               .Case("$msamodify", Mips::MSAModify)
03222               .Case("$msarequest", Mips::MSARequest)
03223               .Case("$msamap", Mips::MSAMap)
03224               .Case("$msaunmap", Mips::MSAUnmap)
03225               .Default(0);
03226 
03227     if (!Reg)
03228       return std::make_pair(0U, nullptr);
03229 
03230     RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
03231     return std::make_pair(Reg, RC);
03232   }
03233 
03234   if (!R.second)
03235     return std::make_pair(0U, nullptr);
03236 
03237   if (Prefix == "$f") { // Parse $f0-$f31.
03238     // If the size of FP registers is 64-bit or Reg is an even number, select
03239     // the 64-bit register class. Otherwise, select the 32-bit register class.
03240     if (VT == MVT::Other)
03241       VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
03242 
03243     RC = getRegClassFor(VT);
03244 
03245     if (RC == &Mips::AFGR64RegClass) {
03246       assert(Reg % 2 == 0);
03247       Reg >>= 1;
03248     }
03249   } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
03250     RC = TRI->getRegClass(Mips::FCCRegClassID);
03251   else if (Prefix == "$w") { // Parse $w0-$w31.
03252     RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
03253   } else { // Parse $0-$31.
03254     assert(Prefix == "$");
03255     RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
03256   }
03257 
03258   assert(Reg < RC->getNumRegs());
03259   return std::make_pair(*(RC->begin() + Reg), RC);
03260 }
03261 
03262 /// Given a register class constraint, like 'r', if this corresponds directly
03263 /// to an LLVM register class, return a register of 0 and the register class
03264 /// pointer.
03265 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
03266 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
03267 {
03268   if (Constraint.size() == 1) {
03269     switch (Constraint[0]) {
03270     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
03271     case 'y': // Same as 'r'. Exists for compatibility.
03272     case 'r':
03273       if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
03274         if (Subtarget.inMips16Mode())
03275           return std::make_pair(0U, &Mips::CPU16RegsRegClass);
03276         return std::make_pair(0U, &Mips::GPR32RegClass);
03277       }
03278       if (VT == MVT::i64 && !Subtarget.isGP64bit())
03279         return std::make_pair(0U, &Mips::GPR32RegClass);
03280       if (VT == MVT::i64 && Subtarget.isGP64bit())
03281         return std::make_pair(0U, &Mips::GPR64RegClass);
03282       // This will generate an error message
03283       return std::make_pair(0U, nullptr);
03284     case 'f': // FPU or MSA register
03285       if (VT == MVT::v16i8)
03286         return std::make_pair(0U, &Mips::MSA128BRegClass);
03287       else if (VT == MVT::v8i16 || VT == MVT::v8f16)
03288         return std::make_pair(0U, &Mips::MSA128HRegClass);
03289       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
03290         return std::make_pair(0U, &Mips::MSA128WRegClass);
03291       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
03292         return std::make_pair(0U, &Mips::MSA128DRegClass);
03293       else if (VT == MVT::f32)
03294         return std::make_pair(0U, &Mips::FGR32RegClass);
03295       else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
03296         if (Subtarget.isFP64bit())
03297           return std::make_pair(0U, &Mips::FGR64RegClass);
03298         return std::make_pair(0U, &Mips::AFGR64RegClass);
03299       }
03300       break;
03301     case 'c': // register suitable for indirect jump
03302       if (VT == MVT::i32)
03303         return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
03304       assert(VT == MVT::i64 && "Unexpected type.");
03305       return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
03306     case 'l': // register suitable for indirect jump
03307       if (VT == MVT::i32)
03308         return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
03309       return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
03310     case 'x': // register suitable for indirect jump
03311       // Fixme: Not triggering the use of both hi and low
03312       // This will generate an error message
03313       return std::make_pair(0U, nullptr);
03314     }
03315   }
03316 
03317   std::pair<unsigned, const TargetRegisterClass *> R;
03318   R = parseRegForInlineAsmConstraint(Constraint, VT);
03319 
03320   if (R.second)
03321     return R;
03322 
03323   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
03324 }
03325 
03326 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
03327 /// vector.  If it is invalid, don't add anything to Ops.
03328 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
03329                                                      std::string &Constraint,
03330                                                      std::vector<SDValue>&Ops,
03331                                                      SelectionDAG &DAG) const {
03332   SDValue Result;
03333 
03334   // Only support length 1 constraints for now.
03335   if (Constraint.length() > 1) return;
03336 
03337   char ConstraintLetter = Constraint[0];
03338   switch (ConstraintLetter) {
03339   default: break; // This will fall through to the generic implementation
03340   case 'I': // Signed 16 bit constant
03341     // If this fails, the parent routine will give an error
03342     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03343       EVT Type = Op.getValueType();
03344       int64_t Val = C->getSExtValue();
03345       if (isInt<16>(Val)) {
03346         Result = DAG.getTargetConstant(Val, Type);
03347         break;
03348       }
03349     }
03350     return;
03351   case 'J': // integer zero
03352     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03353       EVT Type = Op.getValueType();
03354       int64_t Val = C->getZExtValue();
03355       if (Val == 0) {
03356         Result = DAG.getTargetConstant(0, Type);
03357         break;
03358       }
03359     }
03360     return;
03361   case 'K': // unsigned 16 bit immediate
03362     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03363       EVT Type = Op.getValueType();
03364       uint64_t Val = (uint64_t)C->getZExtValue();
03365       if (isUInt<16>(Val)) {
03366         Result = DAG.getTargetConstant(Val, Type);
03367         break;
03368       }
03369     }
03370     return;
03371   case 'L': // signed 32 bit immediate where lower 16 bits are 0
03372     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03373       EVT Type = Op.getValueType();
03374       int64_t Val = C->getSExtValue();
03375       if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
03376         Result = DAG.getTargetConstant(Val, Type);
03377         break;
03378       }
03379     }
03380     return;
03381   case 'N': // immediate in the range of -65535 to -1 (inclusive)
03382     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03383       EVT Type = Op.getValueType();
03384       int64_t Val = C->getSExtValue();
03385       if ((Val >= -65535) && (Val <= -1)) {
03386         Result = DAG.getTargetConstant(Val, Type);
03387         break;
03388       }
03389     }
03390     return;
03391   case 'O': // signed 15 bit immediate
03392     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03393       EVT Type = Op.getValueType();
03394       int64_t Val = C->getSExtValue();
03395       if ((isInt<15>(Val))) {
03396         Result = DAG.getTargetConstant(Val, Type);
03397         break;
03398       }
03399     }
03400     return;
03401   case 'P': // immediate in the range of 1 to 65535 (inclusive)
03402     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03403       EVT Type = Op.getValueType();
03404       int64_t Val = C->getSExtValue();
03405       if ((Val <= 65535) && (Val >= 1)) {
03406         Result = DAG.getTargetConstant(Val, Type);
03407         break;
03408       }
03409     }
03410     return;
03411   }
03412 
03413   if (Result.getNode()) {
03414     Ops.push_back(Result);
03415     return;
03416   }
03417 
03418   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
03419 }
03420 
03421 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
03422                                                Type *Ty) const {
03423   // No global is ever allowed as a base.
03424   if (AM.BaseGV)
03425     return false;
03426 
03427   switch (AM.Scale) {
03428   case 0: // "r+i" or just "i", depending on HasBaseReg.
03429     break;
03430   case 1:
03431     if (!AM.HasBaseReg) // allow "r+i".
03432       break;
03433     return false; // disallow "r+r" or "r+r+i".
03434   default:
03435     return false;
03436   }
03437 
03438   return true;
03439 }
03440 
03441 bool
03442 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
03443   // The Mips target isn't yet aware of offsets.
03444   return false;
03445 }
03446 
03447 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
03448                                             unsigned SrcAlign,
03449                                             bool IsMemset, bool ZeroMemset,
03450                                             bool MemcpyStrSrc,
03451                                             MachineFunction &MF) const {
03452   if (Subtarget.hasMips64())
03453     return MVT::i64;
03454 
03455   return MVT::i32;
03456 }
03457 
03458 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
03459   if (VT != MVT::f32 && VT != MVT::f64)
03460     return false;
03461   if (Imm.isNegZero())
03462     return false;
03463   return Imm.isZero();
03464 }
03465 
03466 unsigned MipsTargetLowering::getJumpTableEncoding() const {
03467   if (Subtarget.isABI_N64())
03468     return MachineJumpTableInfo::EK_GPRel64BlockAddress;
03469 
03470   return TargetLowering::getJumpTableEncoding();
03471 }
03472 
03473 /// This function returns true if CallSym is a long double emulation routine.
03474 static bool isF128SoftLibCall(const char *CallSym) {
03475   const char *const LibCalls[] =
03476     {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
03477      "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
03478      "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
03479      "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
03480      "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
03481      "__trunctfdf2", "__trunctfsf2", "__unordtf2",
03482      "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
03483      "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
03484      "truncl"};
03485 
03486   const char *const *End = LibCalls + array_lengthof(LibCalls);
03487 
03488   // Check that LibCalls is sorted alphabetically.
03489   MipsTargetLowering::LTStr Comp;
03490 
03491 #ifndef NDEBUG
03492   for (const char *const *I = LibCalls; I < End - 1; ++I)
03493     assert(Comp(*I, *(I + 1)));
03494 #endif
03495 
03496   return std::binary_search(LibCalls, End, CallSym, Comp);
03497 }
03498 
03499 /// This function returns true if Ty is fp128, {f128} or i128 which was
03500 /// originally a fp128.
03501 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
03502   if (Ty->isFP128Ty())
03503     return true;
03504 
03505   if (Ty->isStructTy() && Ty->getStructNumElements() == 1 &&
03506       Ty->getStructElementType(0)->isFP128Ty())
03507     return true;
03508 
03509   const ExternalSymbolSDNode *ES =
03510     dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
03511 
03512   // If the Ty is i128 and the function being called is a long double emulation
03513   // routine, then the original type is f128.
03514   return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
03515 }
03516 
03517 MipsTargetLowering::MipsCC::SpecialCallingConvType
03518   MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
03519   MipsCC::SpecialCallingConvType SpecialCallingConv =
03520     MipsCC::NoSpecialCallingConv;
03521   if (Subtarget.inMips16HardFloat()) {
03522     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
03523       llvm::StringRef Sym = G->getGlobal()->getName();
03524       Function *F = G->getGlobal()->getParent()->getFunction(Sym);
03525       if (F && F->hasFnAttribute("__Mips16RetHelper")) {
03526         SpecialCallingConv = MipsCC::Mips16RetHelperConv;
03527       }
03528     }
03529   }
03530   return SpecialCallingConv;
03531 }
03532 
03533 MipsTargetLowering::MipsCC::MipsCC(
03534     CallingConv::ID CC, const MipsSubtarget &Subtarget_, CCState &Info,
03535     MipsCC::SpecialCallingConvType SpecialCallingConv_)
03536     : CCInfo(Info), CallConv(CC), Subtarget(Subtarget_),
03537       SpecialCallingConv(SpecialCallingConv_) {
03538   // Pre-allocate reserved argument area.
03539   CCInfo.AllocateStack(reservedArgArea(), 1);
03540 }
03541 
03542 
03543 void MipsTargetLowering::MipsCC::
03544 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
03545                     bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
03546                     std::vector<ArgListEntry> &FuncArgs) {
03547   assert((CallConv != CallingConv::Fast || !IsVarArg) &&
03548          "CallingConv::Fast shouldn't be used for vararg functions.");
03549 
03550   unsigned NumOpnds = Args.size();
03551   llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
03552 
03553   for (unsigned I = 0; I != NumOpnds; ++I) {
03554     MVT ArgVT = Args[I].VT;
03555     ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
03556     bool R;
03557 
03558     if (ArgFlags.isByVal()) {
03559       handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
03560       continue;
03561     }
03562 
03563     if (IsVarArg && !Args[I].IsFixed)
03564       R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
03565     else {
03566       MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
03567                            IsSoftFloat);
03568       R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
03569     }
03570 
03571     if (R) {
03572 #ifndef NDEBUG
03573       dbgs() << "Call operand #" << I << " has unhandled type "
03574              << EVT(ArgVT).getEVTString();
03575 #endif
03576       llvm_unreachable(nullptr);
03577     }
03578   }
03579 }
03580 
03581 void MipsTargetLowering::MipsCC::
03582 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
03583                        bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
03584   unsigned NumArgs = Args.size();
03585   llvm::CCAssignFn *FixedFn = fixedArgFn();
03586   unsigned CurArgIdx = 0;
03587 
03588   for (unsigned I = 0; I != NumArgs; ++I) {
03589     MVT ArgVT = Args[I].VT;
03590     ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
03591     std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
03592     CurArgIdx = Args[I].OrigArgIndex;
03593 
03594     if (ArgFlags.isByVal()) {
03595       handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
03596       continue;
03597     }
03598 
03599     MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), nullptr, IsSoftFloat);
03600 
03601     if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
03602       continue;
03603 
03604 #ifndef NDEBUG
03605     dbgs() << "Formal Arg #" << I << " has unhandled type "
03606            << EVT(ArgVT).getEVTString();
03607 #endif
03608     llvm_unreachable(nullptr);
03609   }
03610 }
03611 
03612 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
03613                                                 MVT LocVT,
03614                                                 CCValAssign::LocInfo LocInfo,
03615                                                 ISD::ArgFlagsTy ArgFlags) {
03616   assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
03617 
03618   struct ByValArgInfo ByVal;
03619   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
03620   unsigned ByValSize =
03621       RoundUpToAlignment(ArgFlags.getByValSize(), RegSizeInBytes);
03622   unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSizeInBytes),
03623                             RegSizeInBytes * 2);
03624 
03625   if (useRegsForByval())
03626     allocateRegs(ByVal, ByValSize, Align);
03627 
03628   // Allocate space on caller's stack.
03629   ByVal.Address =
03630       CCInfo.AllocateStack(ByValSize - RegSizeInBytes * ByVal.NumRegs, Align);
03631   CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
03632                                     LocInfo));
03633   ByValArgs.push_back(ByVal);
03634 }
03635 
03636 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
03637   return (Subtarget.isABI_O32() && (CallConv != CallingConv::Fast)) ? 16 : 0;
03638 }
03639 
03640 const ArrayRef<MCPhysReg> MipsTargetLowering::MipsCC::intArgRegs() const {
03641   if (Subtarget.isABI_O32())
03642     return makeArrayRef(O32IntRegs);
03643   return makeArrayRef(Mips64IntRegs);
03644 }
03645 
03646 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
03647   if (CallConv == CallingConv::Fast)
03648     return CC_Mips_FastCC;
03649 
03650   if (SpecialCallingConv == Mips16RetHelperConv)
03651     return CC_Mips16RetHelper;
03652   return Subtarget.isABI_O32()
03653              ? (Subtarget.isFP64bit() ? CC_MipsO32_FP64 : CC_MipsO32_FP32)
03654              : CC_MipsN;
03655 }
03656 
03657 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
03658   return Subtarget.isABI_O32()
03659              ? (Subtarget.isFP64bit() ? CC_MipsO32_FP64 : CC_MipsO32_FP32)
03660              : CC_MipsN_VarArg;
03661 }
03662 
03663 const MCPhysReg *MipsTargetLowering::MipsCC::shadowRegs() const {
03664   return Subtarget.isABI_O32() ? O32IntRegs : Mips64DPRegs;
03665 }
03666 
03667 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
03668                                               unsigned ByValSize,
03669                                               unsigned Align) {
03670   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
03671   const ArrayRef<MCPhysReg> IntArgRegs = intArgRegs();
03672   const MCPhysReg *ShadowRegs = shadowRegs();
03673   assert(!(ByValSize % RegSizeInBytes) && !(Align % RegSizeInBytes) &&
03674          "Byval argument's size and alignment should be a multiple of"
03675          "RegSizeInBytes.");
03676 
03677   ByVal.FirstIdx =
03678       CCInfo.getFirstUnallocated(IntArgRegs.data(), IntArgRegs.size());
03679 
03680   // If Align > RegSizeInBytes, the first arg register must be even.
03681   if ((Align > RegSizeInBytes) && (ByVal.FirstIdx % 2)) {
03682     CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
03683     ++ByVal.FirstIdx;
03684   }
03685 
03686   // Mark the registers allocated.
03687   for (unsigned I = ByVal.FirstIdx; ByValSize && (I < IntArgRegs.size());
03688        ByValSize -= RegSizeInBytes, ++I, ++ByVal.NumRegs)
03689     CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
03690 }
03691 
03692 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
03693                                          const SDNode *CallNode,
03694                                          bool IsSoftFloat) const {
03695   if (IsSoftFloat || Subtarget.isABI_O32())
03696     return VT;
03697 
03698   // Check if the original type was fp128.
03699   if (originalTypeIsF128(OrigTy, CallNode)) {
03700     assert(VT == MVT::i64);
03701     return MVT::f64;
03702   }
03703 
03704   return VT;
03705 }
03706 
03707 void MipsTargetLowering::
03708 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
03709               SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
03710               SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
03711               const MipsCC &CC, const ByValArgInfo &ByVal) const {
03712   MachineFunction &MF = DAG.getMachineFunction();
03713   MachineFrameInfo *MFI = MF.getFrameInfo();
03714   unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
03715   unsigned RegAreaSize = ByVal.NumRegs * GPRSizeInBytes;
03716   unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
03717   int FrameObjOffset;
03718 
03719   if (RegAreaSize)
03720     FrameObjOffset =
03721         (int)CC.reservedArgArea() -
03722         (int)((CC.intArgRegs().size() - ByVal.FirstIdx) * GPRSizeInBytes);
03723   else
03724     FrameObjOffset = ByVal.Address;
03725 
03726   // Create frame object.
03727   EVT PtrTy = getPointerTy();
03728   int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
03729   SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
03730   InVals.push_back(FIN);
03731 
03732   if (!ByVal.NumRegs)
03733     return;
03734 
03735   // Copy arg registers.
03736   MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
03737   const TargetRegisterClass *RC = getRegClassFor(RegTy);
03738 
03739   for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
03740     unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
03741     unsigned VReg = addLiveIn(MF, ArgReg, RC);
03742     unsigned Offset = I * GPRSizeInBytes;
03743     SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
03744                                    DAG.getConstant(Offset, PtrTy));
03745     SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
03746                                  StorePtr, MachinePointerInfo(FuncArg, Offset),
03747                                  false, false, 0);
03748     OutChains.push_back(Store);
03749   }
03750 }
03751 
03752 // Copy byVal arg to registers and stack.
03753 void MipsTargetLowering::
03754 passByValArg(SDValue Chain, SDLoc DL,
03755              std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
03756              SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
03757              MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
03758              const MipsCC &CC, const ByValArgInfo &ByVal,
03759              const ISD::ArgFlagsTy &Flags, bool isLittle) const {
03760   unsigned ByValSizeInBytes = Flags.getByValSize();
03761   unsigned OffsetInBytes = 0; // From beginning of struct
03762   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
03763   unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
03764   EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
03765 
03766   if (ByVal.NumRegs) {
03767     const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
03768     bool LeftoverBytes = (ByVal.NumRegs * RegSizeInBytes > ByValSizeInBytes);
03769     unsigned I = 0;
03770 
03771     // Copy words to registers.
03772     for (; I < ByVal.NumRegs - LeftoverBytes;
03773          ++I, OffsetInBytes += RegSizeInBytes) {
03774       SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
03775                                     DAG.getConstant(OffsetInBytes, PtrTy));
03776       SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
03777                                     MachinePointerInfo(), false, false, false,
03778                                     Alignment);
03779       MemOpChains.push_back(LoadVal.getValue(1));
03780       unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
03781       RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
03782     }
03783 
03784     // Return if the struct has been fully copied.
03785     if (ByValSizeInBytes == OffsetInBytes)
03786       return;
03787 
03788     // Copy the remainder of the byval argument with sub-word loads and shifts.
03789     if (LeftoverBytes) {
03790       assert((ByValSizeInBytes > OffsetInBytes) &&
03791              (ByValSizeInBytes < OffsetInBytes + RegSizeInBytes) &&
03792              "Size of the remainder should be smaller than RegSizeInBytes.");
03793       SDValue Val;
03794 
03795       for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
03796            OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
03797         unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
03798 
03799         if (RemainingSizeInBytes < LoadSizeInBytes)
03800           continue;
03801 
03802         // Load subword.
03803         SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
03804                                       DAG.getConstant(OffsetInBytes, PtrTy));
03805         SDValue LoadVal = DAG.getExtLoad(
03806             ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
03807             MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
03808             Alignment);
03809         MemOpChains.push_back(LoadVal.getValue(1));
03810 
03811         // Shift the loaded value.
03812         unsigned Shamt;
03813 
03814         if (isLittle)
03815           Shamt = TotalBytesLoaded * 8;
03816         else
03817           Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
03818 
03819         SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
03820                                     DAG.getConstant(Shamt, MVT::i32));
03821 
03822         if (Val.getNode())
03823           Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
03824         else
03825           Val = Shift;
03826 
03827         OffsetInBytes += LoadSizeInBytes;
03828         TotalBytesLoaded += LoadSizeInBytes;
03829         Alignment = std::min(Alignment, LoadSizeInBytes);
03830       }
03831 
03832       unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
03833       RegsToPass.push_back(std::make_pair(ArgReg, Val));
03834       return;
03835     }
03836   }
03837 
03838   // Copy remainder of byval arg to it with memcpy.
03839   unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
03840   SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
03841                             DAG.getConstant(OffsetInBytes, PtrTy));
03842   SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
03843                             DAG.getIntPtrConstant(ByVal.Address));
03844   Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
03845                         Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
03846                         MachinePointerInfo(), MachinePointerInfo());
03847   MemOpChains.push_back(Chain);
03848 }
03849 
03850 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
03851                                          const MipsCC &CC, SDValue Chain,
03852                                          SDLoc DL, SelectionDAG &DAG) const {
03853   const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
03854   const CCState &CCInfo = CC.getCCInfo();
03855   unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs.data(), ArgRegs.size());
03856   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
03857   MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
03858   const TargetRegisterClass *RC = getRegClassFor(RegTy);
03859   MachineFunction &MF = DAG.getMachineFunction();
03860   MachineFrameInfo *MFI = MF.getFrameInfo();
03861   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
03862 
03863   // Offset of the first variable argument from stack pointer.
03864   int VaArgOffset;
03865 
03866   if (ArgRegs.size() == Idx)
03867     VaArgOffset =
03868         RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSizeInBytes);
03869   else
03870     VaArgOffset = (int)CC.reservedArgArea() -
03871                   (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
03872 
03873   // Record the frame index of the first variable argument
03874   // which is a value necessary to VASTART.
03875   int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
03876   MipsFI->setVarArgsFrameIndex(FI);
03877 
03878   // Copy the integer registers that have not been used for argument passing
03879   // to the argument register save area. For O32, the save area is allocated
03880   // in the caller's stack frame, while for N32/64, it is allocated in the
03881   // callee's stack frame.
03882   for (unsigned I = Idx; I < ArgRegs.size();
03883        ++I, VaArgOffset += RegSizeInBytes) {
03884     unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
03885     SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
03886     FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
03887     SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
03888     SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
03889                                  MachinePointerInfo(), false, false, 0);
03890     cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
03891         (Value *)nullptr);
03892     OutChains.push_back(Store);
03893   }
03894 }