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