LLVM API Documentation

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