1 //===- MipsISelLowering.cpp - Mips DAG Lowering Implementation ------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that Mips uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "MipsISelLowering.h" 15 #include "MCTargetDesc/MipsBaseInfo.h" 16 #include "MCTargetDesc/MipsInstPrinter.h" 17 #include "MCTargetDesc/MipsMCTargetDesc.h" 18 #include "MipsCCState.h" 19 #include "MipsInstrInfo.h" 20 #include "MipsMachineFunction.h" 21 #include "MipsRegisterInfo.h" 22 #include "MipsSubtarget.h" 23 #include "MipsTargetMachine.h" 24 #include "MipsTargetObjectFile.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/ArrayRef.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/Statistic.h" 29 #include "llvm/ADT/StringRef.h" 30 #include "llvm/ADT/StringSwitch.h" 31 #include "llvm/CodeGen/CallingConvLower.h" 32 #include "llvm/CodeGen/FunctionLoweringInfo.h" 33 #include "llvm/CodeGen/ISDOpcodes.h" 34 #include "llvm/CodeGen/MachineBasicBlock.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/CodeGen/MachineFunction.h" 37 #include "llvm/CodeGen/MachineInstr.h" 38 #include "llvm/CodeGen/MachineInstrBuilder.h" 39 #include "llvm/CodeGen/MachineJumpTableInfo.h" 40 #include "llvm/CodeGen/MachineMemOperand.h" 41 #include "llvm/CodeGen/MachineOperand.h" 42 #include "llvm/CodeGen/MachineRegisterInfo.h" 43 #include "llvm/CodeGen/SelectionDAG.h" 44 #include "llvm/CodeGen/SelectionDAGNodes.h" 45 #include "llvm/CodeGen/TargetFrameLowering.h" 46 #include "llvm/CodeGen/TargetInstrInfo.h" 47 #include "llvm/CodeGen/TargetRegisterInfo.h" 48 #include "llvm/CodeGen/ValueTypes.h" 49 #include "llvm/CodeGenTypes/MachineValueType.h" 50 #include "llvm/IR/CallingConv.h" 51 #include "llvm/IR/Constants.h" 52 #include "llvm/IR/DataLayout.h" 53 #include "llvm/IR/DebugLoc.h" 54 #include "llvm/IR/DerivedTypes.h" 55 #include "llvm/IR/Function.h" 56 #include "llvm/IR/GlobalValue.h" 57 #include "llvm/IR/Module.h" 58 #include "llvm/IR/Type.h" 59 #include "llvm/IR/Value.h" 60 #include "llvm/MC/MCContext.h" 61 #include "llvm/Support/Casting.h" 62 #include "llvm/Support/CodeGen.h" 63 #include "llvm/Support/CommandLine.h" 64 #include "llvm/Support/Compiler.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/MathExtras.h" 67 #include "llvm/Target/TargetMachine.h" 68 #include "llvm/Target/TargetOptions.h" 69 #include <algorithm> 70 #include <cassert> 71 #include <cctype> 72 #include <cstdint> 73 #include <deque> 74 #include <iterator> 75 #include <utility> 76 #include <vector> 77 78 using namespace llvm; 79 80 #define DEBUG_TYPE "mips-lower" 81 82 STATISTIC(NumTailCalls, "Number of tail calls"); 83 84 static cl::opt<bool> 85 NoZeroDivCheck("mno-check-zero-division", cl::Hidden, 86 cl::desc("MIPS: Don't trap on integer division by zero."), 87 cl::init(false)); 88 89 extern cl::opt<bool> EmitJalrReloc; 90 91 static const MCPhysReg Mips64DPRegs[8] = { 92 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64, 93 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64 94 }; 95 96 // The MIPS MSA ABI passes vector arguments in the integer register set. 97 // The number of integer registers used is dependant on the ABI used. 98 MVT MipsTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 99 CallingConv::ID CC, 100 EVT VT) const { 101 if (!VT.isVector()) 102 return getRegisterType(Context, VT); 103 104 if (VT.isPow2VectorType() && VT.getVectorElementType().isRound()) 105 return Subtarget.isABI_O32() || VT.getSizeInBits() == 32 ? MVT::i32 106 : MVT::i64; 107 return getRegisterType(Context, VT.getVectorElementType()); 108 } 109 110 unsigned MipsTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 111 CallingConv::ID CC, 112 EVT VT) const { 113 if (VT.isVector()) { 114 if (VT.isPow2VectorType() && VT.getVectorElementType().isRound()) 115 return divideCeil(VT.getSizeInBits(), Subtarget.isABI_O32() ? 32 : 64); 116 return VT.getVectorNumElements() * 117 getNumRegisters(Context, VT.getVectorElementType()); 118 } 119 return MipsTargetLowering::getNumRegisters(Context, VT); 120 } 121 122 unsigned MipsTargetLowering::getVectorTypeBreakdownForCallingConv( 123 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, 124 unsigned &NumIntermediates, MVT &RegisterVT) const { 125 if (VT.isPow2VectorType() && VT.getVectorElementType().isRound()) { 126 IntermediateVT = getRegisterTypeForCallingConv(Context, CC, VT); 127 RegisterVT = IntermediateVT.getSimpleVT(); 128 NumIntermediates = getNumRegistersForCallingConv(Context, CC, VT); 129 return NumIntermediates; 130 } 131 IntermediateVT = VT.getVectorElementType(); 132 NumIntermediates = VT.getVectorNumElements(); 133 RegisterVT = getRegisterType(Context, IntermediateVT); 134 return NumIntermediates * getNumRegisters(Context, IntermediateVT); 135 } 136 137 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const { 138 MachineFunction &MF = DAG.getMachineFunction(); 139 MipsFunctionInfo *FI = MF.getInfo<MipsFunctionInfo>(); 140 return DAG.getRegister(FI->getGlobalBaseReg(MF), Ty); 141 } 142 143 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty, 144 SelectionDAG &DAG, 145 unsigned Flag) const { 146 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag); 147 } 148 149 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty, 150 SelectionDAG &DAG, 151 unsigned Flag) const { 152 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag); 153 } 154 155 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty, 156 SelectionDAG &DAG, 157 unsigned Flag) const { 158 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); 159 } 160 161 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, 162 SelectionDAG &DAG, 163 unsigned Flag) const { 164 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); 165 } 166 167 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, 168 SelectionDAG &DAG, 169 unsigned Flag) const { 170 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 171 N->getOffset(), Flag); 172 } 173 174 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const { 175 switch ((MipsISD::NodeType)Opcode) { 176 case MipsISD::FIRST_NUMBER: break; 177 case MipsISD::JmpLink: return "MipsISD::JmpLink"; 178 case MipsISD::TailCall: return "MipsISD::TailCall"; 179 case MipsISD::Highest: return "MipsISD::Highest"; 180 case MipsISD::Higher: return "MipsISD::Higher"; 181 case MipsISD::Hi: return "MipsISD::Hi"; 182 case MipsISD::Lo: return "MipsISD::Lo"; 183 case MipsISD::GotHi: return "MipsISD::GotHi"; 184 case MipsISD::TlsHi: return "MipsISD::TlsHi"; 185 case MipsISD::GPRel: return "MipsISD::GPRel"; 186 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer"; 187 case MipsISD::Ret: return "MipsISD::Ret"; 188 case MipsISD::ERet: return "MipsISD::ERet"; 189 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN"; 190 case MipsISD::FAbs: return "MipsISD::FAbs"; 191 case MipsISD::FMS: return "MipsISD::FMS"; 192 case MipsISD::FPBrcond: return "MipsISD::FPBrcond"; 193 case MipsISD::FPCmp: return "MipsISD::FPCmp"; 194 case MipsISD::FSELECT: return "MipsISD::FSELECT"; 195 case MipsISD::MTC1_D64: return "MipsISD::MTC1_D64"; 196 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T"; 197 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F"; 198 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP"; 199 case MipsISD::MFHI: return "MipsISD::MFHI"; 200 case MipsISD::MFLO: return "MipsISD::MFLO"; 201 case MipsISD::MTLOHI: return "MipsISD::MTLOHI"; 202 case MipsISD::Mult: return "MipsISD::Mult"; 203 case MipsISD::Multu: return "MipsISD::Multu"; 204 case MipsISD::MAdd: return "MipsISD::MAdd"; 205 case MipsISD::MAddu: return "MipsISD::MAddu"; 206 case MipsISD::MSub: return "MipsISD::MSub"; 207 case MipsISD::MSubu: return "MipsISD::MSubu"; 208 case MipsISD::DivRem: return "MipsISD::DivRem"; 209 case MipsISD::DivRemU: return "MipsISD::DivRemU"; 210 case MipsISD::DivRem16: return "MipsISD::DivRem16"; 211 case MipsISD::DivRemU16: return "MipsISD::DivRemU16"; 212 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64"; 213 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64"; 214 case MipsISD::Wrapper: return "MipsISD::Wrapper"; 215 case MipsISD::DynAlloc: return "MipsISD::DynAlloc"; 216 case MipsISD::Sync: return "MipsISD::Sync"; 217 case MipsISD::Ext: return "MipsISD::Ext"; 218 case MipsISD::Ins: return "MipsISD::Ins"; 219 case MipsISD::CIns: return "MipsISD::CIns"; 220 case MipsISD::LWL: return "MipsISD::LWL"; 221 case MipsISD::LWR: return "MipsISD::LWR"; 222 case MipsISD::SWL: return "MipsISD::SWL"; 223 case MipsISD::SWR: return "MipsISD::SWR"; 224 case MipsISD::LDL: return "MipsISD::LDL"; 225 case MipsISD::LDR: return "MipsISD::LDR"; 226 case MipsISD::SDL: return "MipsISD::SDL"; 227 case MipsISD::SDR: return "MipsISD::SDR"; 228 case MipsISD::EXTP: return "MipsISD::EXTP"; 229 case MipsISD::EXTPDP: return "MipsISD::EXTPDP"; 230 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H"; 231 case MipsISD::EXTR_W: return "MipsISD::EXTR_W"; 232 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W"; 233 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W"; 234 case MipsISD::SHILO: return "MipsISD::SHILO"; 235 case MipsISD::MTHLIP: return "MipsISD::MTHLIP"; 236 case MipsISD::MULSAQ_S_W_PH: return "MipsISD::MULSAQ_S_W_PH"; 237 case MipsISD::MAQ_S_W_PHL: return "MipsISD::MAQ_S_W_PHL"; 238 case MipsISD::MAQ_S_W_PHR: return "MipsISD::MAQ_S_W_PHR"; 239 case MipsISD::MAQ_SA_W_PHL: return "MipsISD::MAQ_SA_W_PHL"; 240 case MipsISD::MAQ_SA_W_PHR: return "MipsISD::MAQ_SA_W_PHR"; 241 case MipsISD::DOUBLE_SELECT_I: return "MipsISD::DOUBLE_SELECT_I"; 242 case MipsISD::DOUBLE_SELECT_I64: return "MipsISD::DOUBLE_SELECT_I64"; 243 case MipsISD::DPAU_H_QBL: return "MipsISD::DPAU_H_QBL"; 244 case MipsISD::DPAU_H_QBR: return "MipsISD::DPAU_H_QBR"; 245 case MipsISD::DPSU_H_QBL: return "MipsISD::DPSU_H_QBL"; 246 case MipsISD::DPSU_H_QBR: return "MipsISD::DPSU_H_QBR"; 247 case MipsISD::DPAQ_S_W_PH: return "MipsISD::DPAQ_S_W_PH"; 248 case MipsISD::DPSQ_S_W_PH: return "MipsISD::DPSQ_S_W_PH"; 249 case MipsISD::DPAQ_SA_L_W: return "MipsISD::DPAQ_SA_L_W"; 250 case MipsISD::DPSQ_SA_L_W: return "MipsISD::DPSQ_SA_L_W"; 251 case MipsISD::DPA_W_PH: return "MipsISD::DPA_W_PH"; 252 case MipsISD::DPS_W_PH: return "MipsISD::DPS_W_PH"; 253 case MipsISD::DPAQX_S_W_PH: return "MipsISD::DPAQX_S_W_PH"; 254 case MipsISD::DPAQX_SA_W_PH: return "MipsISD::DPAQX_SA_W_PH"; 255 case MipsISD::DPAX_W_PH: return "MipsISD::DPAX_W_PH"; 256 case MipsISD::DPSX_W_PH: return "MipsISD::DPSX_W_PH"; 257 case MipsISD::DPSQX_S_W_PH: return "MipsISD::DPSQX_S_W_PH"; 258 case MipsISD::DPSQX_SA_W_PH: return "MipsISD::DPSQX_SA_W_PH"; 259 case MipsISD::MULSA_W_PH: return "MipsISD::MULSA_W_PH"; 260 case MipsISD::MULT: return "MipsISD::MULT"; 261 case MipsISD::MULTU: return "MipsISD::MULTU"; 262 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP"; 263 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP"; 264 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP"; 265 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP"; 266 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP"; 267 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP"; 268 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP"; 269 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP"; 270 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP"; 271 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO"; 272 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO"; 273 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO"; 274 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO"; 275 case MipsISD::VCEQ: return "MipsISD::VCEQ"; 276 case MipsISD::VCLE_S: return "MipsISD::VCLE_S"; 277 case MipsISD::VCLE_U: return "MipsISD::VCLE_U"; 278 case MipsISD::VCLT_S: return "MipsISD::VCLT_S"; 279 case MipsISD::VCLT_U: return "MipsISD::VCLT_U"; 280 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT"; 281 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT"; 282 case MipsISD::VNOR: return "MipsISD::VNOR"; 283 case MipsISD::VSHF: return "MipsISD::VSHF"; 284 case MipsISD::SHF: return "MipsISD::SHF"; 285 case MipsISD::ILVEV: return "MipsISD::ILVEV"; 286 case MipsISD::ILVOD: return "MipsISD::ILVOD"; 287 case MipsISD::ILVL: return "MipsISD::ILVL"; 288 case MipsISD::ILVR: return "MipsISD::ILVR"; 289 case MipsISD::PCKEV: return "MipsISD::PCKEV"; 290 case MipsISD::PCKOD: return "MipsISD::PCKOD"; 291 case MipsISD::INSVE: return "MipsISD::INSVE"; 292 } 293 return nullptr; 294 } 295 296 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM, 297 const MipsSubtarget &STI) 298 : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) { 299 // Mips does not have i1 type, so use i32 for 300 // setcc operations results (slt, sgt, ...). 301 setBooleanContents(ZeroOrOneBooleanContent); 302 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 303 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA 304 // does. Integer booleans still use 0 and 1. 305 if (Subtarget.hasMips32r6()) 306 setBooleanContents(ZeroOrOneBooleanContent, 307 ZeroOrNegativeOneBooleanContent); 308 309 // Load extented operations for i1 types must be promoted 310 for (MVT VT : MVT::integer_valuetypes()) { 311 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote); 312 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 313 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 314 } 315 316 // MIPS doesn't have extending float->double load/store. Set LoadExtAction 317 // for f32, f16 318 for (MVT VT : MVT::fp_valuetypes()) { 319 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 320 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 321 } 322 323 // Set LoadExtAction for f16 vectors to Expand 324 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 325 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements()); 326 if (F16VT.isValid()) 327 setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand); 328 } 329 330 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 331 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 332 333 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 334 335 // Used by legalize types to correctly generate the setcc result. 336 // Without this, every float setcc comes with a AND/OR with the result, 337 // we don't want this, since the fpcmp result goes to a flag register, 338 // which is used implicitly by brcond and select operations. 339 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 340 341 // Mips Custom Operations 342 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 343 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 344 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 345 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 346 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 347 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 348 setOperationAction(ISD::SELECT, MVT::f32, Custom); 349 setOperationAction(ISD::SELECT, MVT::f64, Custom); 350 setOperationAction(ISD::SELECT, MVT::i32, Custom); 351 setOperationAction(ISD::SETCC, MVT::f32, Custom); 352 setOperationAction(ISD::SETCC, MVT::f64, Custom); 353 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 354 setOperationAction(ISD::FABS, MVT::f32, Custom); 355 setOperationAction(ISD::FABS, MVT::f64, Custom); 356 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 357 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 358 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 359 360 // Lower fmin/fmax/fclass operations for MIPS R6. 361 if (Subtarget.hasMips32r6()) { 362 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 363 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 364 setOperationAction(ISD::FMINNUM, MVT::f32, Expand); 365 setOperationAction(ISD::FMAXNUM, MVT::f32, Expand); 366 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 367 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 368 setOperationAction(ISD::FMINNUM, MVT::f64, Expand); 369 setOperationAction(ISD::FMAXNUM, MVT::f64, Expand); 370 setOperationAction(ISD::IS_FPCLASS, MVT::f32, Legal); 371 setOperationAction(ISD::IS_FPCLASS, MVT::f64, Legal); 372 } else { 373 setOperationAction(ISD::FCANONICALIZE, MVT::f32, Custom); 374 setOperationAction(ISD::FCANONICALIZE, MVT::f64, Custom); 375 } 376 377 if (Subtarget.isGP64bit()) { 378 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 379 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 380 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 381 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 382 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 383 setOperationAction(ISD::SELECT, MVT::i64, Custom); 384 if (Subtarget.hasMips64r6()) { 385 setOperationAction(ISD::LOAD, MVT::i64, Legal); 386 setOperationAction(ISD::STORE, MVT::i64, Legal); 387 } else { 388 setOperationAction(ISD::LOAD, MVT::i64, Custom); 389 setOperationAction(ISD::STORE, MVT::i64, Custom); 390 } 391 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 392 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 393 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 394 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 395 } 396 397 if (!Subtarget.isGP64bit()) { 398 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 399 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 400 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 401 } 402 403 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 404 if (Subtarget.isGP64bit()) 405 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 406 407 setOperationAction(ISD::SDIV, MVT::i32, Expand); 408 setOperationAction(ISD::SREM, MVT::i32, Expand); 409 setOperationAction(ISD::UDIV, MVT::i32, Expand); 410 setOperationAction(ISD::UREM, MVT::i32, Expand); 411 setOperationAction(ISD::SDIV, MVT::i64, Expand); 412 setOperationAction(ISD::SREM, MVT::i64, Expand); 413 setOperationAction(ISD::UDIV, MVT::i64, Expand); 414 setOperationAction(ISD::UREM, MVT::i64, Expand); 415 416 // Operations not directly supported by Mips. 417 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 418 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 419 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 420 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 421 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 422 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 423 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 424 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 425 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 426 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 427 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 428 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 429 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 430 if (Subtarget.hasCnMips()) { 431 setOperationAction(ISD::CTPOP, MVT::i32, Legal); 432 setOperationAction(ISD::CTPOP, MVT::i64, Legal); 433 } else { 434 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 435 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 436 } 437 setOperationAction(ISD::CTTZ, MVT::i32, Expand); 438 setOperationAction(ISD::CTTZ, MVT::i64, Expand); 439 setOperationAction(ISD::ROTL, MVT::i32, Expand); 440 setOperationAction(ISD::ROTL, MVT::i64, Expand); 441 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 442 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 443 444 if (!Subtarget.hasMips32r2()) 445 setOperationAction(ISD::ROTR, MVT::i32, Expand); 446 447 if (!Subtarget.hasMips64r2()) 448 setOperationAction(ISD::ROTR, MVT::i64, Expand); 449 450 setOperationAction(ISD::FSIN, MVT::f32, Expand); 451 setOperationAction(ISD::FSIN, MVT::f64, Expand); 452 setOperationAction(ISD::FCOS, MVT::f32, Expand); 453 setOperationAction(ISD::FCOS, MVT::f64, Expand); 454 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 455 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 456 setOperationAction(ISD::FPOW, MVT::f32, Expand); 457 setOperationAction(ISD::FPOW, MVT::f64, Expand); 458 setOperationAction(ISD::FLOG, MVT::f32, Expand); 459 setOperationAction(ISD::FLOG2, MVT::f32, Expand); 460 setOperationAction(ISD::FLOG10, MVT::f32, Expand); 461 setOperationAction(ISD::FEXP, MVT::f32, Expand); 462 setOperationAction(ISD::FMA, MVT::f32, Expand); 463 setOperationAction(ISD::FMA, MVT::f64, Expand); 464 setOperationAction(ISD::FREM, MVT::f32, Expand); 465 setOperationAction(ISD::FREM, MVT::f64, Expand); 466 467 // Lower f16 conversion operations into library calls 468 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 469 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 470 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 471 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 472 473 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom); 474 475 setOperationAction(ISD::VASTART, MVT::Other, Custom); 476 setOperationAction(ISD::VAARG, MVT::Other, Custom); 477 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 478 setOperationAction(ISD::VAEND, MVT::Other, Expand); 479 480 // Use the default for now 481 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 482 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 483 484 if (!Subtarget.isGP64bit()) { 485 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 486 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 487 } 488 489 if (!Subtarget.hasMips32r2()) { 490 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 491 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 492 } 493 494 // MIPS16 lacks MIPS32's clz and clo instructions. 495 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode()) 496 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 497 if (!Subtarget.hasMips64()) 498 setOperationAction(ISD::CTLZ, MVT::i64, Expand); 499 500 if (!Subtarget.hasMips32r2()) 501 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 502 if (!Subtarget.hasMips64r2()) 503 setOperationAction(ISD::BSWAP, MVT::i64, Expand); 504 505 if (Subtarget.isGP64bit() && Subtarget.hasMips64r6()) { 506 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Legal); 507 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Legal); 508 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Legal); 509 setTruncStoreAction(MVT::i64, MVT::i32, Legal); 510 } else if (Subtarget.isGP64bit()) { 511 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom); 512 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom); 513 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom); 514 setTruncStoreAction(MVT::i64, MVT::i32, Custom); 515 } 516 517 setOperationAction(ISD::TRAP, MVT::Other, Legal); 518 519 setTargetDAGCombine({ISD::SDIVREM, ISD::UDIVREM, ISD::SELECT, ISD::AND, 520 ISD::OR, ISD::ADD, ISD::SUB, ISD::AssertZext, ISD::SHL}); 521 522 if (Subtarget.isGP64bit()) 523 setMaxAtomicSizeInBitsSupported(64); 524 else 525 setMaxAtomicSizeInBitsSupported(32); 526 527 setMinFunctionAlignment(Subtarget.isGP64bit() ? Align(8) : Align(4)); 528 529 // The arguments on the stack are defined in terms of 4-byte slots on O32 530 // and 8-byte slots on N32/N64. 531 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? Align(8) 532 : Align(4)); 533 534 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP); 535 536 MaxStoresPerMemcpy = 16; 537 538 isMicroMips = Subtarget.inMicroMipsMode(); 539 } 540 541 const MipsTargetLowering * 542 MipsTargetLowering::create(const MipsTargetMachine &TM, 543 const MipsSubtarget &STI) { 544 if (STI.inMips16Mode()) 545 return createMips16TargetLowering(TM, STI); 546 547 return createMipsSETargetLowering(TM, STI); 548 } 549 550 // Create a fast isel object. 551 FastISel * 552 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 553 const TargetLibraryInfo *libInfo) const { 554 const MipsTargetMachine &TM = 555 static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget()); 556 557 // We support only the standard encoding [MIPS32,MIPS32R5] ISAs. 558 bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() && 559 !Subtarget.hasMips32r6() && !Subtarget.inMips16Mode() && 560 !Subtarget.inMicroMipsMode(); 561 562 // Disable if either of the following is true: 563 // We do not generate PIC, the ABI is not O32, XGOT is being used. 564 if (!TM.isPositionIndependent() || !TM.getABI().IsO32() || 565 Subtarget.useXGOT()) 566 UseFastISel = false; 567 568 return UseFastISel ? Mips::createFastISel(funcInfo, libInfo) : nullptr; 569 } 570 571 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 572 EVT VT) const { 573 if (!VT.isVector()) 574 return MVT::i32; 575 return VT.changeVectorElementTypeToInteger(); 576 } 577 578 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG, 579 TargetLowering::DAGCombinerInfo &DCI, 580 const MipsSubtarget &Subtarget) { 581 if (DCI.isBeforeLegalizeOps()) 582 return SDValue(); 583 584 EVT Ty = N->getValueType(0); 585 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64; 586 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64; 587 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 : 588 MipsISD::DivRemU16; 589 SDLoc DL(N); 590 591 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue, 592 N->getOperand(0), N->getOperand(1)); 593 SDValue InChain = DAG.getEntryNode(); 594 SDValue InGlue = DivRem; 595 596 // insert MFLO 597 if (N->hasAnyUseOfValue(0)) { 598 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty, 599 InGlue); 600 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo); 601 InChain = CopyFromLo.getValue(1); 602 InGlue = CopyFromLo.getValue(2); 603 } 604 605 // insert MFHI 606 if (N->hasAnyUseOfValue(1)) { 607 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL, 608 HI, Ty, InGlue); 609 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi); 610 } 611 612 return SDValue(); 613 } 614 615 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) { 616 switch (CC) { 617 default: llvm_unreachable("Unknown fp condition code!"); 618 case ISD::SETEQ: 619 case ISD::SETOEQ: return Mips::FCOND_OEQ; 620 case ISD::SETUNE: return Mips::FCOND_UNE; 621 case ISD::SETLT: 622 case ISD::SETOLT: return Mips::FCOND_OLT; 623 case ISD::SETGT: 624 case ISD::SETOGT: return Mips::FCOND_OGT; 625 case ISD::SETLE: 626 case ISD::SETOLE: return Mips::FCOND_OLE; 627 case ISD::SETGE: 628 case ISD::SETOGE: return Mips::FCOND_OGE; 629 case ISD::SETULT: return Mips::FCOND_ULT; 630 case ISD::SETULE: return Mips::FCOND_ULE; 631 case ISD::SETUGT: return Mips::FCOND_UGT; 632 case ISD::SETUGE: return Mips::FCOND_UGE; 633 case ISD::SETUO: return Mips::FCOND_UN; 634 case ISD::SETO: return Mips::FCOND_OR; 635 case ISD::SETNE: 636 case ISD::SETONE: return Mips::FCOND_ONE; 637 case ISD::SETUEQ: return Mips::FCOND_UEQ; 638 } 639 } 640 641 /// This function returns true if the floating point conditional branches and 642 /// conditional moves which use condition code CC should be inverted. 643 static bool invertFPCondCodeUser(Mips::CondCode CC) { 644 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT) 645 return false; 646 647 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) && 648 "Illegal Condition Code"); 649 650 return true; 651 } 652 653 // Creates and returns an FPCmp node from a setcc node. 654 // Returns Op if setcc is not a floating point comparison. 655 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) { 656 // must be a SETCC node 657 if (Op.getOpcode() != ISD::SETCC) 658 return Op; 659 660 SDValue LHS = Op.getOperand(0); 661 662 if (!LHS.getValueType().isFloatingPoint()) 663 return Op; 664 665 SDValue RHS = Op.getOperand(1); 666 SDLoc DL(Op); 667 668 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of 669 // node if necessary. 670 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 671 672 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS, 673 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32)); 674 } 675 676 // Creates and returns a CMovFPT/F node. 677 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True, 678 SDValue False, const SDLoc &DL) { 679 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2)); 680 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue()); 681 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32); 682 683 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL, 684 True.getValueType(), True, FCC0, False, Cond); 685 } 686 687 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG, 688 TargetLowering::DAGCombinerInfo &DCI, 689 const MipsSubtarget &Subtarget) { 690 if (DCI.isBeforeLegalizeOps()) 691 return SDValue(); 692 693 SDValue SetCC = N->getOperand(0); 694 695 if ((SetCC.getOpcode() != ISD::SETCC) || 696 !SetCC.getOperand(0).getValueType().isInteger()) 697 return SDValue(); 698 699 SDValue False = N->getOperand(2); 700 EVT FalseTy = False.getValueType(); 701 702 if (!FalseTy.isInteger()) 703 return SDValue(); 704 705 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False); 706 707 // If the RHS (False) is 0, we swap the order of the operands 708 // of ISD::SELECT (obviously also inverting the condition) so that we can 709 // take advantage of conditional moves using the $0 register. 710 // Example: 711 // return (a != 0) ? x : 0; 712 // load $reg, x 713 // movz $reg, $0, a 714 if (!FalseC) 715 return SDValue(); 716 717 const SDLoc DL(N); 718 719 if (!FalseC->getZExtValue()) { 720 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get(); 721 SDValue True = N->getOperand(1); 722 723 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0), 724 SetCC.getOperand(1), 725 ISD::getSetCCInverse(CC, SetCC.getValueType())); 726 727 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True); 728 } 729 730 // If both operands are integer constants there's a possibility that we 731 // can do some interesting optimizations. 732 SDValue True = N->getOperand(1); 733 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True); 734 735 if (!TrueC || !True.getValueType().isInteger()) 736 return SDValue(); 737 738 // We'll also ignore MVT::i64 operands as this optimizations proves 739 // to be ineffective because of the required sign extensions as the result 740 // of a SETCC operator is always MVT::i32 for non-vector types. 741 if (True.getValueType() == MVT::i64) 742 return SDValue(); 743 744 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue(); 745 746 // 1) (a < x) ? y : y-1 747 // slti $reg1, a, x 748 // addiu $reg2, $reg1, y-1 749 if (Diff == 1) 750 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False); 751 752 // 2) (a < x) ? y-1 : y 753 // slti $reg1, a, x 754 // xor $reg1, $reg1, 1 755 // addiu $reg2, $reg1, y-1 756 if (Diff == -1) { 757 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get(); 758 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0), 759 SetCC.getOperand(1), 760 ISD::getSetCCInverse(CC, SetCC.getValueType())); 761 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True); 762 } 763 764 // Could not optimize. 765 return SDValue(); 766 } 767 768 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG, 769 TargetLowering::DAGCombinerInfo &DCI, 770 const MipsSubtarget &Subtarget) { 771 if (DCI.isBeforeLegalizeOps()) 772 return SDValue(); 773 774 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2); 775 776 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse); 777 if (!FalseC || FalseC->getZExtValue()) 778 return SDValue(); 779 780 // Since RHS (False) is 0, we swap the order of the True/False operands 781 // (obviously also inverting the condition) so that we can 782 // take advantage of conditional moves using the $0 register. 783 // Example: 784 // return (a != 0) ? x : 0; 785 // load $reg, x 786 // movz $reg, $0, a 787 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F : 788 MipsISD::CMovFP_T; 789 790 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3); 791 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(), 792 ValueIfFalse, FCC, ValueIfTrue, Glue); 793 } 794 795 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 796 TargetLowering::DAGCombinerInfo &DCI, 797 const MipsSubtarget &Subtarget) { 798 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert()) 799 return SDValue(); 800 801 SDValue FirstOperand = N->getOperand(0); 802 unsigned FirstOperandOpc = FirstOperand.getOpcode(); 803 SDValue Mask = N->getOperand(1); 804 EVT ValTy = N->getValueType(0); 805 SDLoc DL(N); 806 807 uint64_t Pos = 0; 808 unsigned SMPos, SMSize; 809 ConstantSDNode *CN; 810 SDValue NewOperand; 811 unsigned Opc; 812 813 // Op's second operand must be a shifted mask. 814 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) || 815 !isShiftedMask_64(CN->getZExtValue(), SMPos, SMSize)) 816 return SDValue(); 817 818 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) { 819 // Pattern match EXT. 820 // $dst = and ((sra or srl) $src , pos), (2**size - 1) 821 // => ext $dst, $src, pos, size 822 823 // The second operand of the shift must be an immediate. 824 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1)))) 825 return SDValue(); 826 827 Pos = CN->getZExtValue(); 828 829 // Return if the shifted mask does not start at bit 0 or the sum of its size 830 // and Pos exceeds the word's size. 831 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits()) 832 return SDValue(); 833 834 Opc = MipsISD::Ext; 835 NewOperand = FirstOperand.getOperand(0); 836 } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) { 837 // Pattern match CINS. 838 // $dst = and (shl $src , pos), mask 839 // => cins $dst, $src, pos, size 840 // mask is a shifted mask with consecutive 1's, pos = shift amount, 841 // size = population count. 842 843 // The second operand of the shift must be an immediate. 844 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1)))) 845 return SDValue(); 846 847 Pos = CN->getZExtValue(); 848 849 if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 || 850 Pos + SMSize > ValTy.getSizeInBits()) 851 return SDValue(); 852 853 NewOperand = FirstOperand.getOperand(0); 854 // SMSize is 'location' (position) in this case, not size. 855 SMSize--; 856 Opc = MipsISD::CIns; 857 } else { 858 // Pattern match EXT. 859 // $dst = and $src, (2**size - 1) , if size > 16 860 // => ext $dst, $src, pos, size , pos = 0 861 862 // If the mask is <= 0xffff, andi can be used instead. 863 if (CN->getZExtValue() <= 0xffff) 864 return SDValue(); 865 866 // Return if the mask doesn't start at position 0. 867 if (SMPos) 868 return SDValue(); 869 870 Opc = MipsISD::Ext; 871 NewOperand = FirstOperand; 872 } 873 return DAG.getNode(Opc, DL, ValTy, NewOperand, 874 DAG.getConstant(Pos, DL, MVT::i32), 875 DAG.getConstant(SMSize, DL, MVT::i32)); 876 } 877 878 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 879 TargetLowering::DAGCombinerInfo &DCI, 880 const MipsSubtarget &Subtarget) { 881 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert()) 882 return SDValue(); 883 884 SDValue FirstOperand = N->getOperand(0), SecondOperand = N->getOperand(1); 885 unsigned SMPos0, SMSize0, SMPos1, SMSize1; 886 ConstantSDNode *CN, *CN1; 887 888 if ((FirstOperand.getOpcode() == ISD::AND && 889 SecondOperand.getOpcode() == ISD::SHL) || 890 (FirstOperand.getOpcode() == ISD::SHL && 891 SecondOperand.getOpcode() == ISD::AND)) { 892 // Pattern match INS. 893 // $dst = or (and $src1, (2**size0 - 1)), (shl $src2, size0) 894 // ==> ins $src1, $src2, pos, size, pos = size0, size = 32 - pos; 895 // Or: 896 // $dst = or (shl $src2, size0), (and $src1, (2**size0 - 1)) 897 // ==> ins $src1, $src2, pos, size, pos = size0, size = 32 - pos; 898 SDValue AndOperand0 = FirstOperand.getOpcode() == ISD::AND 899 ? FirstOperand.getOperand(0) 900 : SecondOperand.getOperand(0); 901 SDValue ShlOperand0 = FirstOperand.getOpcode() == ISD::AND 902 ? SecondOperand.getOperand(0) 903 : FirstOperand.getOperand(0); 904 SDValue AndMask = FirstOperand.getOpcode() == ISD::AND 905 ? FirstOperand.getOperand(1) 906 : SecondOperand.getOperand(1); 907 if (!(CN = dyn_cast<ConstantSDNode>(AndMask)) || 908 !isShiftedMask_64(CN->getZExtValue(), SMPos0, SMSize0)) 909 return SDValue(); 910 911 SDValue ShlShift = FirstOperand.getOpcode() == ISD::AND 912 ? SecondOperand.getOperand(1) 913 : FirstOperand.getOperand(1); 914 if (!(CN = dyn_cast<ConstantSDNode>(ShlShift))) 915 return SDValue(); 916 uint64_t ShlShiftValue = CN->getZExtValue(); 917 918 if (SMPos0 != 0 || SMSize0 != ShlShiftValue) 919 return SDValue(); 920 921 SDLoc DL(N); 922 EVT ValTy = N->getValueType(0); 923 SMPos1 = ShlShiftValue; 924 assert(SMPos1 < ValTy.getSizeInBits()); 925 SMSize1 = (ValTy == MVT::i64 ? 64 : 32) - SMPos1; 926 return DAG.getNode(MipsISD::Ins, DL, ValTy, ShlOperand0, 927 DAG.getConstant(SMPos1, DL, MVT::i32), 928 DAG.getConstant(SMSize1, DL, MVT::i32), AndOperand0); 929 } 930 931 // See if Op's first operand matches (and $src1 , mask0). 932 if (FirstOperand.getOpcode() != ISD::AND) 933 return SDValue(); 934 935 // Pattern match INS. 936 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1), 937 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1 938 // => ins $dst, $src, size, pos, $src1 939 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) || 940 !isShiftedMask_64(~CN->getSExtValue(), SMPos0, SMSize0)) 941 return SDValue(); 942 943 // See if Op's second operand matches (and (shl $src, pos), mask1). 944 if (SecondOperand.getOpcode() == ISD::AND && 945 SecondOperand.getOperand(0).getOpcode() == ISD::SHL) { 946 947 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand.getOperand(1))) || 948 !isShiftedMask_64(CN->getZExtValue(), SMPos1, SMSize1)) 949 return SDValue(); 950 951 // The shift masks must have the same position and size. 952 if (SMPos0 != SMPos1 || SMSize0 != SMSize1) 953 return SDValue(); 954 955 SDValue Shl = SecondOperand.getOperand(0); 956 957 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1)))) 958 return SDValue(); 959 960 unsigned Shamt = CN->getZExtValue(); 961 962 // Return if the shift amount and the first bit position of mask are not the 963 // same. 964 EVT ValTy = N->getValueType(0); 965 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits())) 966 return SDValue(); 967 968 SDLoc DL(N); 969 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0), 970 DAG.getConstant(SMPos0, DL, MVT::i32), 971 DAG.getConstant(SMSize0, DL, MVT::i32), 972 FirstOperand.getOperand(0)); 973 } else { 974 // Pattern match DINS. 975 // $dst = or (and $src, mask0), mask1 976 // where mask0 = ((1 << SMSize0) -1) << SMPos0 977 // => dins $dst, $src, pos, size 978 if (~CN->getSExtValue() == ((((int64_t)1 << SMSize0) - 1) << SMPos0) && 979 ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) || 980 (SMSize0 + SMPos0 <= 32))) { 981 // Check if AND instruction has constant as argument 982 bool isConstCase = SecondOperand.getOpcode() != ISD::AND; 983 if (SecondOperand.getOpcode() == ISD::AND) { 984 if (!(CN1 = dyn_cast<ConstantSDNode>(SecondOperand->getOperand(1)))) 985 return SDValue(); 986 } else { 987 if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)))) 988 return SDValue(); 989 } 990 // Don't generate INS if constant OR operand doesn't fit into bits 991 // cleared by constant AND operand. 992 if (CN->getSExtValue() & CN1->getSExtValue()) 993 return SDValue(); 994 995 SDLoc DL(N); 996 EVT ValTy = N->getOperand(0)->getValueType(0); 997 SDValue Const1; 998 SDValue SrlX; 999 if (!isConstCase) { 1000 Const1 = DAG.getConstant(SMPos0, DL, MVT::i32); 1001 SrlX = DAG.getNode(ISD::SRL, DL, SecondOperand->getValueType(0), 1002 SecondOperand, Const1); 1003 } 1004 return DAG.getNode( 1005 MipsISD::Ins, DL, N->getValueType(0), 1006 isConstCase 1007 ? DAG.getConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy) 1008 : SrlX, 1009 DAG.getConstant(SMPos0, DL, MVT::i32), 1010 DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31 1011 : SMSize0, 1012 DL, MVT::i32), 1013 FirstOperand->getOperand(0)); 1014 } 1015 return SDValue(); 1016 } 1017 } 1018 1019 static SDValue performMADD_MSUBCombine(SDNode *ROOTNode, SelectionDAG &CurDAG, 1020 const MipsSubtarget &Subtarget) { 1021 // ROOTNode must have a multiplication as an operand for the match to be 1022 // successful. 1023 if (ROOTNode->getOperand(0).getOpcode() != ISD::MUL && 1024 ROOTNode->getOperand(1).getOpcode() != ISD::MUL) 1025 return SDValue(); 1026 1027 // In the case where we have a multiplication as the left operand of 1028 // of a subtraction, we can't combine into a MipsISD::MSub node as the 1029 // the instruction definition of msub(u) places the multiplication on 1030 // on the right. 1031 if (ROOTNode->getOpcode() == ISD::SUB && 1032 ROOTNode->getOperand(0).getOpcode() == ISD::MUL) 1033 return SDValue(); 1034 1035 // We don't handle vector types here. 1036 if (ROOTNode->getValueType(0).isVector()) 1037 return SDValue(); 1038 1039 // For MIPS64, madd / msub instructions are inefficent to use with 64 bit 1040 // arithmetic. E.g. 1041 // (add (mul a b) c) => 1042 // let res = (madd (mthi (drotr c 32))x(mtlo c) a b) in 1043 // MIPS64: (or (dsll (mfhi res) 32) (dsrl (dsll (mflo res) 32) 32) 1044 // or 1045 // MIPS64R2: (dins (mflo res) (mfhi res) 32 32) 1046 // 1047 // The overhead of setting up the Hi/Lo registers and reassembling the 1048 // result makes this a dubious optimzation for MIPS64. The core of the 1049 // problem is that Hi/Lo contain the upper and lower 32 bits of the 1050 // operand and result. 1051 // 1052 // It requires a chain of 4 add/mul for MIPS64R2 to get better code 1053 // density than doing it naively, 5 for MIPS64. Additionally, using 1054 // madd/msub on MIPS64 requires the operands actually be 32 bit sign 1055 // extended operands, not true 64 bit values. 1056 // 1057 // FIXME: For the moment, disable this completely for MIPS64. 1058 if (Subtarget.hasMips64()) 1059 return SDValue(); 1060 1061 SDValue Mult = ROOTNode->getOperand(0).getOpcode() == ISD::MUL 1062 ? ROOTNode->getOperand(0) 1063 : ROOTNode->getOperand(1); 1064 1065 SDValue AddOperand = ROOTNode->getOperand(0).getOpcode() == ISD::MUL 1066 ? ROOTNode->getOperand(1) 1067 : ROOTNode->getOperand(0); 1068 1069 // Transform this to a MADD only if the user of this node is the add. 1070 // If there are other users of the mul, this function returns here. 1071 if (!Mult.hasOneUse()) 1072 return SDValue(); 1073 1074 // maddu and madd are unusual instructions in that on MIPS64 bits 63..31 1075 // must be in canonical form, i.e. sign extended. For MIPS32, the operands 1076 // of the multiply must have 32 or more sign bits, otherwise we cannot 1077 // perform this optimization. We have to check this here as we're performing 1078 // this optimization pre-legalization. 1079 SDValue MultLHS = Mult->getOperand(0); 1080 SDValue MultRHS = Mult->getOperand(1); 1081 1082 bool IsSigned = MultLHS->getOpcode() == ISD::SIGN_EXTEND && 1083 MultRHS->getOpcode() == ISD::SIGN_EXTEND; 1084 bool IsUnsigned = MultLHS->getOpcode() == ISD::ZERO_EXTEND && 1085 MultRHS->getOpcode() == ISD::ZERO_EXTEND; 1086 1087 if (!IsSigned && !IsUnsigned) 1088 return SDValue(); 1089 1090 // Initialize accumulator. 1091 SDLoc DL(ROOTNode); 1092 SDValue BottomHalf, TopHalf; 1093 std::tie(BottomHalf, TopHalf) = 1094 CurDAG.SplitScalar(AddOperand, DL, MVT::i32, MVT::i32); 1095 SDValue ACCIn = 1096 CurDAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped, BottomHalf, TopHalf); 1097 1098 // Create MipsMAdd(u) / MipsMSub(u) node. 1099 bool IsAdd = ROOTNode->getOpcode() == ISD::ADD; 1100 unsigned Opcode = IsAdd ? (IsUnsigned ? MipsISD::MAddu : MipsISD::MAdd) 1101 : (IsUnsigned ? MipsISD::MSubu : MipsISD::MSub); 1102 SDValue MAddOps[3] = { 1103 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(0)), 1104 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(1)), ACCIn}; 1105 SDValue MAdd = CurDAG.getNode(Opcode, DL, MVT::Untyped, MAddOps); 1106 1107 SDValue ResLo = CurDAG.getNode(MipsISD::MFLO, DL, MVT::i32, MAdd); 1108 SDValue ResHi = CurDAG.getNode(MipsISD::MFHI, DL, MVT::i32, MAdd); 1109 SDValue Combined = 1110 CurDAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResLo, ResHi); 1111 return Combined; 1112 } 1113 1114 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG, 1115 TargetLowering::DAGCombinerInfo &DCI, 1116 const MipsSubtarget &Subtarget) { 1117 // (sub v0 (mul v1, v2)) => (msub v1, v2, v0) 1118 if (DCI.isBeforeLegalizeOps()) { 1119 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() && 1120 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64) 1121 return performMADD_MSUBCombine(N, DAG, Subtarget); 1122 1123 return SDValue(); 1124 } 1125 1126 return SDValue(); 1127 } 1128 1129 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 1130 TargetLowering::DAGCombinerInfo &DCI, 1131 const MipsSubtarget &Subtarget) { 1132 // (add v0 (mul v1, v2)) => (madd v1, v2, v0) 1133 if (DCI.isBeforeLegalizeOps()) { 1134 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() && 1135 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64) 1136 return performMADD_MSUBCombine(N, DAG, Subtarget); 1137 1138 return SDValue(); 1139 } 1140 1141 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt)) 1142 SDValue Add = N->getOperand(1); 1143 1144 if (Add.getOpcode() != ISD::ADD) 1145 return SDValue(); 1146 1147 SDValue Lo = Add.getOperand(1); 1148 1149 if ((Lo.getOpcode() != MipsISD::Lo) || 1150 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable)) 1151 return SDValue(); 1152 1153 EVT ValTy = N->getValueType(0); 1154 SDLoc DL(N); 1155 1156 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0), 1157 Add.getOperand(0)); 1158 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo); 1159 } 1160 1161 static SDValue performSHLCombine(SDNode *N, SelectionDAG &DAG, 1162 TargetLowering::DAGCombinerInfo &DCI, 1163 const MipsSubtarget &Subtarget) { 1164 // Pattern match CINS. 1165 // $dst = shl (and $src , imm), pos 1166 // => cins $dst, $src, pos, size 1167 1168 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips()) 1169 return SDValue(); 1170 1171 SDValue FirstOperand = N->getOperand(0); 1172 unsigned FirstOperandOpc = FirstOperand.getOpcode(); 1173 SDValue SecondOperand = N->getOperand(1); 1174 EVT ValTy = N->getValueType(0); 1175 SDLoc DL(N); 1176 1177 uint64_t Pos = 0; 1178 unsigned SMPos, SMSize; 1179 ConstantSDNode *CN; 1180 SDValue NewOperand; 1181 1182 // The second operand of the shift must be an immediate. 1183 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand))) 1184 return SDValue(); 1185 1186 Pos = CN->getZExtValue(); 1187 1188 if (Pos >= ValTy.getSizeInBits()) 1189 return SDValue(); 1190 1191 if (FirstOperandOpc != ISD::AND) 1192 return SDValue(); 1193 1194 // AND's second operand must be a shifted mask. 1195 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) || 1196 !isShiftedMask_64(CN->getZExtValue(), SMPos, SMSize)) 1197 return SDValue(); 1198 1199 // Return if the shifted mask does not start at bit 0 or the sum of its size 1200 // and Pos exceeds the word's size. 1201 if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits()) 1202 return SDValue(); 1203 1204 NewOperand = FirstOperand.getOperand(0); 1205 // SMSize is 'location' (position) in this case, not size. 1206 SMSize--; 1207 1208 return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand, 1209 DAG.getConstant(Pos, DL, MVT::i32), 1210 DAG.getConstant(SMSize, DL, MVT::i32)); 1211 } 1212 1213 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) 1214 const { 1215 SelectionDAG &DAG = DCI.DAG; 1216 unsigned Opc = N->getOpcode(); 1217 1218 switch (Opc) { 1219 default: break; 1220 case ISD::SDIVREM: 1221 case ISD::UDIVREM: 1222 return performDivRemCombine(N, DAG, DCI, Subtarget); 1223 case ISD::SELECT: 1224 return performSELECTCombine(N, DAG, DCI, Subtarget); 1225 case MipsISD::CMovFP_F: 1226 case MipsISD::CMovFP_T: 1227 return performCMovFPCombine(N, DAG, DCI, Subtarget); 1228 case ISD::AND: 1229 return performANDCombine(N, DAG, DCI, Subtarget); 1230 case ISD::OR: 1231 return performORCombine(N, DAG, DCI, Subtarget); 1232 case ISD::ADD: 1233 return performADDCombine(N, DAG, DCI, Subtarget); 1234 case ISD::SHL: 1235 return performSHLCombine(N, DAG, DCI, Subtarget); 1236 case ISD::SUB: 1237 return performSUBCombine(N, DAG, DCI, Subtarget); 1238 } 1239 1240 return SDValue(); 1241 } 1242 1243 bool MipsTargetLowering::isCheapToSpeculateCttz(Type *Ty) const { 1244 return Subtarget.hasMips32(); 1245 } 1246 1247 bool MipsTargetLowering::isCheapToSpeculateCtlz(Type *Ty) const { 1248 return Subtarget.hasMips32(); 1249 } 1250 1251 bool MipsTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1252 // We can use ANDI+SLTIU as a bit test. Y contains the bit position. 1253 // For MIPSR2 or later, we may be able to use the `ext` instruction or its' 1254 // double-word variants. 1255 if (auto *C = dyn_cast<ConstantSDNode>(Y)) 1256 return C->getAPIntValue().ule(15); 1257 1258 return false; 1259 } 1260 1261 bool MipsTargetLowering::shouldFoldConstantShiftPairToMask( 1262 const SDNode *N, CombineLevel Level) const { 1263 assert(((N->getOpcode() == ISD::SHL && 1264 N->getOperand(0).getOpcode() == ISD::SRL) || 1265 (N->getOpcode() == ISD::SRL && 1266 N->getOperand(0).getOpcode() == ISD::SHL)) && 1267 "Expected shift-shift mask"); 1268 1269 if (N->getOperand(0).getValueType().isVector()) 1270 return false; 1271 return true; 1272 } 1273 1274 void 1275 MipsTargetLowering::ReplaceNodeResults(SDNode *N, 1276 SmallVectorImpl<SDValue> &Results, 1277 SelectionDAG &DAG) const { 1278 return LowerOperationWrapper(N, Results, DAG); 1279 } 1280 1281 SDValue MipsTargetLowering:: 1282 LowerOperation(SDValue Op, SelectionDAG &DAG) const 1283 { 1284 switch (Op.getOpcode()) 1285 { 1286 case ISD::BRCOND: return lowerBRCOND(Op, DAG); 1287 case ISD::ConstantPool: return lowerConstantPool(Op, DAG); 1288 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG); 1289 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG); 1290 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG); 1291 case ISD::JumpTable: return lowerJumpTable(Op, DAG); 1292 case ISD::SELECT: return lowerSELECT(Op, DAG); 1293 case ISD::SETCC: return lowerSETCC(Op, DAG); 1294 case ISD::VASTART: return lowerVASTART(Op, DAG); 1295 case ISD::VAARG: return lowerVAARG(Op, DAG); 1296 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG); 1297 case ISD::FABS: return lowerFABS(Op, DAG); 1298 case ISD::FCANONICALIZE: 1299 return lowerFCANONICALIZE(Op, DAG); 1300 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG); 1301 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG); 1302 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG); 1303 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG); 1304 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG); 1305 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true); 1306 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false); 1307 case ISD::LOAD: return lowerLOAD(Op, DAG); 1308 case ISD::STORE: return lowerSTORE(Op, DAG); 1309 case ISD::EH_DWARF_CFA: return lowerEH_DWARF_CFA(Op, DAG); 1310 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG); 1311 } 1312 return SDValue(); 1313 } 1314 1315 //===----------------------------------------------------------------------===// 1316 // Lower helper functions 1317 //===----------------------------------------------------------------------===// 1318 1319 // addLiveIn - This helper function adds the specified physical register to the 1320 // MachineFunction as a live in value. It also creates a corresponding 1321 // virtual register for it. 1322 static unsigned 1323 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC) 1324 { 1325 Register VReg = MF.getRegInfo().createVirtualRegister(RC); 1326 MF.getRegInfo().addLiveIn(PReg, VReg); 1327 return VReg; 1328 } 1329 1330 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr &MI, 1331 MachineBasicBlock &MBB, 1332 const TargetInstrInfo &TII, 1333 bool Is64Bit, bool IsMicroMips) { 1334 if (NoZeroDivCheck) 1335 return &MBB; 1336 1337 // Insert instruction "teq $divisor_reg, $zero, 7". 1338 MachineBasicBlock::iterator I(MI); 1339 MachineInstrBuilder MIB; 1340 MachineOperand &Divisor = MI.getOperand(2); 1341 MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(), 1342 TII.get(IsMicroMips ? Mips::TEQ_MM : Mips::TEQ)) 1343 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill())) 1344 .addReg(Mips::ZERO) 1345 .addImm(7); 1346 1347 // Use the 32-bit sub-register if this is a 64-bit division. 1348 if (Is64Bit) 1349 MIB->getOperand(0).setSubReg(Mips::sub_32); 1350 1351 // Clear Divisor's kill flag. 1352 Divisor.setIsKill(false); 1353 1354 // We would normally delete the original instruction here but in this case 1355 // we only needed to inject an additional instruction rather than replace it. 1356 1357 return &MBB; 1358 } 1359 1360 MachineBasicBlock * 1361 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 1362 MachineBasicBlock *BB) const { 1363 switch (MI.getOpcode()) { 1364 default: 1365 llvm_unreachable("Unexpected instr type to insert"); 1366 case Mips::ATOMIC_LOAD_ADD_I8: 1367 return emitAtomicBinaryPartword(MI, BB, 1); 1368 case Mips::ATOMIC_LOAD_ADD_I16: 1369 return emitAtomicBinaryPartword(MI, BB, 2); 1370 case Mips::ATOMIC_LOAD_ADD_I32: 1371 return emitAtomicBinary(MI, BB); 1372 case Mips::ATOMIC_LOAD_ADD_I64: 1373 return emitAtomicBinary(MI, BB); 1374 1375 case Mips::ATOMIC_LOAD_AND_I8: 1376 return emitAtomicBinaryPartword(MI, BB, 1); 1377 case Mips::ATOMIC_LOAD_AND_I16: 1378 return emitAtomicBinaryPartword(MI, BB, 2); 1379 case Mips::ATOMIC_LOAD_AND_I32: 1380 return emitAtomicBinary(MI, BB); 1381 case Mips::ATOMIC_LOAD_AND_I64: 1382 return emitAtomicBinary(MI, BB); 1383 1384 case Mips::ATOMIC_LOAD_OR_I8: 1385 return emitAtomicBinaryPartword(MI, BB, 1); 1386 case Mips::ATOMIC_LOAD_OR_I16: 1387 return emitAtomicBinaryPartword(MI, BB, 2); 1388 case Mips::ATOMIC_LOAD_OR_I32: 1389 return emitAtomicBinary(MI, BB); 1390 case Mips::ATOMIC_LOAD_OR_I64: 1391 return emitAtomicBinary(MI, BB); 1392 1393 case Mips::ATOMIC_LOAD_XOR_I8: 1394 return emitAtomicBinaryPartword(MI, BB, 1); 1395 case Mips::ATOMIC_LOAD_XOR_I16: 1396 return emitAtomicBinaryPartword(MI, BB, 2); 1397 case Mips::ATOMIC_LOAD_XOR_I32: 1398 return emitAtomicBinary(MI, BB); 1399 case Mips::ATOMIC_LOAD_XOR_I64: 1400 return emitAtomicBinary(MI, BB); 1401 1402 case Mips::ATOMIC_LOAD_NAND_I8: 1403 return emitAtomicBinaryPartword(MI, BB, 1); 1404 case Mips::ATOMIC_LOAD_NAND_I16: 1405 return emitAtomicBinaryPartword(MI, BB, 2); 1406 case Mips::ATOMIC_LOAD_NAND_I32: 1407 return emitAtomicBinary(MI, BB); 1408 case Mips::ATOMIC_LOAD_NAND_I64: 1409 return emitAtomicBinary(MI, BB); 1410 1411 case Mips::ATOMIC_LOAD_SUB_I8: 1412 return emitAtomicBinaryPartword(MI, BB, 1); 1413 case Mips::ATOMIC_LOAD_SUB_I16: 1414 return emitAtomicBinaryPartword(MI, BB, 2); 1415 case Mips::ATOMIC_LOAD_SUB_I32: 1416 return emitAtomicBinary(MI, BB); 1417 case Mips::ATOMIC_LOAD_SUB_I64: 1418 return emitAtomicBinary(MI, BB); 1419 1420 case Mips::ATOMIC_SWAP_I8: 1421 return emitAtomicBinaryPartword(MI, BB, 1); 1422 case Mips::ATOMIC_SWAP_I16: 1423 return emitAtomicBinaryPartword(MI, BB, 2); 1424 case Mips::ATOMIC_SWAP_I32: 1425 return emitAtomicBinary(MI, BB); 1426 case Mips::ATOMIC_SWAP_I64: 1427 return emitAtomicBinary(MI, BB); 1428 1429 case Mips::ATOMIC_CMP_SWAP_I8: 1430 return emitAtomicCmpSwapPartword(MI, BB, 1); 1431 case Mips::ATOMIC_CMP_SWAP_I16: 1432 return emitAtomicCmpSwapPartword(MI, BB, 2); 1433 case Mips::ATOMIC_CMP_SWAP_I32: 1434 return emitAtomicCmpSwap(MI, BB); 1435 case Mips::ATOMIC_CMP_SWAP_I64: 1436 return emitAtomicCmpSwap(MI, BB); 1437 1438 case Mips::ATOMIC_LOAD_MIN_I8: 1439 return emitAtomicBinaryPartword(MI, BB, 1); 1440 case Mips::ATOMIC_LOAD_MIN_I16: 1441 return emitAtomicBinaryPartword(MI, BB, 2); 1442 case Mips::ATOMIC_LOAD_MIN_I32: 1443 return emitAtomicBinary(MI, BB); 1444 case Mips::ATOMIC_LOAD_MIN_I64: 1445 return emitAtomicBinary(MI, BB); 1446 1447 case Mips::ATOMIC_LOAD_MAX_I8: 1448 return emitAtomicBinaryPartword(MI, BB, 1); 1449 case Mips::ATOMIC_LOAD_MAX_I16: 1450 return emitAtomicBinaryPartword(MI, BB, 2); 1451 case Mips::ATOMIC_LOAD_MAX_I32: 1452 return emitAtomicBinary(MI, BB); 1453 case Mips::ATOMIC_LOAD_MAX_I64: 1454 return emitAtomicBinary(MI, BB); 1455 1456 case Mips::ATOMIC_LOAD_UMIN_I8: 1457 return emitAtomicBinaryPartword(MI, BB, 1); 1458 case Mips::ATOMIC_LOAD_UMIN_I16: 1459 return emitAtomicBinaryPartword(MI, BB, 2); 1460 case Mips::ATOMIC_LOAD_UMIN_I32: 1461 return emitAtomicBinary(MI, BB); 1462 case Mips::ATOMIC_LOAD_UMIN_I64: 1463 return emitAtomicBinary(MI, BB); 1464 1465 case Mips::ATOMIC_LOAD_UMAX_I8: 1466 return emitAtomicBinaryPartword(MI, BB, 1); 1467 case Mips::ATOMIC_LOAD_UMAX_I16: 1468 return emitAtomicBinaryPartword(MI, BB, 2); 1469 case Mips::ATOMIC_LOAD_UMAX_I32: 1470 return emitAtomicBinary(MI, BB); 1471 case Mips::ATOMIC_LOAD_UMAX_I64: 1472 return emitAtomicBinary(MI, BB); 1473 1474 case Mips::PseudoSDIV: 1475 case Mips::PseudoUDIV: 1476 case Mips::DIV: 1477 case Mips::DIVU: 1478 case Mips::MOD: 1479 case Mips::MODU: 1480 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, 1481 false); 1482 case Mips::SDIV_MM_Pseudo: 1483 case Mips::UDIV_MM_Pseudo: 1484 case Mips::SDIV_MM: 1485 case Mips::UDIV_MM: 1486 case Mips::DIV_MMR6: 1487 case Mips::DIVU_MMR6: 1488 case Mips::MOD_MMR6: 1489 case Mips::MODU_MMR6: 1490 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, true); 1491 case Mips::PseudoDSDIV: 1492 case Mips::PseudoDUDIV: 1493 case Mips::DDIV: 1494 case Mips::DDIVU: 1495 case Mips::DMOD: 1496 case Mips::DMODU: 1497 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, false); 1498 1499 case Mips::PseudoSELECT_I: 1500 case Mips::PseudoSELECT_I64: 1501 case Mips::PseudoSELECT_S: 1502 case Mips::PseudoSELECT_D32: 1503 case Mips::PseudoSELECT_D64: 1504 return emitPseudoSELECT(MI, BB, false, Mips::BNE); 1505 case Mips::PseudoSELECTFP_F_I: 1506 case Mips::PseudoSELECTFP_F_I64: 1507 case Mips::PseudoSELECTFP_F_S: 1508 case Mips::PseudoSELECTFP_F_D32: 1509 case Mips::PseudoSELECTFP_F_D64: 1510 return emitPseudoSELECT(MI, BB, true, Mips::BC1F); 1511 case Mips::PseudoSELECTFP_T_I: 1512 case Mips::PseudoSELECTFP_T_I64: 1513 case Mips::PseudoSELECTFP_T_S: 1514 case Mips::PseudoSELECTFP_T_D32: 1515 case Mips::PseudoSELECTFP_T_D64: 1516 return emitPseudoSELECT(MI, BB, true, Mips::BC1T); 1517 case Mips::PseudoD_SELECT_I: 1518 case Mips::PseudoD_SELECT_I64: 1519 return emitPseudoD_SELECT(MI, BB); 1520 case Mips::LDR_W: 1521 return emitLDR_W(MI, BB); 1522 case Mips::LDR_D: 1523 return emitLDR_D(MI, BB); 1524 case Mips::STR_W: 1525 return emitSTR_W(MI, BB); 1526 case Mips::STR_D: 1527 return emitSTR_D(MI, BB); 1528 } 1529 } 1530 1531 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and 1532 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true) 1533 MachineBasicBlock * 1534 MipsTargetLowering::emitAtomicBinary(MachineInstr &MI, 1535 MachineBasicBlock *BB) const { 1536 1537 MachineFunction *MF = BB->getParent(); 1538 MachineRegisterInfo &RegInfo = MF->getRegInfo(); 1539 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 1540 DebugLoc DL = MI.getDebugLoc(); 1541 1542 unsigned AtomicOp; 1543 bool NeedsAdditionalReg = false; 1544 switch (MI.getOpcode()) { 1545 case Mips::ATOMIC_LOAD_ADD_I32: 1546 AtomicOp = Mips::ATOMIC_LOAD_ADD_I32_POSTRA; 1547 break; 1548 case Mips::ATOMIC_LOAD_SUB_I32: 1549 AtomicOp = Mips::ATOMIC_LOAD_SUB_I32_POSTRA; 1550 break; 1551 case Mips::ATOMIC_LOAD_AND_I32: 1552 AtomicOp = Mips::ATOMIC_LOAD_AND_I32_POSTRA; 1553 break; 1554 case Mips::ATOMIC_LOAD_OR_I32: 1555 AtomicOp = Mips::ATOMIC_LOAD_OR_I32_POSTRA; 1556 break; 1557 case Mips::ATOMIC_LOAD_XOR_I32: 1558 AtomicOp = Mips::ATOMIC_LOAD_XOR_I32_POSTRA; 1559 break; 1560 case Mips::ATOMIC_LOAD_NAND_I32: 1561 AtomicOp = Mips::ATOMIC_LOAD_NAND_I32_POSTRA; 1562 break; 1563 case Mips::ATOMIC_SWAP_I32: 1564 AtomicOp = Mips::ATOMIC_SWAP_I32_POSTRA; 1565 break; 1566 case Mips::ATOMIC_LOAD_ADD_I64: 1567 AtomicOp = Mips::ATOMIC_LOAD_ADD_I64_POSTRA; 1568 break; 1569 case Mips::ATOMIC_LOAD_SUB_I64: 1570 AtomicOp = Mips::ATOMIC_LOAD_SUB_I64_POSTRA; 1571 break; 1572 case Mips::ATOMIC_LOAD_AND_I64: 1573 AtomicOp = Mips::ATOMIC_LOAD_AND_I64_POSTRA; 1574 break; 1575 case Mips::ATOMIC_LOAD_OR_I64: 1576 AtomicOp = Mips::ATOMIC_LOAD_OR_I64_POSTRA; 1577 break; 1578 case Mips::ATOMIC_LOAD_XOR_I64: 1579 AtomicOp = Mips::ATOMIC_LOAD_XOR_I64_POSTRA; 1580 break; 1581 case Mips::ATOMIC_LOAD_NAND_I64: 1582 AtomicOp = Mips::ATOMIC_LOAD_NAND_I64_POSTRA; 1583 break; 1584 case Mips::ATOMIC_SWAP_I64: 1585 AtomicOp = Mips::ATOMIC_SWAP_I64_POSTRA; 1586 break; 1587 case Mips::ATOMIC_LOAD_MIN_I32: 1588 AtomicOp = Mips::ATOMIC_LOAD_MIN_I32_POSTRA; 1589 NeedsAdditionalReg = true; 1590 break; 1591 case Mips::ATOMIC_LOAD_MAX_I32: 1592 AtomicOp = Mips::ATOMIC_LOAD_MAX_I32_POSTRA; 1593 NeedsAdditionalReg = true; 1594 break; 1595 case Mips::ATOMIC_LOAD_UMIN_I32: 1596 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I32_POSTRA; 1597 NeedsAdditionalReg = true; 1598 break; 1599 case Mips::ATOMIC_LOAD_UMAX_I32: 1600 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I32_POSTRA; 1601 NeedsAdditionalReg = true; 1602 break; 1603 case Mips::ATOMIC_LOAD_MIN_I64: 1604 AtomicOp = Mips::ATOMIC_LOAD_MIN_I64_POSTRA; 1605 NeedsAdditionalReg = true; 1606 break; 1607 case Mips::ATOMIC_LOAD_MAX_I64: 1608 AtomicOp = Mips::ATOMIC_LOAD_MAX_I64_POSTRA; 1609 NeedsAdditionalReg = true; 1610 break; 1611 case Mips::ATOMIC_LOAD_UMIN_I64: 1612 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I64_POSTRA; 1613 NeedsAdditionalReg = true; 1614 break; 1615 case Mips::ATOMIC_LOAD_UMAX_I64: 1616 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I64_POSTRA; 1617 NeedsAdditionalReg = true; 1618 break; 1619 default: 1620 llvm_unreachable("Unknown pseudo atomic for replacement!"); 1621 } 1622 1623 Register OldVal = MI.getOperand(0).getReg(); 1624 Register Ptr = MI.getOperand(1).getReg(); 1625 Register Incr = MI.getOperand(2).getReg(); 1626 Register Scratch = RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal)); 1627 1628 MachineBasicBlock::iterator II(MI); 1629 1630 // The scratch registers here with the EarlyClobber | Define | Implicit 1631 // flags is used to persuade the register allocator and the machine 1632 // verifier to accept the usage of this register. This has to be a real 1633 // register which has an UNDEF value but is dead after the instruction which 1634 // is unique among the registers chosen for the instruction. 1635 1636 // The EarlyClobber flag has the semantic properties that the operand it is 1637 // attached to is clobbered before the rest of the inputs are read. Hence it 1638 // must be unique among the operands to the instruction. 1639 // The Define flag is needed to coerce the machine verifier that an Undef 1640 // value isn't a problem. 1641 // The Dead flag is needed as the value in scratch isn't used by any other 1642 // instruction. Kill isn't used as Dead is more precise. 1643 // The implicit flag is here due to the interaction between the other flags 1644 // and the machine verifier. 1645 1646 // For correctness purpose, a new pseudo is introduced here. We need this 1647 // new pseudo, so that FastRegisterAllocator does not see an ll/sc sequence 1648 // that is spread over >1 basic blocks. A register allocator which 1649 // introduces (or any codegen infact) a store, can violate the expectations 1650 // of the hardware. 1651 // 1652 // An atomic read-modify-write sequence starts with a linked load 1653 // instruction and ends with a store conditional instruction. The atomic 1654 // read-modify-write sequence fails if any of the following conditions 1655 // occur between the execution of ll and sc: 1656 // * A coherent store is completed by another process or coherent I/O 1657 // module into the block of synchronizable physical memory containing 1658 // the word. The size and alignment of the block is 1659 // implementation-dependent. 1660 // * A coherent store is executed between an LL and SC sequence on the 1661 // same processor to the block of synchornizable physical memory 1662 // containing the word. 1663 // 1664 1665 Register PtrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Ptr)); 1666 Register IncrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Incr)); 1667 1668 BuildMI(*BB, II, DL, TII->get(Mips::COPY), IncrCopy).addReg(Incr); 1669 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr); 1670 1671 MachineInstrBuilder MIB = 1672 BuildMI(*BB, II, DL, TII->get(AtomicOp)) 1673 .addReg(OldVal, RegState::Define | RegState::EarlyClobber) 1674 .addReg(PtrCopy) 1675 .addReg(IncrCopy) 1676 .addReg(Scratch, RegState::Define | RegState::EarlyClobber | 1677 RegState::Implicit | RegState::Dead); 1678 if (NeedsAdditionalReg) { 1679 Register Scratch2 = 1680 RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal)); 1681 MIB.addReg(Scratch2, RegState::Define | RegState::EarlyClobber | 1682 RegState::Implicit | RegState::Dead); 1683 } 1684 1685 MI.eraseFromParent(); 1686 1687 return BB; 1688 } 1689 1690 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg( 1691 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg, 1692 unsigned SrcReg) const { 1693 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 1694 const DebugLoc &DL = MI.getDebugLoc(); 1695 1696 if (Subtarget.hasMips32r2() && Size == 1) { 1697 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg); 1698 return BB; 1699 } 1700 1701 if (Subtarget.hasMips32r2() && Size == 2) { 1702 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg); 1703 return BB; 1704 } 1705 1706 MachineFunction *MF = BB->getParent(); 1707 MachineRegisterInfo &RegInfo = MF->getRegInfo(); 1708 const TargetRegisterClass *RC = getRegClassFor(MVT::i32); 1709 Register ScrReg = RegInfo.createVirtualRegister(RC); 1710 1711 assert(Size < 32); 1712 int64_t ShiftImm = 32 - (Size * 8); 1713 1714 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm); 1715 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm); 1716 1717 return BB; 1718 } 1719 1720 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword( 1721 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const { 1722 assert((Size == 1 || Size == 2) && 1723 "Unsupported size for EmitAtomicBinaryPartial."); 1724 1725 MachineFunction *MF = BB->getParent(); 1726 MachineRegisterInfo &RegInfo = MF->getRegInfo(); 1727 const TargetRegisterClass *RC = getRegClassFor(MVT::i32); 1728 const bool ArePtrs64bit = ABI.ArePtrs64bit(); 1729 const TargetRegisterClass *RCp = 1730 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32); 1731 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 1732 DebugLoc DL = MI.getDebugLoc(); 1733 1734 Register Dest = MI.getOperand(0).getReg(); 1735 Register Ptr = MI.getOperand(1).getReg(); 1736 Register Incr = MI.getOperand(2).getReg(); 1737 1738 Register AlignedAddr = RegInfo.createVirtualRegister(RCp); 1739 Register ShiftAmt = RegInfo.createVirtualRegister(RC); 1740 Register Mask = RegInfo.createVirtualRegister(RC); 1741 Register Mask2 = RegInfo.createVirtualRegister(RC); 1742 Register Incr2 = RegInfo.createVirtualRegister(RC); 1743 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp); 1744 Register PtrLSB2 = RegInfo.createVirtualRegister(RC); 1745 Register MaskUpper = RegInfo.createVirtualRegister(RC); 1746 Register Scratch = RegInfo.createVirtualRegister(RC); 1747 Register Scratch2 = RegInfo.createVirtualRegister(RC); 1748 Register Scratch3 = RegInfo.createVirtualRegister(RC); 1749 1750 unsigned AtomicOp = 0; 1751 bool NeedsAdditionalReg = false; 1752 switch (MI.getOpcode()) { 1753 case Mips::ATOMIC_LOAD_NAND_I8: 1754 AtomicOp = Mips::ATOMIC_LOAD_NAND_I8_POSTRA; 1755 break; 1756 case Mips::ATOMIC_LOAD_NAND_I16: 1757 AtomicOp = Mips::ATOMIC_LOAD_NAND_I16_POSTRA; 1758 break; 1759 case Mips::ATOMIC_SWAP_I8: 1760 AtomicOp = Mips::ATOMIC_SWAP_I8_POSTRA; 1761 break; 1762 case Mips::ATOMIC_SWAP_I16: 1763 AtomicOp = Mips::ATOMIC_SWAP_I16_POSTRA; 1764 break; 1765 case Mips::ATOMIC_LOAD_ADD_I8: 1766 AtomicOp = Mips::ATOMIC_LOAD_ADD_I8_POSTRA; 1767 break; 1768 case Mips::ATOMIC_LOAD_ADD_I16: 1769 AtomicOp = Mips::ATOMIC_LOAD_ADD_I16_POSTRA; 1770 break; 1771 case Mips::ATOMIC_LOAD_SUB_I8: 1772 AtomicOp = Mips::ATOMIC_LOAD_SUB_I8_POSTRA; 1773 break; 1774 case Mips::ATOMIC_LOAD_SUB_I16: 1775 AtomicOp = Mips::ATOMIC_LOAD_SUB_I16_POSTRA; 1776 break; 1777 case Mips::ATOMIC_LOAD_AND_I8: 1778 AtomicOp = Mips::ATOMIC_LOAD_AND_I8_POSTRA; 1779 break; 1780 case Mips::ATOMIC_LOAD_AND_I16: 1781 AtomicOp = Mips::ATOMIC_LOAD_AND_I16_POSTRA; 1782 break; 1783 case Mips::ATOMIC_LOAD_OR_I8: 1784 AtomicOp = Mips::ATOMIC_LOAD_OR_I8_POSTRA; 1785 break; 1786 case Mips::ATOMIC_LOAD_OR_I16: 1787 AtomicOp = Mips::ATOMIC_LOAD_OR_I16_POSTRA; 1788 break; 1789 case Mips::ATOMIC_LOAD_XOR_I8: 1790 AtomicOp = Mips::ATOMIC_LOAD_XOR_I8_POSTRA; 1791 break; 1792 case Mips::ATOMIC_LOAD_XOR_I16: 1793 AtomicOp = Mips::ATOMIC_LOAD_XOR_I16_POSTRA; 1794 break; 1795 case Mips::ATOMIC_LOAD_MIN_I8: 1796 AtomicOp = Mips::ATOMIC_LOAD_MIN_I8_POSTRA; 1797 NeedsAdditionalReg = true; 1798 break; 1799 case Mips::ATOMIC_LOAD_MIN_I16: 1800 AtomicOp = Mips::ATOMIC_LOAD_MIN_I16_POSTRA; 1801 NeedsAdditionalReg = true; 1802 break; 1803 case Mips::ATOMIC_LOAD_MAX_I8: 1804 AtomicOp = Mips::ATOMIC_LOAD_MAX_I8_POSTRA; 1805 NeedsAdditionalReg = true; 1806 break; 1807 case Mips::ATOMIC_LOAD_MAX_I16: 1808 AtomicOp = Mips::ATOMIC_LOAD_MAX_I16_POSTRA; 1809 NeedsAdditionalReg = true; 1810 break; 1811 case Mips::ATOMIC_LOAD_UMIN_I8: 1812 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I8_POSTRA; 1813 NeedsAdditionalReg = true; 1814 break; 1815 case Mips::ATOMIC_LOAD_UMIN_I16: 1816 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I16_POSTRA; 1817 NeedsAdditionalReg = true; 1818 break; 1819 case Mips::ATOMIC_LOAD_UMAX_I8: 1820 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I8_POSTRA; 1821 NeedsAdditionalReg = true; 1822 break; 1823 case Mips::ATOMIC_LOAD_UMAX_I16: 1824 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I16_POSTRA; 1825 NeedsAdditionalReg = true; 1826 break; 1827 default: 1828 llvm_unreachable("Unknown subword atomic pseudo for expansion!"); 1829 } 1830 1831 // insert new blocks after the current block 1832 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 1833 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 1834 MachineFunction::iterator It = ++BB->getIterator(); 1835 MF->insert(It, exitMBB); 1836 1837 // Transfer the remainder of BB and its successor edges to exitMBB. 1838 exitMBB->splice(exitMBB->begin(), BB, 1839 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 1840 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 1841 1842 BB->addSuccessor(exitMBB, BranchProbability::getOne()); 1843 1844 // thisMBB: 1845 // addiu masklsb2,$0,-4 # 0xfffffffc 1846 // and alignedaddr,ptr,masklsb2 1847 // andi ptrlsb2,ptr,3 1848 // sll shiftamt,ptrlsb2,3 1849 // ori maskupper,$0,255 # 0xff 1850 // sll mask,maskupper,shiftamt 1851 // nor mask2,$0,mask 1852 // sll incr2,incr,shiftamt 1853 1854 int64_t MaskImm = (Size == 1) ? 255 : 65535; 1855 BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2) 1856 .addReg(ABI.GetNullPtr()).addImm(-4); 1857 BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr) 1858 .addReg(Ptr).addReg(MaskLSB2); 1859 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2) 1860 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3); 1861 if (Subtarget.isLittle()) { 1862 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3); 1863 } else { 1864 Register Off = RegInfo.createVirtualRegister(RC); 1865 BuildMI(BB, DL, TII->get(Mips::XORi), Off) 1866 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2); 1867 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3); 1868 } 1869 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper) 1870 .addReg(Mips::ZERO).addImm(MaskImm); 1871 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask) 1872 .addReg(MaskUpper).addReg(ShiftAmt); 1873 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask); 1874 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt); 1875 1876 1877 // The purposes of the flags on the scratch registers is explained in 1878 // emitAtomicBinary. In summary, we need a scratch register which is going to 1879 // be undef, that is unique among registers chosen for the instruction. 1880 1881 MachineInstrBuilder MIB = 1882 BuildMI(BB, DL, TII->get(AtomicOp)) 1883 .addReg(Dest, RegState::Define | RegState::EarlyClobber) 1884 .addReg(AlignedAddr) 1885 .addReg(Incr2) 1886 .addReg(Mask) 1887 .addReg(Mask2) 1888 .addReg(ShiftAmt) 1889 .addReg(Scratch, RegState::EarlyClobber | RegState::Define | 1890 RegState::Dead | RegState::Implicit) 1891 .addReg(Scratch2, RegState::EarlyClobber | RegState::Define | 1892 RegState::Dead | RegState::Implicit) 1893 .addReg(Scratch3, RegState::EarlyClobber | RegState::Define | 1894 RegState::Dead | RegState::Implicit); 1895 if (NeedsAdditionalReg) { 1896 Register Scratch4 = RegInfo.createVirtualRegister(RC); 1897 MIB.addReg(Scratch4, RegState::EarlyClobber | RegState::Define | 1898 RegState::Dead | RegState::Implicit); 1899 } 1900 1901 MI.eraseFromParent(); // The instruction is gone now. 1902 1903 return exitMBB; 1904 } 1905 1906 // Lower atomic compare and swap to a pseudo instruction, taking care to 1907 // define a scratch register for the pseudo instruction's expansion. The 1908 // instruction is expanded after the register allocator as to prevent 1909 // the insertion of stores between the linked load and the store conditional. 1910 1911 MachineBasicBlock * 1912 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI, 1913 MachineBasicBlock *BB) const { 1914 1915 assert((MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 || 1916 MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) && 1917 "Unsupported atomic pseudo for EmitAtomicCmpSwap."); 1918 1919 const unsigned Size = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ? 4 : 8; 1920 1921 MachineFunction *MF = BB->getParent(); 1922 MachineRegisterInfo &MRI = MF->getRegInfo(); 1923 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8)); 1924 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 1925 DebugLoc DL = MI.getDebugLoc(); 1926 1927 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 1928 ? Mips::ATOMIC_CMP_SWAP_I32_POSTRA 1929 : Mips::ATOMIC_CMP_SWAP_I64_POSTRA; 1930 Register Dest = MI.getOperand(0).getReg(); 1931 Register Ptr = MI.getOperand(1).getReg(); 1932 Register OldVal = MI.getOperand(2).getReg(); 1933 Register NewVal = MI.getOperand(3).getReg(); 1934 1935 Register Scratch = MRI.createVirtualRegister(RC); 1936 MachineBasicBlock::iterator II(MI); 1937 1938 // We need to create copies of the various registers and kill them at the 1939 // atomic pseudo. If the copies are not made, when the atomic is expanded 1940 // after fast register allocation, the spills will end up outside of the 1941 // blocks that their values are defined in, causing livein errors. 1942 1943 Register PtrCopy = MRI.createVirtualRegister(MRI.getRegClass(Ptr)); 1944 Register OldValCopy = MRI.createVirtualRegister(MRI.getRegClass(OldVal)); 1945 Register NewValCopy = MRI.createVirtualRegister(MRI.getRegClass(NewVal)); 1946 1947 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr); 1948 BuildMI(*BB, II, DL, TII->get(Mips::COPY), OldValCopy).addReg(OldVal); 1949 BuildMI(*BB, II, DL, TII->get(Mips::COPY), NewValCopy).addReg(NewVal); 1950 1951 // The purposes of the flags on the scratch registers is explained in 1952 // emitAtomicBinary. In summary, we need a scratch register which is going to 1953 // be undef, that is unique among registers chosen for the instruction. 1954 1955 BuildMI(*BB, II, DL, TII->get(AtomicOp)) 1956 .addReg(Dest, RegState::Define | RegState::EarlyClobber) 1957 .addReg(PtrCopy, RegState::Kill) 1958 .addReg(OldValCopy, RegState::Kill) 1959 .addReg(NewValCopy, RegState::Kill) 1960 .addReg(Scratch, RegState::EarlyClobber | RegState::Define | 1961 RegState::Dead | RegState::Implicit); 1962 1963 MI.eraseFromParent(); // The instruction is gone now. 1964 1965 return BB; 1966 } 1967 1968 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword( 1969 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const { 1970 assert((Size == 1 || Size == 2) && 1971 "Unsupported size for EmitAtomicCmpSwapPartial."); 1972 1973 MachineFunction *MF = BB->getParent(); 1974 MachineRegisterInfo &RegInfo = MF->getRegInfo(); 1975 const TargetRegisterClass *RC = getRegClassFor(MVT::i32); 1976 const bool ArePtrs64bit = ABI.ArePtrs64bit(); 1977 const TargetRegisterClass *RCp = 1978 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32); 1979 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 1980 DebugLoc DL = MI.getDebugLoc(); 1981 1982 Register Dest = MI.getOperand(0).getReg(); 1983 Register Ptr = MI.getOperand(1).getReg(); 1984 Register CmpVal = MI.getOperand(2).getReg(); 1985 Register NewVal = MI.getOperand(3).getReg(); 1986 1987 Register AlignedAddr = RegInfo.createVirtualRegister(RCp); 1988 Register ShiftAmt = RegInfo.createVirtualRegister(RC); 1989 Register Mask = RegInfo.createVirtualRegister(RC); 1990 Register Mask2 = RegInfo.createVirtualRegister(RC); 1991 Register ShiftedCmpVal = RegInfo.createVirtualRegister(RC); 1992 Register ShiftedNewVal = RegInfo.createVirtualRegister(RC); 1993 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp); 1994 Register PtrLSB2 = RegInfo.createVirtualRegister(RC); 1995 Register MaskUpper = RegInfo.createVirtualRegister(RC); 1996 Register MaskedCmpVal = RegInfo.createVirtualRegister(RC); 1997 Register MaskedNewVal = RegInfo.createVirtualRegister(RC); 1998 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I8 1999 ? Mips::ATOMIC_CMP_SWAP_I8_POSTRA 2000 : Mips::ATOMIC_CMP_SWAP_I16_POSTRA; 2001 2002 // The scratch registers here with the EarlyClobber | Define | Dead | Implicit 2003 // flags are used to coerce the register allocator and the machine verifier to 2004 // accept the usage of these registers. 2005 // The EarlyClobber flag has the semantic properties that the operand it is 2006 // attached to is clobbered before the rest of the inputs are read. Hence it 2007 // must be unique among the operands to the instruction. 2008 // The Define flag is needed to coerce the machine verifier that an Undef 2009 // value isn't a problem. 2010 // The Dead flag is needed as the value in scratch isn't used by any other 2011 // instruction. Kill isn't used as Dead is more precise. 2012 Register Scratch = RegInfo.createVirtualRegister(RC); 2013 Register Scratch2 = RegInfo.createVirtualRegister(RC); 2014 2015 // insert new blocks after the current block 2016 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 2017 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 2018 MachineFunction::iterator It = ++BB->getIterator(); 2019 MF->insert(It, exitMBB); 2020 2021 // Transfer the remainder of BB and its successor edges to exitMBB. 2022 exitMBB->splice(exitMBB->begin(), BB, 2023 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 2024 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 2025 2026 BB->addSuccessor(exitMBB, BranchProbability::getOne()); 2027 2028 // thisMBB: 2029 // addiu masklsb2,$0,-4 # 0xfffffffc 2030 // and alignedaddr,ptr,masklsb2 2031 // andi ptrlsb2,ptr,3 2032 // xori ptrlsb2,ptrlsb2,3 # Only for BE 2033 // sll shiftamt,ptrlsb2,3 2034 // ori maskupper,$0,255 # 0xff 2035 // sll mask,maskupper,shiftamt 2036 // nor mask2,$0,mask 2037 // andi maskedcmpval,cmpval,255 2038 // sll shiftedcmpval,maskedcmpval,shiftamt 2039 // andi maskednewval,newval,255 2040 // sll shiftednewval,maskednewval,shiftamt 2041 int64_t MaskImm = (Size == 1) ? 255 : 65535; 2042 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2) 2043 .addReg(ABI.GetNullPtr()).addImm(-4); 2044 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr) 2045 .addReg(Ptr).addReg(MaskLSB2); 2046 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2) 2047 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3); 2048 if (Subtarget.isLittle()) { 2049 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3); 2050 } else { 2051 Register Off = RegInfo.createVirtualRegister(RC); 2052 BuildMI(BB, DL, TII->get(Mips::XORi), Off) 2053 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2); 2054 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3); 2055 } 2056 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper) 2057 .addReg(Mips::ZERO).addImm(MaskImm); 2058 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask) 2059 .addReg(MaskUpper).addReg(ShiftAmt); 2060 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask); 2061 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal) 2062 .addReg(CmpVal).addImm(MaskImm); 2063 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal) 2064 .addReg(MaskedCmpVal).addReg(ShiftAmt); 2065 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal) 2066 .addReg(NewVal).addImm(MaskImm); 2067 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal) 2068 .addReg(MaskedNewVal).addReg(ShiftAmt); 2069 2070 // The purposes of the flags on the scratch registers are explained in 2071 // emitAtomicBinary. In summary, we need a scratch register which is going to 2072 // be undef, that is unique among the register chosen for the instruction. 2073 2074 BuildMI(BB, DL, TII->get(AtomicOp)) 2075 .addReg(Dest, RegState::Define | RegState::EarlyClobber) 2076 .addReg(AlignedAddr) 2077 .addReg(Mask) 2078 .addReg(ShiftedCmpVal) 2079 .addReg(Mask2) 2080 .addReg(ShiftedNewVal) 2081 .addReg(ShiftAmt) 2082 .addReg(Scratch, RegState::EarlyClobber | RegState::Define | 2083 RegState::Dead | RegState::Implicit) 2084 .addReg(Scratch2, RegState::EarlyClobber | RegState::Define | 2085 RegState::Dead | RegState::Implicit); 2086 2087 MI.eraseFromParent(); // The instruction is gone now. 2088 2089 return exitMBB; 2090 } 2091 2092 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 2093 // The first operand is the chain, the second is the condition, the third is 2094 // the block to branch to if the condition is true. 2095 SDValue Chain = Op.getOperand(0); 2096 SDValue Dest = Op.getOperand(2); 2097 SDLoc DL(Op); 2098 2099 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6()); 2100 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1)); 2101 2102 // Return if flag is not set by a floating point comparison. 2103 if (CondRes.getOpcode() != MipsISD::FPCmp) 2104 return Op; 2105 2106 SDValue CCNode = CondRes.getOperand(2); 2107 Mips::CondCode CC = (Mips::CondCode)CCNode->getAsZExtVal(); 2108 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T; 2109 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32); 2110 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32); 2111 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode, 2112 FCC0, Dest, CondRes); 2113 } 2114 2115 SDValue MipsTargetLowering:: 2116 lowerSELECT(SDValue Op, SelectionDAG &DAG) const 2117 { 2118 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6()); 2119 SDValue Cond = createFPCmp(DAG, Op.getOperand(0)); 2120 2121 // Return if flag is not set by a floating point comparison. 2122 if (Cond.getOpcode() != MipsISD::FPCmp) 2123 return Op; 2124 2125 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2), 2126 SDLoc(Op)); 2127 } 2128 2129 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2130 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6()); 2131 SDValue Cond = createFPCmp(DAG, Op); 2132 2133 assert(Cond.getOpcode() == MipsISD::FPCmp && 2134 "Floating point operand expected."); 2135 2136 SDLoc DL(Op); 2137 SDValue True = DAG.getConstant(1, DL, MVT::i32); 2138 SDValue False = DAG.getConstant(0, DL, MVT::i32); 2139 2140 return createCMovFP(DAG, Cond, True, False, DL); 2141 } 2142 2143 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op, 2144 SelectionDAG &DAG) const { 2145 EVT Ty = Op.getValueType(); 2146 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 2147 const GlobalValue *GV = N->getGlobal(); 2148 2149 if (GV->hasDLLImportStorageClass()) { 2150 assert(Subtarget.isTargetWindows() && 2151 "Windows is the only supported COFF target"); 2152 return getDllimportVariable( 2153 N, SDLoc(N), Ty, DAG, DAG.getEntryNode(), 2154 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2155 } 2156 2157 if (!isPositionIndependent()) { 2158 const MipsTargetObjectFile *TLOF = 2159 static_cast<const MipsTargetObjectFile *>( 2160 getTargetMachine().getObjFileLowering()); 2161 const GlobalObject *GO = GV->getAliaseeObject(); 2162 if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine())) 2163 // %gp_rel relocation 2164 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64()); 2165 2166 // %hi/%lo relocation 2167 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG) 2168 // %highest/%higher/%hi/%lo relocation 2169 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG); 2170 } 2171 2172 // Every other architecture would use shouldAssumeDSOLocal in here, but 2173 // mips is special. 2174 // * In PIC code mips requires got loads even for local statics! 2175 // * To save on got entries, for local statics the got entry contains the 2176 // page and an additional add instruction takes care of the low bits. 2177 // * It is legal to access a hidden symbol with a non hidden undefined, 2178 // so one cannot guarantee that all access to a hidden symbol will know 2179 // it is hidden. 2180 // * Mips linkers don't support creating a page and a full got entry for 2181 // the same symbol. 2182 // * Given all that, we have to use a full got entry for hidden symbols :-( 2183 if (GV->hasLocalLinkage()) 2184 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64()); 2185 2186 if (Subtarget.useXGOT()) 2187 return getAddrGlobalLargeGOT( 2188 N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16, 2189 DAG.getEntryNode(), 2190 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2191 2192 return getAddrGlobal( 2193 N, SDLoc(N), Ty, DAG, 2194 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT, 2195 DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2196 } 2197 2198 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op, 2199 SelectionDAG &DAG) const { 2200 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 2201 EVT Ty = Op.getValueType(); 2202 2203 if (!isPositionIndependent()) 2204 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG) 2205 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG); 2206 2207 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64()); 2208 } 2209 2210 SDValue MipsTargetLowering:: 2211 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const 2212 { 2213 // If the relocation model is PIC, use the General Dynamic TLS Model or 2214 // Local Dynamic TLS model, otherwise use the Initial Exec or 2215 // Local Exec TLS Model. 2216 2217 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2218 if (DAG.getTarget().useEmulatedTLS()) 2219 return LowerToTLSEmulatedModel(GA, DAG); 2220 2221 SDLoc DL(GA); 2222 const GlobalValue *GV = GA->getGlobal(); 2223 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2224 2225 TLSModel::Model model = getTargetMachine().getTLSModel(GV); 2226 2227 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) { 2228 // General Dynamic and Local Dynamic TLS Model. 2229 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM 2230 : MipsII::MO_TLSGD; 2231 2232 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag); 2233 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, 2234 getGlobalReg(DAG, PtrVT), TGA); 2235 unsigned PtrSize = PtrVT.getSizeInBits(); 2236 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize); 2237 2238 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT); 2239 2240 ArgListTy Args; 2241 ArgListEntry Entry; 2242 Entry.Node = Argument; 2243 Entry.Ty = PtrTy; 2244 Args.push_back(Entry); 2245 2246 TargetLowering::CallLoweringInfo CLI(DAG); 2247 CLI.setDebugLoc(DL) 2248 .setChain(DAG.getEntryNode()) 2249 .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args)); 2250 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2251 2252 SDValue Ret = CallResult.first; 2253 2254 if (model != TLSModel::LocalDynamic) 2255 return Ret; 2256 2257 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 2258 MipsII::MO_DTPREL_HI); 2259 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi); 2260 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 2261 MipsII::MO_DTPREL_LO); 2262 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo); 2263 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret); 2264 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo); 2265 } 2266 2267 SDValue Offset; 2268 if (model == TLSModel::InitialExec) { 2269 // Initial Exec TLS Model 2270 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 2271 MipsII::MO_GOTTPREL); 2272 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT), 2273 TGA); 2274 Offset = 2275 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo()); 2276 } else { 2277 // Local Exec TLS Model 2278 assert(model == TLSModel::LocalExec); 2279 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 2280 MipsII::MO_TPREL_HI); 2281 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 2282 MipsII::MO_TPREL_LO); 2283 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi); 2284 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo); 2285 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2286 } 2287 2288 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT); 2289 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset); 2290 } 2291 2292 SDValue MipsTargetLowering:: 2293 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const 2294 { 2295 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 2296 EVT Ty = Op.getValueType(); 2297 2298 if (!isPositionIndependent()) 2299 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG) 2300 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG); 2301 2302 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64()); 2303 } 2304 2305 SDValue MipsTargetLowering:: 2306 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const 2307 { 2308 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 2309 EVT Ty = Op.getValueType(); 2310 2311 if (!isPositionIndependent()) { 2312 const MipsTargetObjectFile *TLOF = 2313 static_cast<const MipsTargetObjectFile *>( 2314 getTargetMachine().getObjFileLowering()); 2315 2316 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(), 2317 getTargetMachine())) 2318 // %gp_rel relocation 2319 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64()); 2320 2321 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG) 2322 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG); 2323 } 2324 2325 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64()); 2326 } 2327 2328 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 2329 MachineFunction &MF = DAG.getMachineFunction(); 2330 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>(); 2331 2332 SDLoc DL(Op); 2333 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 2334 getPointerTy(MF.getDataLayout())); 2335 2336 // vastart just stores the address of the VarArgsFrameIndex slot into the 2337 // memory location argument. 2338 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2339 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 2340 MachinePointerInfo(SV)); 2341 } 2342 2343 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2344 SDNode *Node = Op.getNode(); 2345 EVT VT = Node->getValueType(0); 2346 SDValue Chain = Node->getOperand(0); 2347 SDValue VAListPtr = Node->getOperand(1); 2348 const Align Align = 2349 llvm::MaybeAlign(Node->getConstantOperandVal(3)).valueOrOne(); 2350 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2351 SDLoc DL(Node); 2352 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4; 2353 2354 SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain, 2355 VAListPtr, MachinePointerInfo(SV)); 2356 SDValue VAList = VAListLoad; 2357 2358 // Re-align the pointer if necessary. 2359 // It should only ever be necessary for 64-bit types on O32 since the minimum 2360 // argument alignment is the same as the maximum type alignment for N32/N64. 2361 // 2362 // FIXME: We currently align too often. The code generator doesn't notice 2363 // when the pointer is still aligned from the last va_arg (or pair of 2364 // va_args for the i64 on O32 case). 2365 if (Align > getMinStackArgumentAlignment()) { 2366 VAList = DAG.getNode( 2367 ISD::ADD, DL, VAList.getValueType(), VAList, 2368 DAG.getConstant(Align.value() - 1, DL, VAList.getValueType())); 2369 2370 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList, 2371 DAG.getSignedConstant(-(int64_t)Align.value(), DL, 2372 VAList.getValueType())); 2373 } 2374 2375 // Increment the pointer, VAList, to the next vaarg. 2376 auto &TD = DAG.getDataLayout(); 2377 unsigned ArgSizeInBytes = 2378 TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext())); 2379 SDValue Tmp3 = 2380 DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList, 2381 DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes), 2382 DL, VAList.getValueType())); 2383 // Store the incremented VAList to the legalized pointer 2384 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr, 2385 MachinePointerInfo(SV)); 2386 2387 // In big-endian mode we must adjust the pointer when the load size is smaller 2388 // than the argument slot size. We must also reduce the known alignment to 2389 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get 2390 // the correct half of the slot, and reduce the alignment from 8 (slot 2391 // alignment) down to 4 (type alignment). 2392 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) { 2393 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes; 2394 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList, 2395 DAG.getIntPtrConstant(Adjustment, DL)); 2396 } 2397 // Load the actual argument out of the pointer VAList 2398 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo()); 2399 } 2400 2401 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, 2402 bool HasExtractInsert) { 2403 EVT TyX = Op.getOperand(0).getValueType(); 2404 EVT TyY = Op.getOperand(1).getValueType(); 2405 SDLoc DL(Op); 2406 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32); 2407 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32); 2408 SDValue Res; 2409 2410 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it 2411 // to i32. 2412 SDValue X = (TyX == MVT::f32) ? 2413 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) : 2414 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0), 2415 Const1); 2416 SDValue Y = (TyY == MVT::f32) ? 2417 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) : 2418 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1), 2419 Const1); 2420 2421 if (HasExtractInsert) { 2422 // ext E, Y, 31, 1 ; extract bit31 of Y 2423 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X 2424 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1); 2425 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X); 2426 } else { 2427 // sll SllX, X, 1 2428 // srl SrlX, SllX, 1 2429 // srl SrlY, Y, 31 2430 // sll SllY, SrlX, 31 2431 // or Or, SrlX, SllY 2432 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1); 2433 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1); 2434 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31); 2435 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31); 2436 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY); 2437 } 2438 2439 if (TyX == MVT::f32) 2440 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res); 2441 2442 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, 2443 Op.getOperand(0), 2444 DAG.getConstant(0, DL, MVT::i32)); 2445 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res); 2446 } 2447 2448 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, 2449 bool HasExtractInsert) { 2450 unsigned WidthX = Op.getOperand(0).getValueSizeInBits(); 2451 unsigned WidthY = Op.getOperand(1).getValueSizeInBits(); 2452 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY); 2453 SDLoc DL(Op); 2454 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32); 2455 2456 // Bitcast to integer nodes. 2457 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0)); 2458 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1)); 2459 2460 if (HasExtractInsert) { 2461 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y 2462 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X 2463 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y, 2464 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1); 2465 2466 if (WidthX > WidthY) 2467 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E); 2468 else if (WidthY > WidthX) 2469 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E); 2470 2471 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E, 2472 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1, 2473 X); 2474 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I); 2475 } 2476 2477 // (d)sll SllX, X, 1 2478 // (d)srl SrlX, SllX, 1 2479 // (d)srl SrlY, Y, width(Y)-1 2480 // (d)sll SllY, SrlX, width(Y)-1 2481 // or Or, SrlX, SllY 2482 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1); 2483 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1); 2484 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y, 2485 DAG.getConstant(WidthY - 1, DL, MVT::i32)); 2486 2487 if (WidthX > WidthY) 2488 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY); 2489 else if (WidthY > WidthX) 2490 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY); 2491 2492 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY, 2493 DAG.getConstant(WidthX - 1, DL, MVT::i32)); 2494 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY); 2495 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or); 2496 } 2497 2498 SDValue 2499 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 2500 if (Subtarget.isGP64bit()) 2501 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert()); 2502 2503 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert()); 2504 } 2505 2506 SDValue MipsTargetLowering::lowerFABS32(SDValue Op, SelectionDAG &DAG, 2507 bool HasExtractInsert) const { 2508 SDLoc DL(Op); 2509 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32); 2510 2511 if (DAG.getTarget().Options.NoNaNsFPMath || Subtarget.inAbs2008Mode()) 2512 return DAG.getNode(MipsISD::FAbs, DL, Op.getValueType(), Op.getOperand(0)); 2513 2514 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it 2515 // to i32. 2516 SDValue X = (Op.getValueType() == MVT::f32) 2517 ? DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) 2518 : DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, 2519 Op.getOperand(0), Const1); 2520 2521 // Clear MSB. 2522 if (HasExtractInsert) 2523 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, 2524 DAG.getRegister(Mips::ZERO, MVT::i32), 2525 DAG.getConstant(31, DL, MVT::i32), Const1, X); 2526 else { 2527 // TODO: Provide DAG patterns which transform (and x, cst) 2528 // back to a (shl (srl x (clz cst)) (clz cst)) sequence. 2529 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1); 2530 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1); 2531 } 2532 2533 if (Op.getValueType() == MVT::f32) 2534 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res); 2535 2536 // FIXME: For mips32r2, the sequence of (BuildPairF64 (ins (ExtractElementF64 2537 // Op 1), $zero, 31 1) (ExtractElementF64 Op 0)) and the Op has one use, we 2538 // should be able to drop the usage of mfc1/mtc1 and rewrite the register in 2539 // place. 2540 SDValue LowX = 2541 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0), 2542 DAG.getConstant(0, DL, MVT::i32)); 2543 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res); 2544 } 2545 2546 SDValue MipsTargetLowering::lowerFABS64(SDValue Op, SelectionDAG &DAG, 2547 bool HasExtractInsert) const { 2548 SDLoc DL(Op); 2549 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32); 2550 2551 if (DAG.getTarget().Options.NoNaNsFPMath || Subtarget.inAbs2008Mode()) 2552 return DAG.getNode(MipsISD::FAbs, DL, Op.getValueType(), Op.getOperand(0)); 2553 2554 // Bitcast to integer node. 2555 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0)); 2556 2557 // Clear MSB. 2558 if (HasExtractInsert) 2559 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64, 2560 DAG.getRegister(Mips::ZERO_64, MVT::i64), 2561 DAG.getConstant(63, DL, MVT::i32), Const1, X); 2562 else { 2563 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1); 2564 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1); 2565 } 2566 2567 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res); 2568 } 2569 2570 SDValue MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const { 2571 if ((ABI.IsN32() || ABI.IsN64()) && (Op.getValueType() == MVT::f64)) 2572 return lowerFABS64(Op, DAG, Subtarget.hasExtractInsert()); 2573 2574 return lowerFABS32(Op, DAG, Subtarget.hasExtractInsert()); 2575 } 2576 2577 SDValue MipsTargetLowering::lowerFCANONICALIZE(SDValue Op, 2578 SelectionDAG &DAG) const { 2579 SDLoc DL(Op); 2580 EVT VT = Op.getValueType(); 2581 SDValue Operand = Op.getOperand(0); 2582 SDNodeFlags Flags = Op->getFlags(); 2583 2584 if (Flags.hasNoNaNs() || DAG.isKnownNeverNaN(Operand)) 2585 return Operand; 2586 2587 SDValue Quiet = DAG.getNode(ISD::FADD, DL, VT, Operand, Operand); 2588 return DAG.getSelectCC(DL, Operand, Operand, Quiet, Operand, ISD::SETUO); 2589 } 2590 2591 SDValue MipsTargetLowering:: 2592 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 2593 // check the depth 2594 if (Op.getConstantOperandVal(0) != 0) { 2595 DAG.getContext()->emitError( 2596 "return address can be determined only for current frame"); 2597 return SDValue(); 2598 } 2599 2600 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 2601 MFI.setFrameAddressIsTaken(true); 2602 EVT VT = Op.getValueType(); 2603 SDLoc DL(Op); 2604 SDValue FrameAddr = DAG.getCopyFromReg( 2605 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT); 2606 return FrameAddr; 2607 } 2608 2609 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op, 2610 SelectionDAG &DAG) const { 2611 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 2612 return SDValue(); 2613 2614 // check the depth 2615 if (Op.getConstantOperandVal(0) != 0) { 2616 DAG.getContext()->emitError( 2617 "return address can be determined only for current frame"); 2618 return SDValue(); 2619 } 2620 2621 MachineFunction &MF = DAG.getMachineFunction(); 2622 MachineFrameInfo &MFI = MF.getFrameInfo(); 2623 MVT VT = Op.getSimpleValueType(); 2624 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA; 2625 MFI.setReturnAddressIsTaken(true); 2626 2627 // Return RA, which contains the return address. Mark it an implicit live-in. 2628 Register Reg = MF.addLiveIn(RA, getRegClassFor(VT)); 2629 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT); 2630 } 2631 2632 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is 2633 // generated from __builtin_eh_return (offset, handler) 2634 // The effect of this is to adjust the stack pointer by "offset" 2635 // and then branch to "handler". 2636 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG) 2637 const { 2638 MachineFunction &MF = DAG.getMachineFunction(); 2639 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); 2640 2641 MipsFI->setCallsEhReturn(); 2642 SDValue Chain = Op.getOperand(0); 2643 SDValue Offset = Op.getOperand(1); 2644 SDValue Handler = Op.getOperand(2); 2645 SDLoc DL(Op); 2646 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32; 2647 2648 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and 2649 // EH_RETURN nodes, so that instructions are emitted back-to-back. 2650 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1; 2651 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0; 2652 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue()); 2653 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1)); 2654 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain, 2655 DAG.getRegister(OffsetReg, Ty), 2656 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())), 2657 Chain.getValue(1)); 2658 } 2659 2660 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op, 2661 SelectionDAG &DAG) const { 2662 // FIXME: Need pseudo-fence for 'singlethread' fences 2663 // FIXME: Set SType for weaker fences where supported/appropriate. 2664 unsigned SType = 0; 2665 SDLoc DL(Op); 2666 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0), 2667 DAG.getConstant(SType, DL, MVT::i32)); 2668 } 2669 2670 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op, 2671 SelectionDAG &DAG) const { 2672 SDLoc DL(Op); 2673 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32; 2674 2675 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1); 2676 SDValue Shamt = Op.getOperand(2); 2677 // if shamt < (VT.bits): 2678 // lo = (shl lo, shamt) 2679 // hi = (or (shl hi, shamt) (srl (srl lo, 1), (xor shamt, (VT.bits-1)))) 2680 // else: 2681 // lo = 0 2682 // hi = (shl lo, shamt[4:0]) 2683 SDValue Not = 2684 DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt, 2685 DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32)); 2686 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, 2687 DAG.getConstant(1, DL, VT)); 2688 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not); 2689 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 2690 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 2691 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 2692 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt, 2693 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32)); 2694 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, 2695 DAG.getConstant(0, DL, VT), ShiftLeftLo); 2696 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or); 2697 2698 SDValue Ops[2] = {Lo, Hi}; 2699 return DAG.getMergeValues(Ops, DL); 2700 } 2701 2702 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 2703 bool IsSRA) const { 2704 SDLoc DL(Op); 2705 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1); 2706 SDValue Shamt = Op.getOperand(2); 2707 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32; 2708 2709 // if shamt < (VT.bits): 2710 // lo = (or (shl (shl hi, 1), (xor shamt, (VT.bits-1))) (srl lo, shamt)) 2711 // if isSRA: 2712 // hi = (sra hi, shamt) 2713 // else: 2714 // hi = (srl hi, shamt) 2715 // else: 2716 // if isSRA: 2717 // lo = (sra hi, shamt[4:0]) 2718 // hi = (sra hi, 31) 2719 // else: 2720 // lo = (srl hi, shamt[4:0]) 2721 // hi = 0 2722 SDValue Not = 2723 DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt, 2724 DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32)); 2725 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi, 2726 DAG.getConstant(1, DL, VT)); 2727 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not); 2728 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 2729 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 2730 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, 2731 DL, VT, Hi, Shamt); 2732 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt, 2733 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32)); 2734 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi, 2735 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT)); 2736 2737 if (!(Subtarget.hasMips4() || Subtarget.hasMips32())) { 2738 SDVTList VTList = DAG.getVTList(VT, VT); 2739 return DAG.getNode(Subtarget.isGP64bit() ? MipsISD::DOUBLE_SELECT_I64 2740 : MipsISD::DOUBLE_SELECT_I, 2741 DL, VTList, Cond, ShiftRightHi, 2742 IsSRA ? Ext : DAG.getConstant(0, DL, VT), Or, 2743 ShiftRightHi); 2744 } 2745 2746 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or); 2747 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, 2748 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi); 2749 2750 SDValue Ops[2] = {Lo, Hi}; 2751 return DAG.getMergeValues(Ops, DL); 2752 } 2753 2754 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD, 2755 SDValue Chain, SDValue Src, unsigned Offset) { 2756 SDValue Ptr = LD->getBasePtr(); 2757 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT(); 2758 EVT BasePtrVT = Ptr.getValueType(); 2759 SDLoc DL(LD); 2760 SDVTList VTList = DAG.getVTList(VT, MVT::Other); 2761 2762 if (Offset) 2763 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr, 2764 DAG.getConstant(Offset, DL, BasePtrVT)); 2765 2766 SDValue Ops[] = { Chain, Ptr, Src }; 2767 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT, 2768 LD->getMemOperand()); 2769 } 2770 2771 // Expand an unaligned 32 or 64-bit integer load node. 2772 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const { 2773 LoadSDNode *LD = cast<LoadSDNode>(Op); 2774 EVT MemVT = LD->getMemoryVT(); 2775 2776 if (Subtarget.systemSupportsUnalignedAccess()) 2777 return Op; 2778 2779 // Return if load is aligned or if MemVT is neither i32 nor i64. 2780 if ((LD->getAlign().value() >= (MemVT.getSizeInBits() / 8)) || 2781 ((MemVT != MVT::i32) && (MemVT != MVT::i64))) 2782 return SDValue(); 2783 2784 bool IsLittle = Subtarget.isLittle(); 2785 EVT VT = Op.getValueType(); 2786 ISD::LoadExtType ExtType = LD->getExtensionType(); 2787 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT); 2788 2789 assert((VT == MVT::i32) || (VT == MVT::i64)); 2790 2791 // Expand 2792 // (set dst, (i64 (load baseptr))) 2793 // to 2794 // (set tmp, (ldl (add baseptr, 7), undef)) 2795 // (set dst, (ldr baseptr, tmp)) 2796 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) { 2797 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef, 2798 IsLittle ? 7 : 0); 2799 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL, 2800 IsLittle ? 0 : 7); 2801 } 2802 2803 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef, 2804 IsLittle ? 3 : 0); 2805 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL, 2806 IsLittle ? 0 : 3); 2807 2808 // Expand 2809 // (set dst, (i32 (load baseptr))) or 2810 // (set dst, (i64 (sextload baseptr))) or 2811 // (set dst, (i64 (extload baseptr))) 2812 // to 2813 // (set tmp, (lwl (add baseptr, 3), undef)) 2814 // (set dst, (lwr baseptr, tmp)) 2815 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) || 2816 (ExtType == ISD::EXTLOAD)) 2817 return LWR; 2818 2819 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD)); 2820 2821 // Expand 2822 // (set dst, (i64 (zextload baseptr))) 2823 // to 2824 // (set tmp0, (lwl (add baseptr, 3), undef)) 2825 // (set tmp1, (lwr baseptr, tmp0)) 2826 // (set tmp2, (shl tmp1, 32)) 2827 // (set dst, (srl tmp2, 32)) 2828 SDLoc DL(LD); 2829 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32); 2830 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32); 2831 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32); 2832 SDValue Ops[] = { SRL, LWR.getValue(1) }; 2833 return DAG.getMergeValues(Ops, DL); 2834 } 2835 2836 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD, 2837 SDValue Chain, unsigned Offset) { 2838 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue(); 2839 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType(); 2840 SDLoc DL(SD); 2841 SDVTList VTList = DAG.getVTList(MVT::Other); 2842 2843 if (Offset) 2844 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr, 2845 DAG.getConstant(Offset, DL, BasePtrVT)); 2846 2847 SDValue Ops[] = { Chain, Value, Ptr }; 2848 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT, 2849 SD->getMemOperand()); 2850 } 2851 2852 // Expand an unaligned 32 or 64-bit integer store node. 2853 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG, 2854 bool IsLittle) { 2855 SDValue Value = SD->getValue(), Chain = SD->getChain(); 2856 EVT VT = Value.getValueType(); 2857 2858 // Expand 2859 // (store val, baseptr) or 2860 // (truncstore val, baseptr) 2861 // to 2862 // (swl val, (add baseptr, 3)) 2863 // (swr val, baseptr) 2864 if ((VT == MVT::i32) || SD->isTruncatingStore()) { 2865 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain, 2866 IsLittle ? 3 : 0); 2867 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3); 2868 } 2869 2870 assert(VT == MVT::i64); 2871 2872 // Expand 2873 // (store val, baseptr) 2874 // to 2875 // (sdl val, (add baseptr, 7)) 2876 // (sdr val, baseptr) 2877 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0); 2878 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7); 2879 } 2880 2881 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr). 2882 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG, 2883 bool SingleFloat) { 2884 SDValue Val = SD->getValue(); 2885 2886 if (Val.getOpcode() != ISD::FP_TO_SINT || 2887 (Val.getValueSizeInBits() > 32 && SingleFloat)) 2888 return SDValue(); 2889 2890 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits()); 2891 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy, 2892 Val.getOperand(0)); 2893 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(), 2894 SD->getPointerInfo(), SD->getAlign(), 2895 SD->getMemOperand()->getFlags()); 2896 } 2897 2898 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const { 2899 StoreSDNode *SD = cast<StoreSDNode>(Op); 2900 EVT MemVT = SD->getMemoryVT(); 2901 2902 // Lower unaligned integer stores. 2903 if (!Subtarget.systemSupportsUnalignedAccess() && 2904 (SD->getAlign().value() < (MemVT.getSizeInBits() / 8)) && 2905 ((MemVT == MVT::i32) || (MemVT == MVT::i64))) 2906 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle()); 2907 2908 return lowerFP_TO_SINT_STORE(SD, DAG, Subtarget.isSingleFloat()); 2909 } 2910 2911 SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 2912 SelectionDAG &DAG) const { 2913 2914 // Return a fixed StackObject with offset 0 which points to the old stack 2915 // pointer. 2916 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 2917 EVT ValTy = Op->getValueType(0); 2918 int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false); 2919 return DAG.getFrameIndex(FI, ValTy); 2920 } 2921 2922 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op, 2923 SelectionDAG &DAG) const { 2924 if (Op.getValueSizeInBits() > 32 && Subtarget.isSingleFloat()) 2925 return SDValue(); 2926 2927 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits()); 2928 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy, 2929 Op.getOperand(0)); 2930 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc); 2931 } 2932 2933 //===----------------------------------------------------------------------===// 2934 // Calling Convention Implementation 2935 //===----------------------------------------------------------------------===// 2936 2937 //===----------------------------------------------------------------------===// 2938 // TODO: Implement a generic logic using tblgen that can support this. 2939 // Mips O32 ABI rules: 2940 // --- 2941 // i32 - Passed in A0, A1, A2, A3 and stack 2942 // f32 - Only passed in f32 registers if no int reg has been used yet to hold 2943 // an argument. Otherwise, passed in A1, A2, A3 and stack. 2944 // f64 - Only passed in two aliased f32 registers if no int reg has been used 2945 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is 2946 // not used, it must be shadowed. If only A3 is available, shadow it and 2947 // go to stack. 2948 // vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack. 2949 // vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3} 2950 // with the remainder spilled to the stack. 2951 // vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases 2952 // spilling the remainder to the stack. 2953 // 2954 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack. 2955 //===----------------------------------------------------------------------===// 2956 2957 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT, 2958 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 2959 CCState &State, ArrayRef<MCPhysReg> F64Regs) { 2960 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>( 2961 State.getMachineFunction().getSubtarget()); 2962 2963 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 }; 2964 2965 const MipsCCState * MipsState = static_cast<MipsCCState *>(&State); 2966 2967 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 }; 2968 2969 static const MCPhysReg FloatVectorIntRegs[] = { Mips::A0, Mips::A2 }; 2970 2971 // Do not process byval args here. 2972 if (ArgFlags.isByVal()) 2973 return true; 2974 2975 // Promote i8 and i16 2976 if (ArgFlags.isInReg() && !Subtarget.isLittle()) { 2977 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) { 2978 LocVT = MVT::i32; 2979 if (ArgFlags.isSExt()) 2980 LocInfo = CCValAssign::SExtUpper; 2981 else if (ArgFlags.isZExt()) 2982 LocInfo = CCValAssign::ZExtUpper; 2983 else 2984 LocInfo = CCValAssign::AExtUpper; 2985 } 2986 } 2987 2988 // Promote i8 and i16 2989 if (LocVT == MVT::i8 || LocVT == MVT::i16) { 2990 LocVT = MVT::i32; 2991 if (ArgFlags.isSExt()) 2992 LocInfo = CCValAssign::SExt; 2993 else if (ArgFlags.isZExt()) 2994 LocInfo = CCValAssign::ZExt; 2995 else 2996 LocInfo = CCValAssign::AExt; 2997 } 2998 2999 unsigned Reg; 3000 3001 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following 3002 // is true: function is vararg, argument is 3rd or higher, there is previous 3003 // argument which is not f32 or f64. 3004 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 || 3005 State.getFirstUnallocated(F32Regs) != ValNo; 3006 Align OrigAlign = ArgFlags.getNonZeroOrigAlign(); 3007 bool isI64 = (ValVT == MVT::i32 && OrigAlign == Align(8)); 3008 bool isVectorFloat = MipsState->WasOriginalArgVectorFloat(ValNo); 3009 3010 // The MIPS vector ABI for floats passes them in a pair of registers 3011 if (ValVT == MVT::i32 && isVectorFloat) { 3012 // This is the start of an vector that was scalarized into an unknown number 3013 // of components. It doesn't matter how many there are. Allocate one of the 3014 // notional 8 byte aligned registers which map onto the argument stack, and 3015 // shadow the register lost to alignment requirements. 3016 if (ArgFlags.isSplit()) { 3017 Reg = State.AllocateReg(FloatVectorIntRegs); 3018 if (Reg == Mips::A2) 3019 State.AllocateReg(Mips::A1); 3020 else if (Reg == 0) 3021 State.AllocateReg(Mips::A3); 3022 } else { 3023 // If we're an intermediate component of the split, we can just attempt to 3024 // allocate a register directly. 3025 Reg = State.AllocateReg(IntRegs); 3026 } 3027 } else if (ValVT == MVT::i32 || 3028 (ValVT == MVT::f32 && AllocateFloatsInIntReg)) { 3029 Reg = State.AllocateReg(IntRegs); 3030 // If this is the first part of an i64 arg, 3031 // the allocated register must be either A0 or A2. 3032 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3)) 3033 Reg = State.AllocateReg(IntRegs); 3034 LocVT = MVT::i32; 3035 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) { 3036 // Allocate int register and shadow next int register. If first 3037 // available register is Mips::A1 or Mips::A3, shadow it too. 3038 Reg = State.AllocateReg(IntRegs); 3039 if (Reg == Mips::A1 || Reg == Mips::A3) 3040 Reg = State.AllocateReg(IntRegs); 3041 3042 if (Reg) { 3043 LocVT = MVT::i32; 3044 3045 State.addLoc( 3046 CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 3047 MCRegister HiReg = State.AllocateReg(IntRegs); 3048 assert(HiReg); 3049 State.addLoc( 3050 CCValAssign::getCustomReg(ValNo, ValVT, HiReg, LocVT, LocInfo)); 3051 return false; 3052 } 3053 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) { 3054 // we are guaranteed to find an available float register 3055 if (ValVT == MVT::f32) { 3056 Reg = State.AllocateReg(F32Regs); 3057 // Shadow int register 3058 State.AllocateReg(IntRegs); 3059 } else { 3060 Reg = State.AllocateReg(F64Regs); 3061 // Shadow int registers 3062 MCRegister Reg2 = State.AllocateReg(IntRegs); 3063 if (Reg2 == Mips::A1 || Reg2 == Mips::A3) 3064 State.AllocateReg(IntRegs); 3065 State.AllocateReg(IntRegs); 3066 } 3067 } else 3068 llvm_unreachable("Cannot handle this ValVT."); 3069 3070 if (!Reg) { 3071 unsigned Offset = State.AllocateStack(ValVT.getStoreSize(), OrigAlign); 3072 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 3073 } else 3074 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 3075 3076 return false; 3077 } 3078 3079 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT, 3080 MVT LocVT, CCValAssign::LocInfo LocInfo, 3081 ISD::ArgFlagsTy ArgFlags, CCState &State) { 3082 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 }; 3083 3084 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs); 3085 } 3086 3087 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT, 3088 MVT LocVT, CCValAssign::LocInfo LocInfo, 3089 ISD::ArgFlagsTy ArgFlags, CCState &State) { 3090 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 }; 3091 3092 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs); 3093 } 3094 3095 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT, 3096 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 3097 CCState &State) LLVM_ATTRIBUTE_UNUSED; 3098 3099 #include "MipsGenCallingConv.inc" 3100 3101 CCAssignFn *MipsTargetLowering::CCAssignFnForCall() const{ 3102 return CC_Mips_FixedArg; 3103 } 3104 3105 CCAssignFn *MipsTargetLowering::CCAssignFnForReturn() const{ 3106 return RetCC_Mips; 3107 } 3108 //===----------------------------------------------------------------------===// 3109 // Call Calling Convention Implementation 3110 //===----------------------------------------------------------------------===// 3111 3112 SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset, 3113 SDValue Chain, SDValue Arg, 3114 const SDLoc &DL, bool IsTailCall, 3115 SelectionDAG &DAG) const { 3116 if (!IsTailCall) { 3117 SDValue PtrOff = 3118 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr, 3119 DAG.getIntPtrConstant(Offset, DL)); 3120 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo()); 3121 } 3122 3123 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 3124 int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false); 3125 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3126 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(), MaybeAlign(), 3127 MachineMemOperand::MOVolatile); 3128 } 3129 3130 void MipsTargetLowering:: 3131 getOpndList(SmallVectorImpl<SDValue> &Ops, 3132 std::deque<std::pair<unsigned, SDValue>> &RegsToPass, 3133 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage, 3134 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee, 3135 SDValue Chain) const { 3136 // Insert node "GP copy globalreg" before call to function. 3137 // 3138 // R_MIPS_CALL* operators (emitted when non-internal functions are called 3139 // in PIC mode) allow symbols to be resolved via lazy binding. 3140 // The lazy binding stub requires GP to point to the GOT. 3141 // Note that we don't need GP to point to the GOT for indirect calls 3142 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates 3143 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs 3144 // used for the function (that is, Mips linker doesn't generate lazy binding 3145 // stub for a function whose address is taken in the program). 3146 if (IsPICCall && !InternalLinkage && IsCallReloc) { 3147 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP; 3148 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32; 3149 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty))); 3150 } 3151 3152 // Build a sequence of copy-to-reg nodes chained together with token 3153 // chain and flag operands which copy the outgoing args into registers. 3154 // The InGlue in necessary since all emitted instructions must be 3155 // stuck together. 3156 SDValue InGlue; 3157 3158 for (auto &R : RegsToPass) { 3159 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, R.first, R.second, InGlue); 3160 InGlue = Chain.getValue(1); 3161 } 3162 3163 // Add argument registers to the end of the list so that they are 3164 // known live into the call. 3165 for (auto &R : RegsToPass) 3166 Ops.push_back(CLI.DAG.getRegister(R.first, R.second.getValueType())); 3167 3168 // Add a register mask operand representing the call-preserved registers. 3169 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 3170 const uint32_t *Mask = 3171 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv); 3172 assert(Mask && "Missing call preserved mask for calling convention"); 3173 if (Subtarget.inMips16HardFloat()) { 3174 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) { 3175 StringRef Sym = G->getGlobal()->getName(); 3176 Function *F = G->getGlobal()->getParent()->getFunction(Sym); 3177 if (F && F->hasFnAttribute("__Mips16RetHelper")) { 3178 Mask = MipsRegisterInfo::getMips16RetHelperMask(); 3179 } 3180 } 3181 } 3182 Ops.push_back(CLI.DAG.getRegisterMask(Mask)); 3183 3184 if (InGlue.getNode()) 3185 Ops.push_back(InGlue); 3186 } 3187 3188 void MipsTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 3189 SDNode *Node) const { 3190 switch (MI.getOpcode()) { 3191 default: 3192 return; 3193 case Mips::JALR: 3194 case Mips::JALRPseudo: 3195 case Mips::JALR64: 3196 case Mips::JALR64Pseudo: 3197 case Mips::JALR16_MM: 3198 case Mips::JALRC16_MMR6: 3199 case Mips::TAILCALLREG: 3200 case Mips::TAILCALLREG64: 3201 case Mips::TAILCALLR6REG: 3202 case Mips::TAILCALL64R6REG: 3203 case Mips::TAILCALLREG_MM: 3204 case Mips::TAILCALLREG_MMR6: { 3205 if (!EmitJalrReloc || 3206 Subtarget.inMips16Mode() || 3207 !isPositionIndependent() || 3208 Node->getNumOperands() < 1 || 3209 Node->getOperand(0).getNumOperands() < 2) { 3210 return; 3211 } 3212 // We are after the callee address, set by LowerCall(). 3213 // If added to MI, asm printer will emit .reloc R_MIPS_JALR for the 3214 // symbol. 3215 const SDValue TargetAddr = Node->getOperand(0).getOperand(1); 3216 StringRef Sym; 3217 if (const GlobalAddressSDNode *G = 3218 dyn_cast_or_null<const GlobalAddressSDNode>(TargetAddr)) { 3219 // We must not emit the R_MIPS_JALR relocation against data symbols 3220 // since this will cause run-time crashes if the linker replaces the 3221 // call instruction with a relative branch to the data symbol. 3222 if (!isa<Function>(G->getGlobal())) { 3223 LLVM_DEBUG(dbgs() << "Not adding R_MIPS_JALR against data symbol " 3224 << G->getGlobal()->getName() << "\n"); 3225 return; 3226 } 3227 Sym = G->getGlobal()->getName(); 3228 } 3229 else if (const ExternalSymbolSDNode *ES = 3230 dyn_cast_or_null<const ExternalSymbolSDNode>(TargetAddr)) { 3231 Sym = ES->getSymbol(); 3232 } 3233 3234 if (Sym.empty()) 3235 return; 3236 3237 MachineFunction *MF = MI.getParent()->getParent(); 3238 MCSymbol *S = MF->getContext().getOrCreateSymbol(Sym); 3239 LLVM_DEBUG(dbgs() << "Adding R_MIPS_JALR against " << Sym << "\n"); 3240 MI.addOperand(MachineOperand::CreateMCSymbol(S, MipsII::MO_JALR)); 3241 } 3242 } 3243 } 3244 3245 /// LowerCall - functions arguments are copied from virtual regs to 3246 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted. 3247 SDValue 3248 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 3249 SmallVectorImpl<SDValue> &InVals) const { 3250 SelectionDAG &DAG = CLI.DAG; 3251 SDLoc DL = CLI.DL; 3252 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 3253 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 3254 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 3255 SDValue Chain = CLI.Chain; 3256 SDValue Callee = CLI.Callee; 3257 bool &IsTailCall = CLI.IsTailCall; 3258 CallingConv::ID CallConv = CLI.CallConv; 3259 bool IsVarArg = CLI.IsVarArg; 3260 3261 MachineFunction &MF = DAG.getMachineFunction(); 3262 MachineFrameInfo &MFI = MF.getFrameInfo(); 3263 const TargetFrameLowering *TFL = Subtarget.getFrameLowering(); 3264 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>(); 3265 bool IsPIC = isPositionIndependent(); 3266 3267 // Analyze operands of the call, assigning locations to each operand. 3268 SmallVector<CCValAssign, 16> ArgLocs; 3269 MipsCCState CCInfo( 3270 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(), 3271 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget)); 3272 3273 const ExternalSymbolSDNode *ES = 3274 dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode()); 3275 3276 // There is one case where CALLSEQ_START..CALLSEQ_END can be nested, which 3277 // is during the lowering of a call with a byval argument which produces 3278 // a call to memcpy. For the O32 case, this causes the caller to allocate 3279 // stack space for the reserved argument area for the callee, then recursively 3280 // again for the memcpy call. In the NEWABI case, this doesn't occur as those 3281 // ABIs mandate that the callee allocates the reserved argument area. We do 3282 // still produce nested CALLSEQ_START..CALLSEQ_END with zero space though. 3283 // 3284 // If the callee has a byval argument and memcpy is used, we are mandated 3285 // to already have produced a reserved argument area for the callee for O32. 3286 // Therefore, the reserved argument area can be reused for both calls. 3287 // 3288 // Other cases of calling memcpy cannot have a chain with a CALLSEQ_START 3289 // present, as we have yet to hook that node onto the chain. 3290 // 3291 // Hence, the CALLSEQ_START and CALLSEQ_END nodes can be eliminated in this 3292 // case. GCC does a similar trick, in that wherever possible, it calculates 3293 // the maximum out going argument area (including the reserved area), and 3294 // preallocates the stack space on entrance to the caller. 3295 // 3296 // FIXME: We should do the same for efficiency and space. 3297 3298 // Note: The check on the calling convention below must match 3299 // MipsABIInfo::GetCalleeAllocdArgSizeInBytes(). 3300 bool MemcpyInByVal = ES && StringRef(ES->getSymbol()) == "memcpy" && 3301 CallConv != CallingConv::Fast && 3302 Chain.getOpcode() == ISD::CALLSEQ_START; 3303 3304 // Allocate the reserved argument area. It seems strange to do this from the 3305 // caller side but removing it breaks the frame size calculation. 3306 unsigned ReservedArgArea = 3307 MemcpyInByVal ? 0 : ABI.GetCalleeAllocdArgSizeInBytes(CallConv); 3308 CCInfo.AllocateStack(ReservedArgArea, Align(1)); 3309 3310 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), 3311 ES ? ES->getSymbol() : nullptr); 3312 3313 // Get a count of how many bytes are to be pushed on the stack. 3314 unsigned StackSize = CCInfo.getStackSize(); 3315 3316 // Call site info for function parameters tracking. 3317 MachineFunction::CallSiteInfo CSInfo; 3318 3319 // Check if it's really possible to do a tail call. Restrict it to functions 3320 // that are part of this compilation unit. 3321 bool InternalLinkage = false; 3322 if (IsTailCall) { 3323 IsTailCall = isEligibleForTailCallOptimization( 3324 CCInfo, StackSize, *MF.getInfo<MipsFunctionInfo>()); 3325 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3326 InternalLinkage = G->getGlobal()->hasInternalLinkage(); 3327 IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() || 3328 G->getGlobal()->hasPrivateLinkage() || 3329 G->getGlobal()->hasHiddenVisibility() || 3330 G->getGlobal()->hasProtectedVisibility()); 3331 } 3332 } 3333 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) 3334 report_fatal_error("failed to perform tail call elimination on a call " 3335 "site marked musttail"); 3336 3337 if (IsTailCall) 3338 ++NumTailCalls; 3339 3340 // Chain is the output chain of the last Load/Store or CopyToReg node. 3341 // ByValChain is the output chain of the last Memcpy node created for copying 3342 // byval arguments to the stack. 3343 unsigned StackAlignment = TFL->getStackAlignment(); 3344 StackSize = alignTo(StackSize, StackAlignment); 3345 3346 if (!(IsTailCall || MemcpyInByVal)) 3347 Chain = DAG.getCALLSEQ_START(Chain, StackSize, 0, DL); 3348 3349 SDValue StackPtr = 3350 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP, 3351 getPointerTy(DAG.getDataLayout())); 3352 3353 std::deque<std::pair<unsigned, SDValue>> RegsToPass; 3354 SmallVector<SDValue, 8> MemOpChains; 3355 3356 CCInfo.rewindByValRegsInfo(); 3357 3358 // Walk the register/memloc assignments, inserting copies/loads. 3359 for (unsigned i = 0, e = ArgLocs.size(), OutIdx = 0; i != e; ++i, ++OutIdx) { 3360 SDValue Arg = OutVals[OutIdx]; 3361 CCValAssign &VA = ArgLocs[i]; 3362 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT(); 3363 ISD::ArgFlagsTy Flags = Outs[OutIdx].Flags; 3364 bool UseUpperBits = false; 3365 3366 // ByVal Arg. 3367 if (Flags.isByVal()) { 3368 unsigned FirstByValReg, LastByValReg; 3369 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed(); 3370 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg); 3371 3372 assert(Flags.getByValSize() && 3373 "ByVal args of size 0 should have been ignored by front-end."); 3374 assert(ByValIdx < CCInfo.getInRegsParamsCount()); 3375 assert(!IsTailCall && 3376 "Do not tail-call optimize if there is a byval argument."); 3377 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg, 3378 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(), 3379 VA); 3380 CCInfo.nextInRegsParam(); 3381 continue; 3382 } 3383 3384 // Promote the value if needed. 3385 switch (VA.getLocInfo()) { 3386 default: 3387 llvm_unreachable("Unknown loc info!"); 3388 case CCValAssign::Full: 3389 if (VA.isRegLoc()) { 3390 if ((ValVT == MVT::f32 && LocVT == MVT::i32) || 3391 (ValVT == MVT::f64 && LocVT == MVT::i64) || 3392 (ValVT == MVT::i64 && LocVT == MVT::f64)) 3393 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg); 3394 else if (ValVT == MVT::f64 && LocVT == MVT::i32) { 3395 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, 3396 Arg, DAG.getConstant(0, DL, MVT::i32)); 3397 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, 3398 Arg, DAG.getConstant(1, DL, MVT::i32)); 3399 if (!Subtarget.isLittle()) 3400 std::swap(Lo, Hi); 3401 3402 assert(VA.needsCustom()); 3403 3404 Register LocRegLo = VA.getLocReg(); 3405 Register LocRegHigh = ArgLocs[++i].getLocReg(); 3406 RegsToPass.push_back(std::make_pair(LocRegLo, Lo)); 3407 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi)); 3408 continue; 3409 } 3410 } 3411 break; 3412 case CCValAssign::BCvt: 3413 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg); 3414 break; 3415 case CCValAssign::SExtUpper: 3416 UseUpperBits = true; 3417 [[fallthrough]]; 3418 case CCValAssign::SExt: 3419 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg); 3420 break; 3421 case CCValAssign::ZExtUpper: 3422 UseUpperBits = true; 3423 [[fallthrough]]; 3424 case CCValAssign::ZExt: 3425 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg); 3426 break; 3427 case CCValAssign::AExtUpper: 3428 UseUpperBits = true; 3429 [[fallthrough]]; 3430 case CCValAssign::AExt: 3431 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg); 3432 break; 3433 } 3434 3435 if (UseUpperBits) { 3436 unsigned ValSizeInBits = Outs[OutIdx].ArgVT.getSizeInBits(); 3437 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits(); 3438 Arg = DAG.getNode( 3439 ISD::SHL, DL, VA.getLocVT(), Arg, 3440 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT())); 3441 } 3442 3443 // Arguments that can be passed on register must be kept at 3444 // RegsToPass vector 3445 if (VA.isRegLoc()) { 3446 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3447 3448 // If the parameter is passed through reg $D, which splits into 3449 // two physical registers, avoid creating call site info. 3450 if (Mips::AFGR64RegClass.contains(VA.getLocReg())) 3451 continue; 3452 3453 // Collect CSInfo about which register passes which parameter. 3454 const TargetOptions &Options = DAG.getTarget().Options; 3455 if (Options.EmitCallSiteInfo) 3456 CSInfo.ArgRegPairs.emplace_back(VA.getLocReg(), i); 3457 3458 continue; 3459 } 3460 3461 // Register can't get to this point... 3462 assert(VA.isMemLoc()); 3463 3464 // emit ISD::STORE whichs stores the 3465 // parameter value to a stack Location 3466 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(), 3467 Chain, Arg, DL, IsTailCall, DAG)); 3468 } 3469 3470 // Transform all store nodes into one single node because all store 3471 // nodes are independent of each other. 3472 if (!MemOpChains.empty()) 3473 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3474 3475 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 3476 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 3477 // node so that legalize doesn't hack it. 3478 3479 EVT Ty = Callee.getValueType(); 3480 bool GlobalOrExternal = false, IsCallReloc = false; 3481 3482 // The long-calls feature is ignored in case of PIC. 3483 // While we do not support -mshared / -mno-shared properly, 3484 // ignore long-calls in case of -mabicalls too. 3485 if (!Subtarget.isABICalls() && !IsPIC) { 3486 // If the function should be called using "long call", 3487 // get its address into a register to prevent using 3488 // of the `jal` instruction for the direct call. 3489 if (auto *N = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3490 if (Subtarget.useLongCalls()) 3491 Callee = Subtarget.hasSym32() 3492 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG) 3493 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG); 3494 } else if (auto *N = dyn_cast<GlobalAddressSDNode>(Callee)) { 3495 bool UseLongCalls = Subtarget.useLongCalls(); 3496 // If the function has long-call/far/near attribute 3497 // it overrides command line switch pased to the backend. 3498 if (auto *F = dyn_cast<Function>(N->getGlobal())) { 3499 if (F->hasFnAttribute("long-call")) 3500 UseLongCalls = true; 3501 else if (F->hasFnAttribute("short-call")) 3502 UseLongCalls = false; 3503 } 3504 if (UseLongCalls) 3505 Callee = Subtarget.hasSym32() 3506 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG) 3507 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG); 3508 } 3509 } 3510 3511 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3512 if (Subtarget.isTargetCOFF() && 3513 G->getGlobal()->hasDLLImportStorageClass()) { 3514 assert(Subtarget.isTargetWindows() && 3515 "Windows is the only supported COFF target"); 3516 auto PtrInfo = MachinePointerInfo(); 3517 Callee = DAG.getLoad(Ty, DL, Chain, 3518 getDllimportSymbol(G, SDLoc(G), Ty, DAG), PtrInfo); 3519 } else if (IsPIC) { 3520 const GlobalValue *Val = G->getGlobal(); 3521 InternalLinkage = Val->hasInternalLinkage(); 3522 3523 if (InternalLinkage) 3524 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64()); 3525 else if (Subtarget.useXGOT()) { 3526 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16, 3527 MipsII::MO_CALL_LO16, Chain, 3528 FuncInfo->callPtrInfo(MF, Val)); 3529 IsCallReloc = true; 3530 } else { 3531 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain, 3532 FuncInfo->callPtrInfo(MF, Val)); 3533 IsCallReloc = true; 3534 } 3535 } else 3536 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, 3537 getPointerTy(DAG.getDataLayout()), 0, 3538 MipsII::MO_NO_FLAG); 3539 GlobalOrExternal = true; 3540 } 3541 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3542 const char *Sym = S->getSymbol(); 3543 3544 if (!IsPIC) // static 3545 Callee = DAG.getTargetExternalSymbol( 3546 Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG); 3547 else if (Subtarget.useXGOT()) { 3548 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16, 3549 MipsII::MO_CALL_LO16, Chain, 3550 FuncInfo->callPtrInfo(MF, Sym)); 3551 IsCallReloc = true; 3552 } else { // PIC 3553 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain, 3554 FuncInfo->callPtrInfo(MF, Sym)); 3555 IsCallReloc = true; 3556 } 3557 3558 GlobalOrExternal = true; 3559 } 3560 3561 SmallVector<SDValue, 8> Ops(1, Chain); 3562 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3563 3564 getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage, 3565 IsCallReloc, CLI, Callee, Chain); 3566 3567 if (IsTailCall) { 3568 MF.getFrameInfo().setHasTailCall(); 3569 SDValue Ret = DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops); 3570 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 3571 return Ret; 3572 } 3573 3574 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops); 3575 SDValue InGlue = Chain.getValue(1); 3576 3577 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 3578 3579 // Create the CALLSEQ_END node in the case of where it is not a call to 3580 // memcpy. 3581 if (!(MemcpyInByVal)) { 3582 Chain = DAG.getCALLSEQ_END(Chain, StackSize, 0, InGlue, DL); 3583 InGlue = Chain.getValue(1); 3584 } 3585 3586 // Handle result values, copying them out of physregs into vregs that we 3587 // return. 3588 return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG, 3589 InVals, CLI); 3590 } 3591 3592 /// LowerCallResult - Lower the result values of a call into the 3593 /// appropriate copies out of appropriate physical registers. 3594 SDValue MipsTargetLowering::LowerCallResult( 3595 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg, 3596 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3597 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 3598 TargetLowering::CallLoweringInfo &CLI) const { 3599 // Assign locations to each value returned by this call. 3600 SmallVector<CCValAssign, 16> RVLocs; 3601 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 3602 *DAG.getContext()); 3603 3604 const ExternalSymbolSDNode *ES = 3605 dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode()); 3606 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy, 3607 ES ? ES->getSymbol() : nullptr); 3608 3609 // Copy all of the result registers out of their specified physreg. 3610 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3611 CCValAssign &VA = RVLocs[i]; 3612 assert(VA.isRegLoc() && "Can only return in registers!"); 3613 3614 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(), 3615 RVLocs[i].getLocVT(), InGlue); 3616 Chain = Val.getValue(1); 3617 InGlue = Val.getValue(2); 3618 3619 if (VA.isUpperBitsInLoc()) { 3620 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits(); 3621 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits(); 3622 unsigned Shift = 3623 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA; 3624 Val = DAG.getNode( 3625 Shift, DL, VA.getLocVT(), Val, 3626 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT())); 3627 } 3628 3629 switch (VA.getLocInfo()) { 3630 default: 3631 llvm_unreachable("Unknown loc info!"); 3632 case CCValAssign::Full: 3633 break; 3634 case CCValAssign::BCvt: 3635 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 3636 break; 3637 case CCValAssign::AExt: 3638 case CCValAssign::AExtUpper: 3639 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 3640 break; 3641 case CCValAssign::ZExt: 3642 case CCValAssign::ZExtUpper: 3643 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 3644 DAG.getValueType(VA.getValVT())); 3645 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 3646 break; 3647 case CCValAssign::SExt: 3648 case CCValAssign::SExtUpper: 3649 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 3650 DAG.getValueType(VA.getValVT())); 3651 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 3652 break; 3653 } 3654 3655 InVals.push_back(Val); 3656 } 3657 3658 return Chain; 3659 } 3660 3661 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA, 3662 EVT ArgVT, const SDLoc &DL, 3663 SelectionDAG &DAG) { 3664 MVT LocVT = VA.getLocVT(); 3665 EVT ValVT = VA.getValVT(); 3666 3667 // Shift into the upper bits if necessary. 3668 switch (VA.getLocInfo()) { 3669 default: 3670 break; 3671 case CCValAssign::AExtUpper: 3672 case CCValAssign::SExtUpper: 3673 case CCValAssign::ZExtUpper: { 3674 unsigned ValSizeInBits = ArgVT.getSizeInBits(); 3675 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits(); 3676 unsigned Opcode = 3677 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA; 3678 Val = DAG.getNode( 3679 Opcode, DL, VA.getLocVT(), Val, 3680 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT())); 3681 break; 3682 } 3683 } 3684 3685 // If this is an value smaller than the argument slot size (32-bit for O32, 3686 // 64-bit for N32/N64), it has been promoted in some way to the argument slot 3687 // size. Extract the value and insert any appropriate assertions regarding 3688 // sign/zero extension. 3689 switch (VA.getLocInfo()) { 3690 default: 3691 llvm_unreachable("Unknown loc info!"); 3692 case CCValAssign::Full: 3693 break; 3694 case CCValAssign::AExtUpper: 3695 case CCValAssign::AExt: 3696 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 3697 break; 3698 case CCValAssign::SExtUpper: 3699 case CCValAssign::SExt: 3700 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT)); 3701 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 3702 break; 3703 case CCValAssign::ZExtUpper: 3704 case CCValAssign::ZExt: 3705 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT)); 3706 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 3707 break; 3708 case CCValAssign::BCvt: 3709 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 3710 break; 3711 } 3712 3713 return Val; 3714 } 3715 3716 //===----------------------------------------------------------------------===// 3717 // Formal Arguments Calling Convention Implementation 3718 //===----------------------------------------------------------------------===// 3719 /// LowerFormalArguments - transform physical registers into virtual registers 3720 /// and generate load operations for arguments places on the stack. 3721 SDValue MipsTargetLowering::LowerFormalArguments( 3722 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 3723 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3724 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3725 MachineFunction &MF = DAG.getMachineFunction(); 3726 MachineFrameInfo &MFI = MF.getFrameInfo(); 3727 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); 3728 3729 MipsFI->setVarArgsFrameIndex(0); 3730 3731 // Used with vargs to acumulate store chains. 3732 std::vector<SDValue> OutChains; 3733 3734 // Assign locations to all of the incoming arguments. 3735 SmallVector<CCValAssign, 16> ArgLocs; 3736 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 3737 *DAG.getContext()); 3738 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), Align(1)); 3739 const Function &Func = DAG.getMachineFunction().getFunction(); 3740 Function::const_arg_iterator FuncArg = Func.arg_begin(); 3741 3742 if (Func.hasFnAttribute("interrupt") && !Func.arg_empty()) 3743 report_fatal_error( 3744 "Functions with the interrupt attribute cannot have arguments!"); 3745 3746 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg); 3747 MipsFI->setFormalArgInfo(CCInfo.getStackSize(), 3748 CCInfo.getInRegsParamsCount() > 0); 3749 3750 unsigned CurArgIdx = 0; 3751 CCInfo.rewindByValRegsInfo(); 3752 3753 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) { 3754 CCValAssign &VA = ArgLocs[i]; 3755 if (Ins[InsIdx].isOrigArg()) { 3756 std::advance(FuncArg, Ins[InsIdx].getOrigArgIndex() - CurArgIdx); 3757 CurArgIdx = Ins[InsIdx].getOrigArgIndex(); 3758 } 3759 EVT ValVT = VA.getValVT(); 3760 ISD::ArgFlagsTy Flags = Ins[InsIdx].Flags; 3761 bool IsRegLoc = VA.isRegLoc(); 3762 3763 if (Flags.isByVal()) { 3764 assert(Ins[InsIdx].isOrigArg() && "Byval arguments cannot be implicit"); 3765 unsigned FirstByValReg, LastByValReg; 3766 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed(); 3767 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg); 3768 3769 assert(Flags.getByValSize() && 3770 "ByVal args of size 0 should have been ignored by front-end."); 3771 assert(ByValIdx < CCInfo.getInRegsParamsCount()); 3772 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg, 3773 FirstByValReg, LastByValReg, VA, CCInfo); 3774 CCInfo.nextInRegsParam(); 3775 continue; 3776 } 3777 3778 // Arguments stored on registers 3779 if (IsRegLoc) { 3780 MVT RegVT = VA.getLocVT(); 3781 Register ArgReg = VA.getLocReg(); 3782 const TargetRegisterClass *RC = getRegClassFor(RegVT); 3783 3784 // Transform the arguments stored on 3785 // physical registers into virtual ones 3786 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC); 3787 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 3788 3789 ArgValue = 3790 UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG); 3791 3792 // Handle floating point arguments passed in integer registers and 3793 // long double arguments passed in floating point registers. 3794 if ((RegVT == MVT::i32 && ValVT == MVT::f32) || 3795 (RegVT == MVT::i64 && ValVT == MVT::f64) || 3796 (RegVT == MVT::f64 && ValVT == MVT::i64)) 3797 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue); 3798 else if (ABI.IsO32() && RegVT == MVT::i32 && 3799 ValVT == MVT::f64) { 3800 assert(VA.needsCustom() && "Expected custom argument for f64 split"); 3801 CCValAssign &NextVA = ArgLocs[++i]; 3802 unsigned Reg2 = 3803 addLiveIn(DAG.getMachineFunction(), NextVA.getLocReg(), RC); 3804 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT); 3805 if (!Subtarget.isLittle()) 3806 std::swap(ArgValue, ArgValue2); 3807 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, 3808 ArgValue, ArgValue2); 3809 } 3810 3811 InVals.push_back(ArgValue); 3812 } else { // VA.isRegLoc() 3813 MVT LocVT = VA.getLocVT(); 3814 3815 assert(!VA.needsCustom() && "unexpected custom memory argument"); 3816 3817 // Only arguments pased on the stack should make it here. 3818 assert(VA.isMemLoc()); 3819 3820 // The stack pointer offset is relative to the caller stack frame. 3821 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, 3822 VA.getLocMemOffset(), true); 3823 3824 // Create load nodes to retrieve arguments from the stack 3825 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3826 SDValue ArgValue = DAG.getLoad( 3827 LocVT, DL, Chain, FIN, 3828 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3829 OutChains.push_back(ArgValue.getValue(1)); 3830 3831 ArgValue = 3832 UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG); 3833 3834 InVals.push_back(ArgValue); 3835 } 3836 } 3837 3838 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) { 3839 3840 if (ArgLocs[i].needsCustom()) { 3841 ++i; 3842 continue; 3843 } 3844 3845 // The mips ABIs for returning structs by value requires that we copy 3846 // the sret argument into $v0 for the return. Save the argument into 3847 // a virtual register so that we can access it from the return points. 3848 if (Ins[InsIdx].Flags.isSRet()) { 3849 unsigned Reg = MipsFI->getSRetReturnReg(); 3850 if (!Reg) { 3851 Reg = MF.getRegInfo().createVirtualRegister( 3852 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32)); 3853 MipsFI->setSRetReturnReg(Reg); 3854 } 3855 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]); 3856 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain); 3857 break; 3858 } 3859 } 3860 3861 if (IsVarArg) 3862 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo); 3863 3864 // All stores are grouped in one node to allow the matching between 3865 // the size of Ins and InVals. This only happens when on varg functions 3866 if (!OutChains.empty()) { 3867 OutChains.push_back(Chain); 3868 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 3869 } 3870 3871 return Chain; 3872 } 3873 3874 //===----------------------------------------------------------------------===// 3875 // Return Value Calling Convention Implementation 3876 //===----------------------------------------------------------------------===// 3877 3878 bool 3879 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 3880 MachineFunction &MF, bool IsVarArg, 3881 const SmallVectorImpl<ISD::OutputArg> &Outs, 3882 LLVMContext &Context, const Type *RetTy) const { 3883 SmallVector<CCValAssign, 16> RVLocs; 3884 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 3885 return CCInfo.CheckCallReturn(Outs, RetCC_Mips, RetTy); 3886 } 3887 3888 bool MipsTargetLowering::shouldSignExtendTypeInLibCall(Type *Ty, 3889 bool IsSigned) const { 3890 if ((ABI.IsN32() || ABI.IsN64()) && Ty->isIntegerTy(32)) 3891 return true; 3892 3893 return IsSigned; 3894 } 3895 3896 SDValue 3897 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 3898 const SDLoc &DL, 3899 SelectionDAG &DAG) const { 3900 MachineFunction &MF = DAG.getMachineFunction(); 3901 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); 3902 3903 MipsFI->setISR(); 3904 3905 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps); 3906 } 3907 3908 SDValue 3909 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 3910 bool IsVarArg, 3911 const SmallVectorImpl<ISD::OutputArg> &Outs, 3912 const SmallVectorImpl<SDValue> &OutVals, 3913 const SDLoc &DL, SelectionDAG &DAG) const { 3914 // CCValAssign - represent the assignment of 3915 // the return value to a location 3916 SmallVector<CCValAssign, 16> RVLocs; 3917 MachineFunction &MF = DAG.getMachineFunction(); 3918 3919 // CCState - Info about the registers and stack slot. 3920 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 3921 3922 // Analyze return values. 3923 CCInfo.AnalyzeReturn(Outs, RetCC_Mips); 3924 3925 SDValue Glue; 3926 SmallVector<SDValue, 4> RetOps(1, Chain); 3927 3928 // Copy the result values into the output registers. 3929 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3930 SDValue Val = OutVals[i]; 3931 CCValAssign &VA = RVLocs[i]; 3932 assert(VA.isRegLoc() && "Can only return in registers!"); 3933 bool UseUpperBits = false; 3934 3935 switch (VA.getLocInfo()) { 3936 default: 3937 llvm_unreachable("Unknown loc info!"); 3938 case CCValAssign::Full: 3939 break; 3940 case CCValAssign::BCvt: 3941 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val); 3942 break; 3943 case CCValAssign::AExtUpper: 3944 UseUpperBits = true; 3945 [[fallthrough]]; 3946 case CCValAssign::AExt: 3947 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val); 3948 break; 3949 case CCValAssign::ZExtUpper: 3950 UseUpperBits = true; 3951 [[fallthrough]]; 3952 case CCValAssign::ZExt: 3953 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val); 3954 break; 3955 case CCValAssign::SExtUpper: 3956 UseUpperBits = true; 3957 [[fallthrough]]; 3958 case CCValAssign::SExt: 3959 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val); 3960 break; 3961 } 3962 3963 if (UseUpperBits) { 3964 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits(); 3965 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits(); 3966 Val = DAG.getNode( 3967 ISD::SHL, DL, VA.getLocVT(), Val, 3968 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT())); 3969 } 3970 3971 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 3972 3973 // Guarantee that all emitted copies are stuck together with flags. 3974 Glue = Chain.getValue(1); 3975 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3976 } 3977 3978 // The mips ABIs for returning structs by value requires that we copy 3979 // the sret argument into $v0 for the return. We saved the argument into 3980 // a virtual register in the entry block, so now we copy the value out 3981 // and into $v0. 3982 if (MF.getFunction().hasStructRetAttr()) { 3983 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); 3984 unsigned Reg = MipsFI->getSRetReturnReg(); 3985 3986 if (!Reg) 3987 llvm_unreachable("sret virtual register not created in the entry block"); 3988 SDValue Val = 3989 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout())); 3990 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0; 3991 3992 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Glue); 3993 Glue = Chain.getValue(1); 3994 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout()))); 3995 } 3996 3997 RetOps[0] = Chain; // Update chain. 3998 3999 // Add the glue if we have it. 4000 if (Glue.getNode()) 4001 RetOps.push_back(Glue); 4002 4003 // ISRs must use "eret". 4004 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt")) 4005 return LowerInterruptReturn(RetOps, DL, DAG); 4006 4007 // Standard return on Mips is a "jr $ra" 4008 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps); 4009 } 4010 4011 //===----------------------------------------------------------------------===// 4012 // Mips Inline Assembly Support 4013 //===----------------------------------------------------------------------===// 4014 4015 /// getConstraintType - Given a constraint letter, return the type of 4016 /// constraint it is for this target. 4017 MipsTargetLowering::ConstraintType 4018 MipsTargetLowering::getConstraintType(StringRef Constraint) const { 4019 // Mips specific constraints 4020 // GCC config/mips/constraints.md 4021 // 4022 // 'd' : An address register. Equivalent to r 4023 // unless generating MIPS16 code. 4024 // 'y' : Equivalent to r; retained for 4025 // backwards compatibility. 4026 // 'c' : A register suitable for use in an indirect 4027 // jump. This will always be $25 for -mabicalls. 4028 // 'l' : The lo register. 1 word storage. 4029 // 'x' : The hilo register pair. Double word storage. 4030 if (Constraint.size() == 1) { 4031 switch (Constraint[0]) { 4032 default : break; 4033 case 'd': 4034 case 'y': 4035 case 'f': 4036 case 'c': 4037 case 'l': 4038 case 'x': 4039 return C_RegisterClass; 4040 case 'R': 4041 return C_Memory; 4042 } 4043 } 4044 4045 if (Constraint == "ZC") 4046 return C_Memory; 4047 4048 return TargetLowering::getConstraintType(Constraint); 4049 } 4050 4051 /// Examine constraint type and operand type and determine a weight value. 4052 /// This object must already have been set up with the operand type 4053 /// and the current alternative constraint selected. 4054 TargetLowering::ConstraintWeight 4055 MipsTargetLowering::getSingleConstraintMatchWeight( 4056 AsmOperandInfo &info, const char *constraint) const { 4057 ConstraintWeight weight = CW_Invalid; 4058 Value *CallOperandVal = info.CallOperandVal; 4059 // If we don't have a value, we can't do a match, 4060 // but allow it at the lowest weight. 4061 if (!CallOperandVal) 4062 return CW_Default; 4063 Type *type = CallOperandVal->getType(); 4064 // Look at the constraint type. 4065 switch (*constraint) { 4066 default: 4067 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 4068 break; 4069 case 'd': 4070 case 'y': 4071 if (type->isIntegerTy()) 4072 weight = CW_Register; 4073 break; 4074 case 'f': // FPU or MSA register 4075 if (Subtarget.hasMSA() && type->isVectorTy() && 4076 type->getPrimitiveSizeInBits().getFixedValue() == 128) 4077 weight = CW_Register; 4078 else if (type->isFloatTy()) 4079 weight = CW_Register; 4080 break; 4081 case 'c': // $25 for indirect jumps 4082 case 'l': // lo register 4083 case 'x': // hilo register pair 4084 if (type->isIntegerTy()) 4085 weight = CW_SpecificReg; 4086 break; 4087 case 'I': // signed 16 bit immediate 4088 case 'J': // integer zero 4089 case 'K': // unsigned 16 bit immediate 4090 case 'L': // signed 32 bit immediate where lower 16 bits are 0 4091 case 'N': // immediate in the range of -65535 to -1 (inclusive) 4092 case 'O': // signed 15 bit immediate (+- 16383) 4093 case 'P': // immediate in the range of 65535 to 1 (inclusive) 4094 if (isa<ConstantInt>(CallOperandVal)) 4095 weight = CW_Constant; 4096 break; 4097 case 'R': 4098 weight = CW_Memory; 4099 break; 4100 } 4101 return weight; 4102 } 4103 4104 /// This is a helper function to parse a physical register string and split it 4105 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag 4106 /// that is returned indicates whether parsing was successful. The second flag 4107 /// is true if the numeric part exists. 4108 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix, 4109 unsigned long long &Reg) { 4110 if (C.front() != '{' || C.back() != '}') 4111 return std::make_pair(false, false); 4112 4113 // Search for the first numeric character. 4114 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1; 4115 I = std::find_if(B, E, isdigit); 4116 4117 Prefix = StringRef(B, I - B); 4118 4119 // The second flag is set to false if no numeric characters were found. 4120 if (I == E) 4121 return std::make_pair(true, false); 4122 4123 // Parse the numeric characters. 4124 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg), 4125 true); 4126 } 4127 4128 EVT MipsTargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT, 4129 ISD::NodeType) const { 4130 bool Cond = !Subtarget.isABI_O32() && VT.getSizeInBits() == 32; 4131 EVT MinVT = getRegisterType(Cond ? MVT::i64 : MVT::i32); 4132 return VT.bitsLT(MinVT) ? MinVT : VT; 4133 } 4134 4135 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering:: 4136 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const { 4137 const TargetRegisterInfo *TRI = 4138 Subtarget.getRegisterInfo(); 4139 const TargetRegisterClass *RC; 4140 StringRef Prefix; 4141 unsigned long long Reg; 4142 4143 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg); 4144 4145 if (!R.first) 4146 return std::make_pair(0U, nullptr); 4147 4148 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo. 4149 // No numeric characters follow "hi" or "lo". 4150 if (R.second) 4151 return std::make_pair(0U, nullptr); 4152 4153 RC = TRI->getRegClass(Prefix == "hi" ? 4154 Mips::HI32RegClassID : Mips::LO32RegClassID); 4155 return std::make_pair(*(RC->begin()), RC); 4156 } else if (Prefix.starts_with("$msa")) { 4157 // Parse $msa(ir|csr|access|save|modify|request|map|unmap) 4158 4159 // No numeric characters follow the name. 4160 if (R.second) 4161 return std::make_pair(0U, nullptr); 4162 4163 Reg = StringSwitch<unsigned long long>(Prefix) 4164 .Case("$msair", Mips::MSAIR) 4165 .Case("$msacsr", Mips::MSACSR) 4166 .Case("$msaaccess", Mips::MSAAccess) 4167 .Case("$msasave", Mips::MSASave) 4168 .Case("$msamodify", Mips::MSAModify) 4169 .Case("$msarequest", Mips::MSARequest) 4170 .Case("$msamap", Mips::MSAMap) 4171 .Case("$msaunmap", Mips::MSAUnmap) 4172 .Default(0); 4173 4174 if (!Reg) 4175 return std::make_pair(0U, nullptr); 4176 4177 RC = TRI->getRegClass(Mips::MSACtrlRegClassID); 4178 return std::make_pair(Reg, RC); 4179 } 4180 4181 if (!R.second) 4182 return std::make_pair(0U, nullptr); 4183 4184 if (Prefix == "$f") { // Parse $f0-$f31. 4185 // If the size of FP registers is 64-bit or Reg is an even number, select 4186 // the 64-bit register class. Otherwise, select the 32-bit register class. 4187 if (VT == MVT::Other) 4188 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32; 4189 4190 RC = getRegClassFor(VT); 4191 4192 if (RC == &Mips::AFGR64RegClass) { 4193 assert(Reg % 2 == 0); 4194 Reg >>= 1; 4195 } 4196 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7. 4197 RC = TRI->getRegClass(Mips::FCCRegClassID); 4198 else if (Prefix == "$w") { // Parse $w0-$w31. 4199 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT); 4200 } else { // Parse $0-$31. 4201 assert(Prefix == "$"); 4202 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT); 4203 } 4204 4205 assert(Reg < RC->getNumRegs()); 4206 return std::make_pair(*(RC->begin() + Reg), RC); 4207 } 4208 4209 /// Given a register class constraint, like 'r', if this corresponds directly 4210 /// to an LLVM register class, return a register of 0 and the register class 4211 /// pointer. 4212 std::pair<unsigned, const TargetRegisterClass *> 4213 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 4214 StringRef Constraint, 4215 MVT VT) const { 4216 if (Constraint.size() == 1) { 4217 switch (Constraint[0]) { 4218 case 'd': // Address register. Same as 'r' unless generating MIPS16 code. 4219 case 'y': // Same as 'r'. Exists for compatibility. 4220 case 'r': 4221 if ((VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8 || 4222 VT == MVT::i1) || 4223 (VT == MVT::f32 && Subtarget.useSoftFloat())) { 4224 if (Subtarget.inMips16Mode()) 4225 return std::make_pair(0U, &Mips::CPU16RegsRegClass); 4226 return std::make_pair(0U, &Mips::GPR32RegClass); 4227 } 4228 if ((VT == MVT::i64 || (VT == MVT::f64 && Subtarget.useSoftFloat())) && 4229 !Subtarget.isGP64bit()) 4230 return std::make_pair(0U, &Mips::GPR32RegClass); 4231 if ((VT == MVT::i64 || (VT == MVT::f64 && Subtarget.useSoftFloat())) && 4232 Subtarget.isGP64bit()) 4233 return std::make_pair(0U, &Mips::GPR64RegClass); 4234 // This will generate an error message 4235 return std::make_pair(0U, nullptr); 4236 case 'f': // FPU or MSA register 4237 if (VT == MVT::v16i8) 4238 return std::make_pair(0U, &Mips::MSA128BRegClass); 4239 else if (VT == MVT::v8i16 || VT == MVT::v8f16) 4240 return std::make_pair(0U, &Mips::MSA128HRegClass); 4241 else if (VT == MVT::v4i32 || VT == MVT::v4f32) 4242 return std::make_pair(0U, &Mips::MSA128WRegClass); 4243 else if (VT == MVT::v2i64 || VT == MVT::v2f64) 4244 return std::make_pair(0U, &Mips::MSA128DRegClass); 4245 else if (VT == MVT::f32) 4246 return std::make_pair(0U, &Mips::FGR32RegClass); 4247 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) { 4248 if (Subtarget.isFP64bit()) 4249 return std::make_pair(0U, &Mips::FGR64RegClass); 4250 return std::make_pair(0U, &Mips::AFGR64RegClass); 4251 } 4252 break; 4253 case 'c': // register suitable for indirect jump 4254 if (VT == MVT::i32) 4255 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass); 4256 if (VT == MVT::i64) 4257 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass); 4258 // This will generate an error message 4259 return std::make_pair(0U, nullptr); 4260 case 'l': // use the `lo` register to store values 4261 // that are no bigger than a word 4262 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) 4263 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass); 4264 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass); 4265 case 'x': // use the concatenated `hi` and `lo` registers 4266 // to store doubleword values 4267 // Fixme: Not triggering the use of both hi and low 4268 // This will generate an error message 4269 return std::make_pair(0U, nullptr); 4270 } 4271 } 4272 4273 if (!Constraint.empty()) { 4274 std::pair<unsigned, const TargetRegisterClass *> R; 4275 R = parseRegForInlineAsmConstraint(Constraint, VT); 4276 4277 if (R.second) 4278 return R; 4279 } 4280 4281 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 4282 } 4283 4284 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 4285 /// vector. If it is invalid, don't add anything to Ops. 4286 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 4287 StringRef Constraint, 4288 std::vector<SDValue> &Ops, 4289 SelectionDAG &DAG) const { 4290 SDLoc DL(Op); 4291 SDValue Result; 4292 4293 // Only support length 1 constraints for now. 4294 if (Constraint.size() > 1) 4295 return; 4296 4297 char ConstraintLetter = Constraint[0]; 4298 switch (ConstraintLetter) { 4299 default: break; // This will fall through to the generic implementation 4300 case 'I': // Signed 16 bit constant 4301 // If this fails, the parent routine will give an error 4302 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4303 EVT Type = Op.getValueType(); 4304 int64_t Val = C->getSExtValue(); 4305 if (isInt<16>(Val)) { 4306 Result = DAG.getSignedTargetConstant(Val, DL, Type); 4307 break; 4308 } 4309 } 4310 return; 4311 case 'J': // integer zero 4312 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4313 EVT Type = Op.getValueType(); 4314 int64_t Val = C->getZExtValue(); 4315 if (Val == 0) { 4316 Result = DAG.getTargetConstant(0, DL, Type); 4317 break; 4318 } 4319 } 4320 return; 4321 case 'K': // unsigned 16 bit immediate 4322 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4323 EVT Type = Op.getValueType(); 4324 uint64_t Val = (uint64_t)C->getZExtValue(); 4325 if (isUInt<16>(Val)) { 4326 Result = DAG.getTargetConstant(Val, DL, Type); 4327 break; 4328 } 4329 } 4330 return; 4331 case 'L': // signed 32 bit immediate where lower 16 bits are 0 4332 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4333 EVT Type = Op.getValueType(); 4334 int64_t Val = C->getSExtValue(); 4335 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){ 4336 Result = DAG.getSignedTargetConstant(Val, DL, Type); 4337 break; 4338 } 4339 } 4340 return; 4341 case 'N': // immediate in the range of -65535 to -1 (inclusive) 4342 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4343 EVT Type = Op.getValueType(); 4344 int64_t Val = C->getSExtValue(); 4345 if ((Val >= -65535) && (Val <= -1)) { 4346 Result = DAG.getSignedTargetConstant(Val, DL, Type); 4347 break; 4348 } 4349 } 4350 return; 4351 case 'O': // signed 15 bit immediate 4352 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4353 EVT Type = Op.getValueType(); 4354 int64_t Val = C->getSExtValue(); 4355 if ((isInt<15>(Val))) { 4356 Result = DAG.getSignedTargetConstant(Val, DL, Type); 4357 break; 4358 } 4359 } 4360 return; 4361 case 'P': // immediate in the range of 1 to 65535 (inclusive) 4362 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4363 EVT Type = Op.getValueType(); 4364 int64_t Val = C->getSExtValue(); 4365 if ((Val <= 65535) && (Val >= 1)) { 4366 Result = DAG.getTargetConstant(Val, DL, Type); 4367 break; 4368 } 4369 } 4370 return; 4371 } 4372 4373 if (Result.getNode()) { 4374 Ops.push_back(Result); 4375 return; 4376 } 4377 4378 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 4379 } 4380 4381 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL, 4382 const AddrMode &AM, Type *Ty, 4383 unsigned AS, 4384 Instruction *I) const { 4385 // No global is ever allowed as a base. 4386 if (AM.BaseGV) 4387 return false; 4388 4389 switch (AM.Scale) { 4390 case 0: // "r+i" or just "i", depending on HasBaseReg. 4391 break; 4392 case 1: 4393 if (!AM.HasBaseReg) // allow "r+i". 4394 break; 4395 return false; // disallow "r+r" or "r+r+i". 4396 default: 4397 return false; 4398 } 4399 4400 return true; 4401 } 4402 4403 bool 4404 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4405 // The Mips target isn't yet aware of offsets. 4406 return false; 4407 } 4408 4409 EVT MipsTargetLowering::getOptimalMemOpType( 4410 const MemOp &Op, const AttributeList &FuncAttributes) const { 4411 if (Subtarget.hasMips64()) 4412 return MVT::i64; 4413 4414 return MVT::i32; 4415 } 4416 4417 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 4418 bool ForCodeSize) const { 4419 if (VT != MVT::f32 && VT != MVT::f64) 4420 return false; 4421 if (Imm.isNegZero()) 4422 return false; 4423 return Imm.isZero(); 4424 } 4425 4426 unsigned MipsTargetLowering::getJumpTableEncoding() const { 4427 4428 // FIXME: For space reasons this should be: EK_GPRel32BlockAddress. 4429 if (ABI.IsN64() && isPositionIndependent()) 4430 return MachineJumpTableInfo::EK_GPRel64BlockAddress; 4431 4432 return TargetLowering::getJumpTableEncoding(); 4433 } 4434 4435 bool MipsTargetLowering::useSoftFloat() const { 4436 return Subtarget.useSoftFloat(); 4437 } 4438 4439 void MipsTargetLowering::copyByValRegs( 4440 SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains, 4441 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags, 4442 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg, 4443 unsigned FirstReg, unsigned LastReg, const CCValAssign &VA, 4444 MipsCCState &State) const { 4445 MachineFunction &MF = DAG.getMachineFunction(); 4446 MachineFrameInfo &MFI = MF.getFrameInfo(); 4447 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes(); 4448 unsigned NumRegs = LastReg - FirstReg; 4449 unsigned RegAreaSize = NumRegs * GPRSizeInBytes; 4450 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize); 4451 int FrameObjOffset; 4452 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs(); 4453 4454 if (RegAreaSize) 4455 FrameObjOffset = 4456 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) - 4457 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes); 4458 else 4459 FrameObjOffset = VA.getLocMemOffset(); 4460 4461 // Create frame object. 4462 EVT PtrTy = getPointerTy(DAG.getDataLayout()); 4463 // Make the fixed object stored to mutable so that the load instructions 4464 // referencing it have their memory dependencies added. 4465 // Set the frame object as isAliased which clears the underlying objects 4466 // vector in ScheduleDAGInstrs::buildSchedGraph() resulting in addition of all 4467 // stores as dependencies for loads referencing this fixed object. 4468 int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, false, true); 4469 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 4470 InVals.push_back(FIN); 4471 4472 if (!NumRegs) 4473 return; 4474 4475 // Copy arg registers. 4476 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8); 4477 const TargetRegisterClass *RC = getRegClassFor(RegTy); 4478 4479 for (unsigned I = 0; I < NumRegs; ++I) { 4480 unsigned ArgReg = ByValArgRegs[FirstReg + I]; 4481 unsigned VReg = addLiveIn(MF, ArgReg, RC); 4482 unsigned Offset = I * GPRSizeInBytes; 4483 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN, 4484 DAG.getConstant(Offset, DL, PtrTy)); 4485 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy), 4486 StorePtr, MachinePointerInfo(FuncArg, Offset)); 4487 OutChains.push_back(Store); 4488 } 4489 } 4490 4491 // Copy byVal arg to registers and stack. 4492 void MipsTargetLowering::passByValArg( 4493 SDValue Chain, const SDLoc &DL, 4494 std::deque<std::pair<unsigned, SDValue>> &RegsToPass, 4495 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr, 4496 MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg, 4497 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle, 4498 const CCValAssign &VA) const { 4499 unsigned ByValSizeInBytes = Flags.getByValSize(); 4500 unsigned OffsetInBytes = 0; // From beginning of struct 4501 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes(); 4502 Align Alignment = 4503 std::min(Flags.getNonZeroByValAlign(), Align(RegSizeInBytes)); 4504 EVT PtrTy = getPointerTy(DAG.getDataLayout()), 4505 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8); 4506 unsigned NumRegs = LastReg - FirstReg; 4507 4508 if (NumRegs) { 4509 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs(); 4510 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes); 4511 unsigned I = 0; 4512 4513 // Copy words to registers. 4514 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) { 4515 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg, 4516 DAG.getConstant(OffsetInBytes, DL, PtrTy)); 4517 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr, 4518 MachinePointerInfo(), Alignment); 4519 MemOpChains.push_back(LoadVal.getValue(1)); 4520 unsigned ArgReg = ArgRegs[FirstReg + I]; 4521 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal)); 4522 } 4523 4524 // Return if the struct has been fully copied. 4525 if (ByValSizeInBytes == OffsetInBytes) 4526 return; 4527 4528 // Copy the remainder of the byval argument with sub-word loads and shifts. 4529 if (LeftoverBytes) { 4530 SDValue Val; 4531 4532 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0; 4533 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) { 4534 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes; 4535 4536 if (RemainingSizeInBytes < LoadSizeInBytes) 4537 continue; 4538 4539 // Load subword. 4540 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg, 4541 DAG.getConstant(OffsetInBytes, DL, 4542 PtrTy)); 4543 SDValue LoadVal = DAG.getExtLoad( 4544 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(), 4545 MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment); 4546 MemOpChains.push_back(LoadVal.getValue(1)); 4547 4548 // Shift the loaded value. 4549 unsigned Shamt; 4550 4551 if (isLittle) 4552 Shamt = TotalBytesLoaded * 8; 4553 else 4554 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8; 4555 4556 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal, 4557 DAG.getConstant(Shamt, DL, MVT::i32)); 4558 4559 if (Val.getNode()) 4560 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift); 4561 else 4562 Val = Shift; 4563 4564 OffsetInBytes += LoadSizeInBytes; 4565 TotalBytesLoaded += LoadSizeInBytes; 4566 Alignment = std::min(Alignment, Align(LoadSizeInBytes)); 4567 } 4568 4569 unsigned ArgReg = ArgRegs[FirstReg + I]; 4570 RegsToPass.push_back(std::make_pair(ArgReg, Val)); 4571 return; 4572 } 4573 } 4574 4575 // Copy remainder of byval arg to it with memcpy. 4576 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes; 4577 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg, 4578 DAG.getConstant(OffsetInBytes, DL, PtrTy)); 4579 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr, 4580 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 4581 Chain = DAG.getMemcpy( 4582 Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, DL, PtrTy), 4583 Align(Alignment), /*isVolatile=*/false, /*AlwaysInline=*/false, 4584 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(), MachinePointerInfo()); 4585 MemOpChains.push_back(Chain); 4586 } 4587 4588 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains, 4589 SDValue Chain, const SDLoc &DL, 4590 SelectionDAG &DAG, 4591 CCState &State) const { 4592 ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs(); 4593 unsigned Idx = State.getFirstUnallocated(ArgRegs); 4594 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes(); 4595 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8); 4596 const TargetRegisterClass *RC = getRegClassFor(RegTy); 4597 MachineFunction &MF = DAG.getMachineFunction(); 4598 MachineFrameInfo &MFI = MF.getFrameInfo(); 4599 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); 4600 4601 // Offset of the first variable argument from stack pointer. 4602 int VaArgOffset; 4603 4604 if (ArgRegs.size() == Idx) 4605 VaArgOffset = alignTo(State.getStackSize(), RegSizeInBytes); 4606 else { 4607 VaArgOffset = 4608 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) - 4609 (int)(RegSizeInBytes * (ArgRegs.size() - Idx)); 4610 } 4611 4612 // Record the frame index of the first variable argument 4613 // which is a value necessary to VASTART. 4614 int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true); 4615 MipsFI->setVarArgsFrameIndex(FI); 4616 4617 // Copy the integer registers that have not been used for argument passing 4618 // to the argument register save area. For O32, the save area is allocated 4619 // in the caller's stack frame, while for N32/64, it is allocated in the 4620 // callee's stack frame. 4621 for (unsigned I = Idx; I < ArgRegs.size(); 4622 ++I, VaArgOffset += RegSizeInBytes) { 4623 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC); 4624 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy); 4625 FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true); 4626 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 4627 SDValue Store = 4628 DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo()); 4629 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue( 4630 (Value *)nullptr); 4631 OutChains.push_back(Store); 4632 } 4633 } 4634 4635 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size, 4636 Align Alignment) const { 4637 const TargetFrameLowering *TFL = Subtarget.getFrameLowering(); 4638 4639 assert(Size && "Byval argument's size shouldn't be 0."); 4640 4641 Alignment = std::min(Alignment, TFL->getStackAlign()); 4642 4643 unsigned FirstReg = 0; 4644 unsigned NumRegs = 0; 4645 4646 if (State->getCallingConv() != CallingConv::Fast) { 4647 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes(); 4648 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs(); 4649 // FIXME: The O32 case actually describes no shadow registers. 4650 const MCPhysReg *ShadowRegs = 4651 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs; 4652 4653 // We used to check the size as well but we can't do that anymore since 4654 // CCState::HandleByVal() rounds up the size after calling this function. 4655 assert( 4656 Alignment >= Align(RegSizeInBytes) && 4657 "Byval argument's alignment should be a multiple of RegSizeInBytes."); 4658 4659 FirstReg = State->getFirstUnallocated(IntArgRegs); 4660 4661 // If Alignment > RegSizeInBytes, the first arg register must be even. 4662 // FIXME: This condition happens to do the right thing but it's not the 4663 // right way to test it. We want to check that the stack frame offset 4664 // of the register is aligned. 4665 if ((Alignment > RegSizeInBytes) && (FirstReg % 2)) { 4666 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]); 4667 ++FirstReg; 4668 } 4669 4670 // Mark the registers allocated. 4671 Size = alignTo(Size, RegSizeInBytes); 4672 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size()); 4673 Size -= RegSizeInBytes, ++I, ++NumRegs) 4674 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]); 4675 } 4676 4677 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs); 4678 } 4679 4680 MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI, 4681 MachineBasicBlock *BB, 4682 bool isFPCmp, 4683 unsigned Opc) const { 4684 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) && 4685 "Subtarget already supports SELECT nodes with the use of" 4686 "conditional-move instructions."); 4687 4688 const TargetInstrInfo *TII = 4689 Subtarget.getInstrInfo(); 4690 DebugLoc DL = MI.getDebugLoc(); 4691 4692 // To "insert" a SELECT instruction, we actually have to insert the 4693 // diamond control-flow pattern. The incoming instruction knows the 4694 // destination vreg to set, the condition code register to branch on, the 4695 // true/false values to select between, and a branch opcode to use. 4696 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 4697 MachineFunction::iterator It = ++BB->getIterator(); 4698 4699 // thisMBB: 4700 // ... 4701 // TrueVal = ... 4702 // setcc r1, r2, r3 4703 // bNE r1, r0, copy1MBB 4704 // fallthrough --> copy0MBB 4705 MachineBasicBlock *thisMBB = BB; 4706 MachineFunction *F = BB->getParent(); 4707 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 4708 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 4709 F->insert(It, copy0MBB); 4710 F->insert(It, sinkMBB); 4711 4712 // Transfer the remainder of BB and its successor edges to sinkMBB. 4713 sinkMBB->splice(sinkMBB->begin(), BB, 4714 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 4715 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 4716 4717 // Next, add the true and fallthrough blocks as its successors. 4718 BB->addSuccessor(copy0MBB); 4719 BB->addSuccessor(sinkMBB); 4720 4721 if (isFPCmp) { 4722 // bc1[tf] cc, sinkMBB 4723 BuildMI(BB, DL, TII->get(Opc)) 4724 .addReg(MI.getOperand(1).getReg()) 4725 .addMBB(sinkMBB); 4726 } else { 4727 // bne rs, $0, sinkMBB 4728 BuildMI(BB, DL, TII->get(Opc)) 4729 .addReg(MI.getOperand(1).getReg()) 4730 .addReg(Mips::ZERO) 4731 .addMBB(sinkMBB); 4732 } 4733 4734 // copy0MBB: 4735 // %FalseValue = ... 4736 // # fallthrough to sinkMBB 4737 BB = copy0MBB; 4738 4739 // Update machine-CFG edges 4740 BB->addSuccessor(sinkMBB); 4741 4742 // sinkMBB: 4743 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ] 4744 // ... 4745 BB = sinkMBB; 4746 4747 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg()) 4748 .addReg(MI.getOperand(2).getReg()) 4749 .addMBB(thisMBB) 4750 .addReg(MI.getOperand(3).getReg()) 4751 .addMBB(copy0MBB); 4752 4753 MI.eraseFromParent(); // The pseudo instruction is gone now. 4754 4755 return BB; 4756 } 4757 4758 MachineBasicBlock * 4759 MipsTargetLowering::emitPseudoD_SELECT(MachineInstr &MI, 4760 MachineBasicBlock *BB) const { 4761 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) && 4762 "Subtarget already supports SELECT nodes with the use of" 4763 "conditional-move instructions."); 4764 4765 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 4766 DebugLoc DL = MI.getDebugLoc(); 4767 4768 // D_SELECT substitutes two SELECT nodes that goes one after another and 4769 // have the same condition operand. On machines which don't have 4770 // conditional-move instruction, it reduces unnecessary branch instructions 4771 // which are result of using two diamond patterns that are result of two 4772 // SELECT pseudo instructions. 4773 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 4774 MachineFunction::iterator It = ++BB->getIterator(); 4775 4776 // thisMBB: 4777 // ... 4778 // TrueVal = ... 4779 // setcc r1, r2, r3 4780 // bNE r1, r0, copy1MBB 4781 // fallthrough --> copy0MBB 4782 MachineBasicBlock *thisMBB = BB; 4783 MachineFunction *F = BB->getParent(); 4784 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 4785 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 4786 F->insert(It, copy0MBB); 4787 F->insert(It, sinkMBB); 4788 4789 // Transfer the remainder of BB and its successor edges to sinkMBB. 4790 sinkMBB->splice(sinkMBB->begin(), BB, 4791 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 4792 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 4793 4794 // Next, add the true and fallthrough blocks as its successors. 4795 BB->addSuccessor(copy0MBB); 4796 BB->addSuccessor(sinkMBB); 4797 4798 // bne rs, $0, sinkMBB 4799 BuildMI(BB, DL, TII->get(Mips::BNE)) 4800 .addReg(MI.getOperand(2).getReg()) 4801 .addReg(Mips::ZERO) 4802 .addMBB(sinkMBB); 4803 4804 // copy0MBB: 4805 // %FalseValue = ... 4806 // # fallthrough to sinkMBB 4807 BB = copy0MBB; 4808 4809 // Update machine-CFG edges 4810 BB->addSuccessor(sinkMBB); 4811 4812 // sinkMBB: 4813 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ] 4814 // ... 4815 BB = sinkMBB; 4816 4817 // Use two PHI nodes to select two reults 4818 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg()) 4819 .addReg(MI.getOperand(3).getReg()) 4820 .addMBB(thisMBB) 4821 .addReg(MI.getOperand(5).getReg()) 4822 .addMBB(copy0MBB); 4823 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(1).getReg()) 4824 .addReg(MI.getOperand(4).getReg()) 4825 .addMBB(thisMBB) 4826 .addReg(MI.getOperand(6).getReg()) 4827 .addMBB(copy0MBB); 4828 4829 MI.eraseFromParent(); // The pseudo instruction is gone now. 4830 4831 return BB; 4832 } 4833 4834 // FIXME? Maybe this could be a TableGen attribute on some registers and 4835 // this table could be generated automatically from RegInfo. 4836 Register 4837 MipsTargetLowering::getRegisterByName(const char *RegName, LLT VT, 4838 const MachineFunction &MF) const { 4839 // The Linux kernel uses $28 and sp. 4840 if (Subtarget.isGP64bit()) { 4841 Register Reg = StringSwitch<Register>(RegName) 4842 .Case("$28", Mips::GP_64) 4843 .Case("sp", Mips::SP_64) 4844 .Default(Register()); 4845 if (Reg) 4846 return Reg; 4847 } else { 4848 Register Reg = StringSwitch<Register>(RegName) 4849 .Case("$28", Mips::GP) 4850 .Case("sp", Mips::SP) 4851 .Default(Register()); 4852 if (Reg) 4853 return Reg; 4854 } 4855 report_fatal_error("Invalid register name global variable"); 4856 } 4857 4858 MachineBasicBlock *MipsTargetLowering::emitLDR_W(MachineInstr &MI, 4859 MachineBasicBlock *BB) const { 4860 MachineFunction *MF = BB->getParent(); 4861 MachineRegisterInfo &MRI = MF->getRegInfo(); 4862 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 4863 const bool IsLittle = Subtarget.isLittle(); 4864 DebugLoc DL = MI.getDebugLoc(); 4865 4866 Register Dest = MI.getOperand(0).getReg(); 4867 Register Address = MI.getOperand(1).getReg(); 4868 unsigned Imm = MI.getOperand(2).getImm(); 4869 4870 MachineBasicBlock::iterator I(MI); 4871 4872 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) { 4873 // Mips release 6 can load from adress that is not naturally-aligned. 4874 Register Temp = MRI.createVirtualRegister(&Mips::GPR32RegClass); 4875 BuildMI(*BB, I, DL, TII->get(Mips::LW)) 4876 .addDef(Temp) 4877 .addUse(Address) 4878 .addImm(Imm); 4879 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Dest).addUse(Temp); 4880 } else { 4881 // Mips release 5 needs to use instructions that can load from an unaligned 4882 // memory address. 4883 Register LoadHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass); 4884 Register LoadFull = MRI.createVirtualRegister(&Mips::GPR32RegClass); 4885 Register Undef = MRI.createVirtualRegister(&Mips::GPR32RegClass); 4886 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(Undef); 4887 BuildMI(*BB, I, DL, TII->get(Mips::LWR)) 4888 .addDef(LoadHalf) 4889 .addUse(Address) 4890 .addImm(Imm + (IsLittle ? 0 : 3)) 4891 .addUse(Undef); 4892 BuildMI(*BB, I, DL, TII->get(Mips::LWL)) 4893 .addDef(LoadFull) 4894 .addUse(Address) 4895 .addImm(Imm + (IsLittle ? 3 : 0)) 4896 .addUse(LoadHalf); 4897 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Dest).addUse(LoadFull); 4898 } 4899 4900 MI.eraseFromParent(); 4901 return BB; 4902 } 4903 4904 MachineBasicBlock *MipsTargetLowering::emitLDR_D(MachineInstr &MI, 4905 MachineBasicBlock *BB) const { 4906 MachineFunction *MF = BB->getParent(); 4907 MachineRegisterInfo &MRI = MF->getRegInfo(); 4908 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 4909 const bool IsLittle = Subtarget.isLittle(); 4910 DebugLoc DL = MI.getDebugLoc(); 4911 4912 Register Dest = MI.getOperand(0).getReg(); 4913 Register Address = MI.getOperand(1).getReg(); 4914 unsigned Imm = MI.getOperand(2).getImm(); 4915 4916 MachineBasicBlock::iterator I(MI); 4917 4918 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) { 4919 // Mips release 6 can load from adress that is not naturally-aligned. 4920 if (Subtarget.isGP64bit()) { 4921 Register Temp = MRI.createVirtualRegister(&Mips::GPR64RegClass); 4922 BuildMI(*BB, I, DL, TII->get(Mips::LD)) 4923 .addDef(Temp) 4924 .addUse(Address) 4925 .addImm(Imm); 4926 BuildMI(*BB, I, DL, TII->get(Mips::FILL_D)).addDef(Dest).addUse(Temp); 4927 } else { 4928 Register Wtemp = MRI.createVirtualRegister(&Mips::MSA128WRegClass); 4929 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass); 4930 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass); 4931 BuildMI(*BB, I, DL, TII->get(Mips::LW)) 4932 .addDef(Lo) 4933 .addUse(Address) 4934 .addImm(Imm + (IsLittle ? 0 : 4)); 4935 BuildMI(*BB, I, DL, TII->get(Mips::LW)) 4936 .addDef(Hi) 4937 .addUse(Address) 4938 .addImm(Imm + (IsLittle ? 4 : 0)); 4939 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Wtemp).addUse(Lo); 4940 BuildMI(*BB, I, DL, TII->get(Mips::INSERT_W), Dest) 4941 .addUse(Wtemp) 4942 .addUse(Hi) 4943 .addImm(1); 4944 } 4945 } else { 4946 // Mips release 5 needs to use instructions that can load from an unaligned 4947 // memory address. 4948 Register LoHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass); 4949 Register LoFull = MRI.createVirtualRegister(&Mips::GPR32RegClass); 4950 Register LoUndef = MRI.createVirtualRegister(&Mips::GPR32RegClass); 4951 Register HiHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass); 4952 Register HiFull = MRI.createVirtualRegister(&Mips::GPR32RegClass); 4953 Register HiUndef = MRI.createVirtualRegister(&Mips::GPR32RegClass); 4954 Register Wtemp = MRI.createVirtualRegister(&Mips::MSA128WRegClass); 4955 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(LoUndef); 4956 BuildMI(*BB, I, DL, TII->get(Mips::LWR)) 4957 .addDef(LoHalf) 4958 .addUse(Address) 4959 .addImm(Imm + (IsLittle ? 0 : 7)) 4960 .addUse(LoUndef); 4961 BuildMI(*BB, I, DL, TII->get(Mips::LWL)) 4962 .addDef(LoFull) 4963 .addUse(Address) 4964 .addImm(Imm + (IsLittle ? 3 : 4)) 4965 .addUse(LoHalf); 4966 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(HiUndef); 4967 BuildMI(*BB, I, DL, TII->get(Mips::LWR)) 4968 .addDef(HiHalf) 4969 .addUse(Address) 4970 .addImm(Imm + (IsLittle ? 4 : 3)) 4971 .addUse(HiUndef); 4972 BuildMI(*BB, I, DL, TII->get(Mips::LWL)) 4973 .addDef(HiFull) 4974 .addUse(Address) 4975 .addImm(Imm + (IsLittle ? 7 : 0)) 4976 .addUse(HiHalf); 4977 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Wtemp).addUse(LoFull); 4978 BuildMI(*BB, I, DL, TII->get(Mips::INSERT_W), Dest) 4979 .addUse(Wtemp) 4980 .addUse(HiFull) 4981 .addImm(1); 4982 } 4983 4984 MI.eraseFromParent(); 4985 return BB; 4986 } 4987 4988 MachineBasicBlock *MipsTargetLowering::emitSTR_W(MachineInstr &MI, 4989 MachineBasicBlock *BB) const { 4990 MachineFunction *MF = BB->getParent(); 4991 MachineRegisterInfo &MRI = MF->getRegInfo(); 4992 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 4993 const bool IsLittle = Subtarget.isLittle(); 4994 DebugLoc DL = MI.getDebugLoc(); 4995 4996 Register StoreVal = MI.getOperand(0).getReg(); 4997 Register Address = MI.getOperand(1).getReg(); 4998 unsigned Imm = MI.getOperand(2).getImm(); 4999 5000 MachineBasicBlock::iterator I(MI); 5001 5002 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) { 5003 // Mips release 6 can store to adress that is not naturally-aligned. 5004 Register BitcastW = MRI.createVirtualRegister(&Mips::MSA128WRegClass); 5005 Register Tmp = MRI.createVirtualRegister(&Mips::GPR32RegClass); 5006 BuildMI(*BB, I, DL, TII->get(Mips::COPY)).addDef(BitcastW).addUse(StoreVal); 5007 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W)) 5008 .addDef(Tmp) 5009 .addUse(BitcastW) 5010 .addImm(0); 5011 BuildMI(*BB, I, DL, TII->get(Mips::SW)) 5012 .addUse(Tmp) 5013 .addUse(Address) 5014 .addImm(Imm); 5015 } else { 5016 // Mips release 5 needs to use instructions that can store to an unaligned 5017 // memory address. 5018 Register Tmp = MRI.createVirtualRegister(&Mips::GPR32RegClass); 5019 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W)) 5020 .addDef(Tmp) 5021 .addUse(StoreVal) 5022 .addImm(0); 5023 BuildMI(*BB, I, DL, TII->get(Mips::SWR)) 5024 .addUse(Tmp) 5025 .addUse(Address) 5026 .addImm(Imm + (IsLittle ? 0 : 3)); 5027 BuildMI(*BB, I, DL, TII->get(Mips::SWL)) 5028 .addUse(Tmp) 5029 .addUse(Address) 5030 .addImm(Imm + (IsLittle ? 3 : 0)); 5031 } 5032 5033 MI.eraseFromParent(); 5034 5035 return BB; 5036 } 5037 5038 MachineBasicBlock *MipsTargetLowering::emitSTR_D(MachineInstr &MI, 5039 MachineBasicBlock *BB) const { 5040 MachineFunction *MF = BB->getParent(); 5041 MachineRegisterInfo &MRI = MF->getRegInfo(); 5042 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 5043 const bool IsLittle = Subtarget.isLittle(); 5044 DebugLoc DL = MI.getDebugLoc(); 5045 5046 Register StoreVal = MI.getOperand(0).getReg(); 5047 Register Address = MI.getOperand(1).getReg(); 5048 unsigned Imm = MI.getOperand(2).getImm(); 5049 5050 MachineBasicBlock::iterator I(MI); 5051 5052 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) { 5053 // Mips release 6 can store to adress that is not naturally-aligned. 5054 if (Subtarget.isGP64bit()) { 5055 Register BitcastD = MRI.createVirtualRegister(&Mips::MSA128DRegClass); 5056 Register Lo = MRI.createVirtualRegister(&Mips::GPR64RegClass); 5057 BuildMI(*BB, I, DL, TII->get(Mips::COPY)) 5058 .addDef(BitcastD) 5059 .addUse(StoreVal); 5060 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_D)) 5061 .addDef(Lo) 5062 .addUse(BitcastD) 5063 .addImm(0); 5064 BuildMI(*BB, I, DL, TII->get(Mips::SD)) 5065 .addUse(Lo) 5066 .addUse(Address) 5067 .addImm(Imm); 5068 } else { 5069 Register BitcastW = MRI.createVirtualRegister(&Mips::MSA128WRegClass); 5070 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass); 5071 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass); 5072 BuildMI(*BB, I, DL, TII->get(Mips::COPY)) 5073 .addDef(BitcastW) 5074 .addUse(StoreVal); 5075 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W)) 5076 .addDef(Lo) 5077 .addUse(BitcastW) 5078 .addImm(0); 5079 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W)) 5080 .addDef(Hi) 5081 .addUse(BitcastW) 5082 .addImm(1); 5083 BuildMI(*BB, I, DL, TII->get(Mips::SW)) 5084 .addUse(Lo) 5085 .addUse(Address) 5086 .addImm(Imm + (IsLittle ? 0 : 4)); 5087 BuildMI(*BB, I, DL, TII->get(Mips::SW)) 5088 .addUse(Hi) 5089 .addUse(Address) 5090 .addImm(Imm + (IsLittle ? 4 : 0)); 5091 } 5092 } else { 5093 // Mips release 5 needs to use instructions that can store to an unaligned 5094 // memory address. 5095 Register Bitcast = MRI.createVirtualRegister(&Mips::MSA128WRegClass); 5096 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass); 5097 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass); 5098 BuildMI(*BB, I, DL, TII->get(Mips::COPY)).addDef(Bitcast).addUse(StoreVal); 5099 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W)) 5100 .addDef(Lo) 5101 .addUse(Bitcast) 5102 .addImm(0); 5103 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W)) 5104 .addDef(Hi) 5105 .addUse(Bitcast) 5106 .addImm(1); 5107 BuildMI(*BB, I, DL, TII->get(Mips::SWR)) 5108 .addUse(Lo) 5109 .addUse(Address) 5110 .addImm(Imm + (IsLittle ? 0 : 3)); 5111 BuildMI(*BB, I, DL, TII->get(Mips::SWL)) 5112 .addUse(Lo) 5113 .addUse(Address) 5114 .addImm(Imm + (IsLittle ? 3 : 0)); 5115 BuildMI(*BB, I, DL, TII->get(Mips::SWR)) 5116 .addUse(Hi) 5117 .addUse(Address) 5118 .addImm(Imm + (IsLittle ? 4 : 7)); 5119 BuildMI(*BB, I, DL, TII->get(Mips::SWL)) 5120 .addUse(Hi) 5121 .addUse(Address) 5122 .addImm(Imm + (IsLittle ? 7 : 4)); 5123 } 5124 5125 MI.eraseFromParent(); 5126 return BB; 5127 } 5128