1 //===-- RISCVISelLowering.cpp - RISCV 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 RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "RISCV.h" 16 #include "RISCVMachineFunctionInfo.h" 17 #include "RISCVRegisterInfo.h" 18 #include "RISCVSubtarget.h" 19 #include "RISCVTargetMachine.h" 20 #include "Utils/RISCVMatInt.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/CodeGen/CallingConvLower.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.h" 28 #include "llvm/CodeGen/SelectionDAGISel.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IntrinsicsRISCV.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include "llvm/Support/raw_ostream.h" 37 38 using namespace llvm; 39 40 #define DEBUG_TYPE "riscv-lower" 41 42 STATISTIC(NumTailCalls, "Number of tail calls"); 43 44 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 45 const RISCVSubtarget &STI) 46 : TargetLowering(TM), Subtarget(STI) { 47 48 if (Subtarget.isRV32E()) 49 report_fatal_error("Codegen not yet implemented for RV32E"); 50 51 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 52 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 53 54 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 55 !Subtarget.hasStdExtF()) { 56 errs() << "Hard-float 'f' ABI can't be used for a target that " 57 "doesn't support the F instruction set extension (ignoring " 58 "target-abi)\n"; 59 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 60 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 61 !Subtarget.hasStdExtD()) { 62 errs() << "Hard-float 'd' ABI can't be used for a target that " 63 "doesn't support the D instruction set extension (ignoring " 64 "target-abi)\n"; 65 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 66 } 67 68 switch (ABI) { 69 default: 70 report_fatal_error("Don't know how to lower this ABI"); 71 case RISCVABI::ABI_ILP32: 72 case RISCVABI::ABI_ILP32F: 73 case RISCVABI::ABI_ILP32D: 74 case RISCVABI::ABI_LP64: 75 case RISCVABI::ABI_LP64F: 76 case RISCVABI::ABI_LP64D: 77 break; 78 } 79 80 MVT XLenVT = Subtarget.getXLenVT(); 81 82 // Set up the register classes. 83 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 84 85 if (Subtarget.hasStdExtF()) 86 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 87 if (Subtarget.hasStdExtD()) 88 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 89 90 // Compute derived properties from the register classes. 91 computeRegisterProperties(STI.getRegisterInfo()); 92 93 setStackPointerRegisterToSaveRestore(RISCV::X2); 94 95 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 96 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 97 98 // TODO: add all necessary setOperationAction calls. 99 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 100 101 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 102 setOperationAction(ISD::BR_CC, XLenVT, Expand); 103 setOperationAction(ISD::SELECT, XLenVT, Custom); 104 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 105 106 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 107 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 108 109 setOperationAction(ISD::VASTART, MVT::Other, Custom); 110 setOperationAction(ISD::VAARG, MVT::Other, Expand); 111 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 112 setOperationAction(ISD::VAEND, MVT::Other, Expand); 113 114 for (auto VT : {MVT::i1, MVT::i8, MVT::i16}) 115 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 116 117 if (Subtarget.is64Bit()) { 118 setOperationAction(ISD::ADD, MVT::i32, Custom); 119 setOperationAction(ISD::SUB, MVT::i32, Custom); 120 setOperationAction(ISD::SHL, MVT::i32, Custom); 121 setOperationAction(ISD::SRA, MVT::i32, Custom); 122 setOperationAction(ISD::SRL, MVT::i32, Custom); 123 } 124 125 if (!Subtarget.hasStdExtM()) { 126 setOperationAction(ISD::MUL, XLenVT, Expand); 127 setOperationAction(ISD::MULHS, XLenVT, Expand); 128 setOperationAction(ISD::MULHU, XLenVT, Expand); 129 setOperationAction(ISD::SDIV, XLenVT, Expand); 130 setOperationAction(ISD::UDIV, XLenVT, Expand); 131 setOperationAction(ISD::SREM, XLenVT, Expand); 132 setOperationAction(ISD::UREM, XLenVT, Expand); 133 } 134 135 if (Subtarget.is64Bit() && Subtarget.hasStdExtM()) { 136 setOperationAction(ISD::MUL, MVT::i32, Custom); 137 setOperationAction(ISD::SDIV, MVT::i32, Custom); 138 setOperationAction(ISD::UDIV, MVT::i32, Custom); 139 setOperationAction(ISD::UREM, MVT::i32, Custom); 140 } 141 142 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 143 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 144 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 145 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 146 147 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 148 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 149 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 150 151 setOperationAction(ISD::ROTL, XLenVT, Expand); 152 setOperationAction(ISD::ROTR, XLenVT, Expand); 153 setOperationAction(ISD::BSWAP, XLenVT, Expand); 154 setOperationAction(ISD::CTTZ, XLenVT, Expand); 155 setOperationAction(ISD::CTLZ, XLenVT, Expand); 156 setOperationAction(ISD::CTPOP, XLenVT, Expand); 157 158 ISD::CondCode FPCCToExtend[] = { 159 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 160 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 161 ISD::SETGE, ISD::SETNE}; 162 163 ISD::NodeType FPOpToExtend[] = { 164 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP, 165 ISD::FP_TO_FP16}; 166 167 if (Subtarget.hasStdExtF()) { 168 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 169 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 170 for (auto CC : FPCCToExtend) 171 setCondCodeAction(CC, MVT::f32, Expand); 172 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 173 setOperationAction(ISD::SELECT, MVT::f32, Custom); 174 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 175 for (auto Op : FPOpToExtend) 176 setOperationAction(Op, MVT::f32, Expand); 177 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 178 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 179 } 180 181 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 182 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 183 184 if (Subtarget.hasStdExtD()) { 185 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 186 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 187 for (auto CC : FPCCToExtend) 188 setCondCodeAction(CC, MVT::f64, Expand); 189 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 190 setOperationAction(ISD::SELECT, MVT::f64, Custom); 191 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 192 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 193 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 194 for (auto Op : FPOpToExtend) 195 setOperationAction(Op, MVT::f64, Expand); 196 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 197 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 198 } 199 200 if (Subtarget.is64Bit() && 201 !(Subtarget.hasStdExtD() || Subtarget.hasStdExtF())) { 202 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 203 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 204 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 205 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 206 } 207 208 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 209 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 210 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 211 212 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 213 214 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 215 // Unfortunately this can't be determined just from the ISA naming string. 216 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 217 Subtarget.is64Bit() ? Legal : Custom); 218 219 setOperationAction(ISD::TRAP, MVT::Other, Legal); 220 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 221 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 222 223 if (Subtarget.hasStdExtA()) { 224 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 225 setMinCmpXchgSizeInBits(32); 226 } else { 227 setMaxAtomicSizeInBitsSupported(0); 228 } 229 230 setBooleanContents(ZeroOrOneBooleanContent); 231 232 // Function alignments. 233 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 234 setMinFunctionAlignment(FunctionAlignment); 235 setPrefFunctionAlignment(FunctionAlignment); 236 237 // Effectively disable jump table generation. 238 setMinimumJumpTableEntries(INT_MAX); 239 } 240 241 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 242 EVT VT) const { 243 if (!VT.isVector()) 244 return getPointerTy(DL); 245 return VT.changeVectorElementTypeToInteger(); 246 } 247 248 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 249 const CallInst &I, 250 MachineFunction &MF, 251 unsigned Intrinsic) const { 252 switch (Intrinsic) { 253 default: 254 return false; 255 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 256 case Intrinsic::riscv_masked_atomicrmw_add_i32: 257 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 258 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 259 case Intrinsic::riscv_masked_atomicrmw_max_i32: 260 case Intrinsic::riscv_masked_atomicrmw_min_i32: 261 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 262 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 263 case Intrinsic::riscv_masked_cmpxchg_i32: 264 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 265 Info.opc = ISD::INTRINSIC_W_CHAIN; 266 Info.memVT = MVT::getVT(PtrTy->getElementType()); 267 Info.ptrVal = I.getArgOperand(0); 268 Info.offset = 0; 269 Info.align = Align(4); 270 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 271 MachineMemOperand::MOVolatile; 272 return true; 273 } 274 } 275 276 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 277 const AddrMode &AM, Type *Ty, 278 unsigned AS, 279 Instruction *I) const { 280 // No global is ever allowed as a base. 281 if (AM.BaseGV) 282 return false; 283 284 // Require a 12-bit signed offset. 285 if (!isInt<12>(AM.BaseOffs)) 286 return false; 287 288 switch (AM.Scale) { 289 case 0: // "r+i" or just "i", depending on HasBaseReg. 290 break; 291 case 1: 292 if (!AM.HasBaseReg) // allow "r+i". 293 break; 294 return false; // disallow "r+r" or "r+r+i". 295 default: 296 return false; 297 } 298 299 return true; 300 } 301 302 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 303 return isInt<12>(Imm); 304 } 305 306 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 307 return isInt<12>(Imm); 308 } 309 310 // On RV32, 64-bit integers are split into their high and low parts and held 311 // in two different registers, so the trunc is free since the low register can 312 // just be used. 313 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 314 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 315 return false; 316 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 317 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 318 return (SrcBits == 64 && DestBits == 32); 319 } 320 321 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 322 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 323 !SrcVT.isInteger() || !DstVT.isInteger()) 324 return false; 325 unsigned SrcBits = SrcVT.getSizeInBits(); 326 unsigned DestBits = DstVT.getSizeInBits(); 327 return (SrcBits == 64 && DestBits == 32); 328 } 329 330 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 331 // Zexts are free if they can be combined with a load. 332 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 333 EVT MemVT = LD->getMemoryVT(); 334 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 335 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 336 (LD->getExtensionType() == ISD::NON_EXTLOAD || 337 LD->getExtensionType() == ISD::ZEXTLOAD)) 338 return true; 339 } 340 341 return TargetLowering::isZExtFree(Val, VT2); 342 } 343 344 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 345 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 346 } 347 348 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 349 bool ForCodeSize) const { 350 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 351 return false; 352 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 353 return false; 354 if (Imm.isNegZero()) 355 return false; 356 return Imm.isZero(); 357 } 358 359 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 360 return (VT == MVT::f32 && Subtarget.hasStdExtF()) || 361 (VT == MVT::f64 && Subtarget.hasStdExtD()); 362 } 363 364 // Changes the condition code and swaps operands if necessary, so the SetCC 365 // operation matches one of the comparisons supported directly in the RISC-V 366 // ISA. 367 static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) { 368 switch (CC) { 369 default: 370 break; 371 case ISD::SETGT: 372 case ISD::SETLE: 373 case ISD::SETUGT: 374 case ISD::SETULE: 375 CC = ISD::getSetCCSwappedOperands(CC); 376 std::swap(LHS, RHS); 377 break; 378 } 379 } 380 381 // Return the RISC-V branch opcode that matches the given DAG integer 382 // condition code. The CondCode must be one of those supported by the RISC-V 383 // ISA (see normaliseSetCC). 384 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) { 385 switch (CC) { 386 default: 387 llvm_unreachable("Unsupported CondCode"); 388 case ISD::SETEQ: 389 return RISCV::BEQ; 390 case ISD::SETNE: 391 return RISCV::BNE; 392 case ISD::SETLT: 393 return RISCV::BLT; 394 case ISD::SETGE: 395 return RISCV::BGE; 396 case ISD::SETULT: 397 return RISCV::BLTU; 398 case ISD::SETUGE: 399 return RISCV::BGEU; 400 } 401 } 402 403 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 404 SelectionDAG &DAG) const { 405 switch (Op.getOpcode()) { 406 default: 407 report_fatal_error("unimplemented operand"); 408 case ISD::GlobalAddress: 409 return lowerGlobalAddress(Op, DAG); 410 case ISD::BlockAddress: 411 return lowerBlockAddress(Op, DAG); 412 case ISD::ConstantPool: 413 return lowerConstantPool(Op, DAG); 414 case ISD::GlobalTLSAddress: 415 return lowerGlobalTLSAddress(Op, DAG); 416 case ISD::SELECT: 417 return lowerSELECT(Op, DAG); 418 case ISD::VASTART: 419 return lowerVASTART(Op, DAG); 420 case ISD::FRAMEADDR: 421 return lowerFRAMEADDR(Op, DAG); 422 case ISD::RETURNADDR: 423 return lowerRETURNADDR(Op, DAG); 424 case ISD::SHL_PARTS: 425 return lowerShiftLeftParts(Op, DAG); 426 case ISD::SRA_PARTS: 427 return lowerShiftRightParts(Op, DAG, true); 428 case ISD::SRL_PARTS: 429 return lowerShiftRightParts(Op, DAG, false); 430 case ISD::BITCAST: { 431 assert(Subtarget.is64Bit() && Subtarget.hasStdExtF() && 432 "Unexpected custom legalisation"); 433 SDLoc DL(Op); 434 SDValue Op0 = Op.getOperand(0); 435 if (Op.getValueType() != MVT::f32 || Op0.getValueType() != MVT::i32) 436 return SDValue(); 437 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 438 SDValue FPConv = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 439 return FPConv; 440 } 441 case ISD::INTRINSIC_WO_CHAIN: 442 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 443 } 444 } 445 446 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 447 SelectionDAG &DAG, unsigned Flags) { 448 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 449 } 450 451 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 452 SelectionDAG &DAG, unsigned Flags) { 453 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 454 Flags); 455 } 456 457 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 458 SelectionDAG &DAG, unsigned Flags) { 459 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 460 N->getOffset(), Flags); 461 } 462 463 template <class NodeTy> 464 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 465 bool IsLocal) const { 466 SDLoc DL(N); 467 EVT Ty = getPointerTy(DAG.getDataLayout()); 468 469 if (isPositionIndependent()) { 470 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 471 if (IsLocal) 472 // Use PC-relative addressing to access the symbol. This generates the 473 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 474 // %pcrel_lo(auipc)). 475 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 476 477 // Use PC-relative addressing to access the GOT for this symbol, then load 478 // the address from the GOT. This generates the pattern (PseudoLA sym), 479 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 480 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 481 } 482 483 switch (getTargetMachine().getCodeModel()) { 484 default: 485 report_fatal_error("Unsupported code model for lowering"); 486 case CodeModel::Small: { 487 // Generate a sequence for accessing addresses within the first 2 GiB of 488 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 489 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 490 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 491 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 492 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 493 } 494 case CodeModel::Medium: { 495 // Generate a sequence for accessing addresses within any 2GiB range within 496 // the address space. This generates the pattern (PseudoLLA sym), which 497 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 498 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 499 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 500 } 501 } 502 } 503 504 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 505 SelectionDAG &DAG) const { 506 SDLoc DL(Op); 507 EVT Ty = Op.getValueType(); 508 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 509 int64_t Offset = N->getOffset(); 510 MVT XLenVT = Subtarget.getXLenVT(); 511 512 const GlobalValue *GV = N->getGlobal(); 513 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 514 SDValue Addr = getAddr(N, DAG, IsLocal); 515 516 // In order to maximise the opportunity for common subexpression elimination, 517 // emit a separate ADD node for the global address offset instead of folding 518 // it in the global address node. Later peephole optimisations may choose to 519 // fold it back in when profitable. 520 if (Offset != 0) 521 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 522 DAG.getConstant(Offset, DL, XLenVT)); 523 return Addr; 524 } 525 526 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 527 SelectionDAG &DAG) const { 528 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 529 530 return getAddr(N, DAG); 531 } 532 533 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 534 SelectionDAG &DAG) const { 535 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 536 537 return getAddr(N, DAG); 538 } 539 540 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 541 SelectionDAG &DAG, 542 bool UseGOT) const { 543 SDLoc DL(N); 544 EVT Ty = getPointerTy(DAG.getDataLayout()); 545 const GlobalValue *GV = N->getGlobal(); 546 MVT XLenVT = Subtarget.getXLenVT(); 547 548 if (UseGOT) { 549 // Use PC-relative addressing to access the GOT for this TLS symbol, then 550 // load the address from the GOT and add the thread pointer. This generates 551 // the pattern (PseudoLA_TLS_IE sym), which expands to 552 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 553 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 554 SDValue Load = 555 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 556 557 // Add the thread pointer. 558 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 559 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 560 } 561 562 // Generate a sequence for accessing the address relative to the thread 563 // pointer, with the appropriate adjustment for the thread pointer offset. 564 // This generates the pattern 565 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 566 SDValue AddrHi = 567 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 568 SDValue AddrAdd = 569 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 570 SDValue AddrLo = 571 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 572 573 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 574 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 575 SDValue MNAdd = SDValue( 576 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 577 0); 578 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 579 } 580 581 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 582 SelectionDAG &DAG) const { 583 SDLoc DL(N); 584 EVT Ty = getPointerTy(DAG.getDataLayout()); 585 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 586 const GlobalValue *GV = N->getGlobal(); 587 588 // Use a PC-relative addressing mode to access the global dynamic GOT address. 589 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 590 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 591 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 592 SDValue Load = 593 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 594 595 // Prepare argument list to generate call. 596 ArgListTy Args; 597 ArgListEntry Entry; 598 Entry.Node = Load; 599 Entry.Ty = CallTy; 600 Args.push_back(Entry); 601 602 // Setup call to __tls_get_addr. 603 TargetLowering::CallLoweringInfo CLI(DAG); 604 CLI.setDebugLoc(DL) 605 .setChain(DAG.getEntryNode()) 606 .setLibCallee(CallingConv::C, CallTy, 607 DAG.getExternalSymbol("__tls_get_addr", Ty), 608 std::move(Args)); 609 610 return LowerCallTo(CLI).first; 611 } 612 613 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 614 SelectionDAG &DAG) const { 615 SDLoc DL(Op); 616 EVT Ty = Op.getValueType(); 617 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 618 int64_t Offset = N->getOffset(); 619 MVT XLenVT = Subtarget.getXLenVT(); 620 621 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 622 623 SDValue Addr; 624 switch (Model) { 625 case TLSModel::LocalExec: 626 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 627 break; 628 case TLSModel::InitialExec: 629 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 630 break; 631 case TLSModel::LocalDynamic: 632 case TLSModel::GeneralDynamic: 633 Addr = getDynamicTLSAddr(N, DAG); 634 break; 635 } 636 637 // In order to maximise the opportunity for common subexpression elimination, 638 // emit a separate ADD node for the global address offset instead of folding 639 // it in the global address node. Later peephole optimisations may choose to 640 // fold it back in when profitable. 641 if (Offset != 0) 642 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 643 DAG.getConstant(Offset, DL, XLenVT)); 644 return Addr; 645 } 646 647 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 648 SDValue CondV = Op.getOperand(0); 649 SDValue TrueV = Op.getOperand(1); 650 SDValue FalseV = Op.getOperand(2); 651 SDLoc DL(Op); 652 MVT XLenVT = Subtarget.getXLenVT(); 653 654 // If the result type is XLenVT and CondV is the output of a SETCC node 655 // which also operated on XLenVT inputs, then merge the SETCC node into the 656 // lowered RISCVISD::SELECT_CC to take advantage of the integer 657 // compare+branch instructions. i.e.: 658 // (select (setcc lhs, rhs, cc), truev, falsev) 659 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 660 if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC && 661 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 662 SDValue LHS = CondV.getOperand(0); 663 SDValue RHS = CondV.getOperand(1); 664 auto CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 665 ISD::CondCode CCVal = CC->get(); 666 667 normaliseSetCC(LHS, RHS, CCVal); 668 669 SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT); 670 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 671 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 672 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops); 673 } 674 675 // Otherwise: 676 // (select condv, truev, falsev) 677 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 678 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 679 SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT); 680 681 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 682 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 683 684 return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops); 685 } 686 687 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 688 MachineFunction &MF = DAG.getMachineFunction(); 689 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 690 691 SDLoc DL(Op); 692 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 693 getPointerTy(MF.getDataLayout())); 694 695 // vastart just stores the address of the VarArgsFrameIndex slot into the 696 // memory location argument. 697 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 698 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 699 MachinePointerInfo(SV)); 700 } 701 702 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 703 SelectionDAG &DAG) const { 704 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 705 MachineFunction &MF = DAG.getMachineFunction(); 706 MachineFrameInfo &MFI = MF.getFrameInfo(); 707 MFI.setFrameAddressIsTaken(true); 708 Register FrameReg = RI.getFrameRegister(MF); 709 int XLenInBytes = Subtarget.getXLen() / 8; 710 711 EVT VT = Op.getValueType(); 712 SDLoc DL(Op); 713 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 714 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 715 while (Depth--) { 716 int Offset = -(XLenInBytes * 2); 717 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 718 DAG.getIntPtrConstant(Offset, DL)); 719 FrameAddr = 720 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 721 } 722 return FrameAddr; 723 } 724 725 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 726 SelectionDAG &DAG) const { 727 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 728 MachineFunction &MF = DAG.getMachineFunction(); 729 MachineFrameInfo &MFI = MF.getFrameInfo(); 730 MFI.setReturnAddressIsTaken(true); 731 MVT XLenVT = Subtarget.getXLenVT(); 732 int XLenInBytes = Subtarget.getXLen() / 8; 733 734 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 735 return SDValue(); 736 737 EVT VT = Op.getValueType(); 738 SDLoc DL(Op); 739 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 740 if (Depth) { 741 int Off = -XLenInBytes; 742 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 743 SDValue Offset = DAG.getConstant(Off, DL, VT); 744 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 745 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 746 MachinePointerInfo()); 747 } 748 749 // Return the value of the return address register, marking it an implicit 750 // live-in. 751 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 752 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 753 } 754 755 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 756 SelectionDAG &DAG) const { 757 SDLoc DL(Op); 758 SDValue Lo = Op.getOperand(0); 759 SDValue Hi = Op.getOperand(1); 760 SDValue Shamt = Op.getOperand(2); 761 EVT VT = Lo.getValueType(); 762 763 // if Shamt-XLEN < 0: // Shamt < XLEN 764 // Lo = Lo << Shamt 765 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 766 // else: 767 // Lo = 0 768 // Hi = Lo << (Shamt-XLEN) 769 770 SDValue Zero = DAG.getConstant(0, DL, VT); 771 SDValue One = DAG.getConstant(1, DL, VT); 772 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 773 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 774 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 775 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 776 777 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 778 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 779 SDValue ShiftRightLo = 780 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 781 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 782 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 783 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 784 785 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 786 787 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 788 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 789 790 SDValue Parts[2] = {Lo, Hi}; 791 return DAG.getMergeValues(Parts, DL); 792 } 793 794 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 795 bool IsSRA) const { 796 SDLoc DL(Op); 797 SDValue Lo = Op.getOperand(0); 798 SDValue Hi = Op.getOperand(1); 799 SDValue Shamt = Op.getOperand(2); 800 EVT VT = Lo.getValueType(); 801 802 // SRA expansion: 803 // if Shamt-XLEN < 0: // Shamt < XLEN 804 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 805 // Hi = Hi >>s Shamt 806 // else: 807 // Lo = Hi >>s (Shamt-XLEN); 808 // Hi = Hi >>s (XLEN-1) 809 // 810 // SRL expansion: 811 // if Shamt-XLEN < 0: // Shamt < XLEN 812 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 813 // Hi = Hi >>u Shamt 814 // else: 815 // Lo = Hi >>u (Shamt-XLEN); 816 // Hi = 0; 817 818 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 819 820 SDValue Zero = DAG.getConstant(0, DL, VT); 821 SDValue One = DAG.getConstant(1, DL, VT); 822 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 823 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 824 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 825 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 826 827 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 828 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 829 SDValue ShiftLeftHi = 830 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 831 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 832 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 833 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 834 SDValue HiFalse = 835 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 836 837 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 838 839 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 840 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 841 842 SDValue Parts[2] = {Lo, Hi}; 843 return DAG.getMergeValues(Parts, DL); 844 } 845 846 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 847 SelectionDAG &DAG) const { 848 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 849 SDLoc DL(Op); 850 switch (IntNo) { 851 default: 852 return SDValue(); // Don't custom lower most intrinsics. 853 case Intrinsic::thread_pointer: { 854 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 855 return DAG.getRegister(RISCV::X4, PtrVT); 856 } 857 } 858 } 859 860 // Returns the opcode of the target-specific SDNode that implements the 32-bit 861 // form of the given Opcode. 862 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 863 switch (Opcode) { 864 default: 865 llvm_unreachable("Unexpected opcode"); 866 case ISD::SHL: 867 return RISCVISD::SLLW; 868 case ISD::SRA: 869 return RISCVISD::SRAW; 870 case ISD::SRL: 871 return RISCVISD::SRLW; 872 case ISD::SDIV: 873 return RISCVISD::DIVW; 874 case ISD::UDIV: 875 return RISCVISD::DIVUW; 876 case ISD::UREM: 877 return RISCVISD::REMUW; 878 } 879 } 880 881 // Converts the given 32-bit operation to a target-specific SelectionDAG node. 882 // Because i32 isn't a legal type for RV64, these operations would otherwise 883 // be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W 884 // later one because the fact the operation was originally of type i32 is 885 // lost. 886 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG) { 887 SDLoc DL(N); 888 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 889 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 890 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 891 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 892 // ReplaceNodeResults requires we maintain the same type for the return value. 893 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 894 } 895 896 // Converts the given 32-bit operation to a i64 operation with signed extension 897 // semantic to reduce the signed extension instructions. 898 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 899 SDLoc DL(N); 900 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 901 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 902 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 903 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 904 DAG.getValueType(MVT::i32)); 905 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 906 } 907 908 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 909 SmallVectorImpl<SDValue> &Results, 910 SelectionDAG &DAG) const { 911 SDLoc DL(N); 912 switch (N->getOpcode()) { 913 default: 914 llvm_unreachable("Don't know how to custom type legalize this operation!"); 915 case ISD::STRICT_FP_TO_SINT: 916 case ISD::STRICT_FP_TO_UINT: 917 case ISD::FP_TO_SINT: 918 case ISD::FP_TO_UINT: { 919 bool IsStrict = N->isStrictFPOpcode(); 920 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 921 "Unexpected custom legalisation"); 922 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 923 RTLIB::Libcall LC; 924 if (N->getOpcode() == ISD::FP_TO_SINT || 925 N->getOpcode() == ISD::STRICT_FP_TO_SINT) 926 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 927 else 928 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 929 MakeLibCallOptions CallOptions; 930 EVT OpVT = Op0.getValueType(); 931 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 932 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 933 SDValue Result; 934 std::tie(Result, Chain) = 935 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 936 Results.push_back(Result); 937 if (IsStrict) 938 Results.push_back(Chain); 939 break; 940 } 941 case ISD::READCYCLECOUNTER: { 942 assert(!Subtarget.is64Bit() && 943 "READCYCLECOUNTER only has custom type legalization on riscv32"); 944 945 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 946 SDValue RCW = 947 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 948 949 Results.push_back( 950 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 951 Results.push_back(RCW.getValue(2)); 952 break; 953 } 954 case ISD::ADD: 955 case ISD::SUB: 956 case ISD::MUL: 957 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 958 "Unexpected custom legalisation"); 959 if (N->getOperand(1).getOpcode() == ISD::Constant) 960 return; 961 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 962 break; 963 case ISD::SHL: 964 case ISD::SRA: 965 case ISD::SRL: 966 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 967 "Unexpected custom legalisation"); 968 if (N->getOperand(1).getOpcode() == ISD::Constant) 969 return; 970 Results.push_back(customLegalizeToWOp(N, DAG)); 971 break; 972 case ISD::SDIV: 973 case ISD::UDIV: 974 case ISD::UREM: 975 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 976 Subtarget.hasStdExtM() && "Unexpected custom legalisation"); 977 if (N->getOperand(0).getOpcode() == ISD::Constant || 978 N->getOperand(1).getOpcode() == ISD::Constant) 979 return; 980 Results.push_back(customLegalizeToWOp(N, DAG)); 981 break; 982 case ISD::BITCAST: { 983 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 984 Subtarget.hasStdExtF() && "Unexpected custom legalisation"); 985 SDLoc DL(N); 986 SDValue Op0 = N->getOperand(0); 987 if (Op0.getValueType() != MVT::f32) 988 return; 989 SDValue FPConv = 990 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 991 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 992 break; 993 } 994 } 995 } 996 997 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 998 DAGCombinerInfo &DCI) const { 999 SelectionDAG &DAG = DCI.DAG; 1000 1001 switch (N->getOpcode()) { 1002 default: 1003 break; 1004 case RISCVISD::SplitF64: { 1005 SDValue Op0 = N->getOperand(0); 1006 // If the input to SplitF64 is just BuildPairF64 then the operation is 1007 // redundant. Instead, use BuildPairF64's operands directly. 1008 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 1009 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 1010 1011 SDLoc DL(N); 1012 1013 // It's cheaper to materialise two 32-bit integers than to load a double 1014 // from the constant pool and transfer it to integer registers through the 1015 // stack. 1016 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 1017 APInt V = C->getValueAPF().bitcastToAPInt(); 1018 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 1019 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 1020 return DCI.CombineTo(N, Lo, Hi); 1021 } 1022 1023 // This is a target-specific version of a DAGCombine performed in 1024 // DAGCombiner::visitBITCAST. It performs the equivalent of: 1025 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 1026 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 1027 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 1028 !Op0.getNode()->hasOneUse()) 1029 break; 1030 SDValue NewSplitF64 = 1031 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 1032 Op0.getOperand(0)); 1033 SDValue Lo = NewSplitF64.getValue(0); 1034 SDValue Hi = NewSplitF64.getValue(1); 1035 APInt SignBit = APInt::getSignMask(32); 1036 if (Op0.getOpcode() == ISD::FNEG) { 1037 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 1038 DAG.getConstant(SignBit, DL, MVT::i32)); 1039 return DCI.CombineTo(N, Lo, NewHi); 1040 } 1041 assert(Op0.getOpcode() == ISD::FABS); 1042 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 1043 DAG.getConstant(~SignBit, DL, MVT::i32)); 1044 return DCI.CombineTo(N, Lo, NewHi); 1045 } 1046 case RISCVISD::SLLW: 1047 case RISCVISD::SRAW: 1048 case RISCVISD::SRLW: { 1049 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 1050 SDValue LHS = N->getOperand(0); 1051 SDValue RHS = N->getOperand(1); 1052 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 1053 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5); 1054 if ((SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI)) || 1055 (SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI))) 1056 return SDValue(); 1057 break; 1058 } 1059 case RISCVISD::FMV_X_ANYEXTW_RV64: { 1060 SDLoc DL(N); 1061 SDValue Op0 = N->getOperand(0); 1062 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 1063 // conversion is unnecessary and can be replaced with an ANY_EXTEND 1064 // of the FMV_W_X_RV64 operand. 1065 if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) { 1066 SDValue AExtOp = 1067 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0.getOperand(0)); 1068 return DCI.CombineTo(N, AExtOp); 1069 } 1070 1071 // This is a target-specific version of a DAGCombine performed in 1072 // DAGCombiner::visitBITCAST. It performs the equivalent of: 1073 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 1074 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 1075 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 1076 !Op0.getNode()->hasOneUse()) 1077 break; 1078 SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, 1079 Op0.getOperand(0)); 1080 APInt SignBit = APInt::getSignMask(32).sext(64); 1081 if (Op0.getOpcode() == ISD::FNEG) { 1082 return DCI.CombineTo(N, 1083 DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV, 1084 DAG.getConstant(SignBit, DL, MVT::i64))); 1085 } 1086 assert(Op0.getOpcode() == ISD::FABS); 1087 return DCI.CombineTo(N, 1088 DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV, 1089 DAG.getConstant(~SignBit, DL, MVT::i64))); 1090 } 1091 } 1092 1093 return SDValue(); 1094 } 1095 1096 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 1097 const SDNode *N, CombineLevel Level) const { 1098 // The following folds are only desirable if `(OP _, c1 << c2)` can be 1099 // materialised in fewer instructions than `(OP _, c1)`: 1100 // 1101 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 1102 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 1103 SDValue N0 = N->getOperand(0); 1104 EVT Ty = N0.getValueType(); 1105 if (Ty.isScalarInteger() && 1106 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 1107 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 1108 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 1109 if (C1 && C2) { 1110 APInt C1Int = C1->getAPIntValue(); 1111 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 1112 1113 // We can materialise `c1 << c2` into an add immediate, so it's "free", 1114 // and the combine should happen, to potentially allow further combines 1115 // later. 1116 if (ShiftedC1Int.getMinSignedBits() <= 64 && 1117 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 1118 return true; 1119 1120 // We can materialise `c1` in an add immediate, so it's "free", and the 1121 // combine should be prevented. 1122 if (C1Int.getMinSignedBits() <= 64 && 1123 isLegalAddImmediate(C1Int.getSExtValue())) 1124 return false; 1125 1126 // Neither constant will fit into an immediate, so find materialisation 1127 // costs. 1128 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 1129 Subtarget.is64Bit()); 1130 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 1131 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.is64Bit()); 1132 1133 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 1134 // combine should be prevented. 1135 if (C1Cost < ShiftedC1Cost) 1136 return false; 1137 } 1138 } 1139 return true; 1140 } 1141 1142 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 1143 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 1144 unsigned Depth) const { 1145 switch (Op.getOpcode()) { 1146 default: 1147 break; 1148 case RISCVISD::SLLW: 1149 case RISCVISD::SRAW: 1150 case RISCVISD::SRLW: 1151 case RISCVISD::DIVW: 1152 case RISCVISD::DIVUW: 1153 case RISCVISD::REMUW: 1154 // TODO: As the result is sign-extended, this is conservatively correct. A 1155 // more precise answer could be calculated for SRAW depending on known 1156 // bits in the shift amount. 1157 return 33; 1158 } 1159 1160 return 1; 1161 } 1162 1163 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 1164 MachineBasicBlock *BB) { 1165 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 1166 1167 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 1168 // Should the count have wrapped while it was being read, we need to try 1169 // again. 1170 // ... 1171 // read: 1172 // rdcycleh x3 # load high word of cycle 1173 // rdcycle x2 # load low word of cycle 1174 // rdcycleh x4 # load high word of cycle 1175 // bne x3, x4, read # check if high word reads match, otherwise try again 1176 // ... 1177 1178 MachineFunction &MF = *BB->getParent(); 1179 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 1180 MachineFunction::iterator It = ++BB->getIterator(); 1181 1182 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 1183 MF.insert(It, LoopMBB); 1184 1185 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 1186 MF.insert(It, DoneMBB); 1187 1188 // Transfer the remainder of BB and its successor edges to DoneMBB. 1189 DoneMBB->splice(DoneMBB->begin(), BB, 1190 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 1191 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 1192 1193 BB->addSuccessor(LoopMBB); 1194 1195 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 1196 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 1197 Register LoReg = MI.getOperand(0).getReg(); 1198 Register HiReg = MI.getOperand(1).getReg(); 1199 DebugLoc DL = MI.getDebugLoc(); 1200 1201 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 1202 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 1203 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 1204 .addReg(RISCV::X0); 1205 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 1206 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 1207 .addReg(RISCV::X0); 1208 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 1209 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 1210 .addReg(RISCV::X0); 1211 1212 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 1213 .addReg(HiReg) 1214 .addReg(ReadAgainReg) 1215 .addMBB(LoopMBB); 1216 1217 LoopMBB->addSuccessor(LoopMBB); 1218 LoopMBB->addSuccessor(DoneMBB); 1219 1220 MI.eraseFromParent(); 1221 1222 return DoneMBB; 1223 } 1224 1225 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 1226 MachineBasicBlock *BB) { 1227 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 1228 1229 MachineFunction &MF = *BB->getParent(); 1230 DebugLoc DL = MI.getDebugLoc(); 1231 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1232 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 1233 Register LoReg = MI.getOperand(0).getReg(); 1234 Register HiReg = MI.getOperand(1).getReg(); 1235 Register SrcReg = MI.getOperand(2).getReg(); 1236 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 1237 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(); 1238 1239 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 1240 RI); 1241 MachineMemOperand *MMO = 1242 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI), 1243 MachineMemOperand::MOLoad, 8, Align(8)); 1244 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 1245 .addFrameIndex(FI) 1246 .addImm(0) 1247 .addMemOperand(MMO); 1248 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 1249 .addFrameIndex(FI) 1250 .addImm(4) 1251 .addMemOperand(MMO); 1252 MI.eraseFromParent(); // The pseudo instruction is gone now. 1253 return BB; 1254 } 1255 1256 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 1257 MachineBasicBlock *BB) { 1258 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 1259 "Unexpected instruction"); 1260 1261 MachineFunction &MF = *BB->getParent(); 1262 DebugLoc DL = MI.getDebugLoc(); 1263 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1264 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 1265 Register DstReg = MI.getOperand(0).getReg(); 1266 Register LoReg = MI.getOperand(1).getReg(); 1267 Register HiReg = MI.getOperand(2).getReg(); 1268 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 1269 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(); 1270 1271 MachineMemOperand *MMO = 1272 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI), 1273 MachineMemOperand::MOStore, 8, Align(8)); 1274 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 1275 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 1276 .addFrameIndex(FI) 1277 .addImm(0) 1278 .addMemOperand(MMO); 1279 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 1280 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 1281 .addFrameIndex(FI) 1282 .addImm(4) 1283 .addMemOperand(MMO); 1284 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 1285 MI.eraseFromParent(); // The pseudo instruction is gone now. 1286 return BB; 1287 } 1288 1289 static bool isSelectPseudo(MachineInstr &MI) { 1290 switch (MI.getOpcode()) { 1291 default: 1292 return false; 1293 case RISCV::Select_GPR_Using_CC_GPR: 1294 case RISCV::Select_FPR32_Using_CC_GPR: 1295 case RISCV::Select_FPR64_Using_CC_GPR: 1296 return true; 1297 } 1298 } 1299 1300 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 1301 MachineBasicBlock *BB) { 1302 // To "insert" Select_* instructions, we actually have to insert the triangle 1303 // control-flow pattern. The incoming instructions know the destination vreg 1304 // to set, the condition code register to branch on, the true/false values to 1305 // select between, and the condcode to use to select the appropriate branch. 1306 // 1307 // We produce the following control flow: 1308 // HeadMBB 1309 // | \ 1310 // | IfFalseMBB 1311 // | / 1312 // TailMBB 1313 // 1314 // When we find a sequence of selects we attempt to optimize their emission 1315 // by sharing the control flow. Currently we only handle cases where we have 1316 // multiple selects with the exact same condition (same LHS, RHS and CC). 1317 // The selects may be interleaved with other instructions if the other 1318 // instructions meet some requirements we deem safe: 1319 // - They are debug instructions. Otherwise, 1320 // - They do not have side-effects, do not access memory and their inputs do 1321 // not depend on the results of the select pseudo-instructions. 1322 // The TrueV/FalseV operands of the selects cannot depend on the result of 1323 // previous selects in the sequence. 1324 // These conditions could be further relaxed. See the X86 target for a 1325 // related approach and more information. 1326 Register LHS = MI.getOperand(1).getReg(); 1327 Register RHS = MI.getOperand(2).getReg(); 1328 auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm()); 1329 1330 SmallVector<MachineInstr *, 4> SelectDebugValues; 1331 SmallSet<Register, 4> SelectDests; 1332 SelectDests.insert(MI.getOperand(0).getReg()); 1333 1334 MachineInstr *LastSelectPseudo = &MI; 1335 1336 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 1337 SequenceMBBI != E; ++SequenceMBBI) { 1338 if (SequenceMBBI->isDebugInstr()) 1339 continue; 1340 else if (isSelectPseudo(*SequenceMBBI)) { 1341 if (SequenceMBBI->getOperand(1).getReg() != LHS || 1342 SequenceMBBI->getOperand(2).getReg() != RHS || 1343 SequenceMBBI->getOperand(3).getImm() != CC || 1344 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 1345 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 1346 break; 1347 LastSelectPseudo = &*SequenceMBBI; 1348 SequenceMBBI->collectDebugValues(SelectDebugValues); 1349 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 1350 } else { 1351 if (SequenceMBBI->hasUnmodeledSideEffects() || 1352 SequenceMBBI->mayLoadOrStore()) 1353 break; 1354 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 1355 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 1356 })) 1357 break; 1358 } 1359 } 1360 1361 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 1362 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 1363 DebugLoc DL = MI.getDebugLoc(); 1364 MachineFunction::iterator I = ++BB->getIterator(); 1365 1366 MachineBasicBlock *HeadMBB = BB; 1367 MachineFunction *F = BB->getParent(); 1368 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 1369 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 1370 1371 F->insert(I, IfFalseMBB); 1372 F->insert(I, TailMBB); 1373 1374 // Transfer debug instructions associated with the selects to TailMBB. 1375 for (MachineInstr *DebugInstr : SelectDebugValues) { 1376 TailMBB->push_back(DebugInstr->removeFromParent()); 1377 } 1378 1379 // Move all instructions after the sequence to TailMBB. 1380 TailMBB->splice(TailMBB->end(), HeadMBB, 1381 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 1382 // Update machine-CFG edges by transferring all successors of the current 1383 // block to the new block which will contain the Phi nodes for the selects. 1384 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 1385 // Set the successors for HeadMBB. 1386 HeadMBB->addSuccessor(IfFalseMBB); 1387 HeadMBB->addSuccessor(TailMBB); 1388 1389 // Insert appropriate branch. 1390 unsigned Opcode = getBranchOpcodeForIntCondCode(CC); 1391 1392 BuildMI(HeadMBB, DL, TII.get(Opcode)) 1393 .addReg(LHS) 1394 .addReg(RHS) 1395 .addMBB(TailMBB); 1396 1397 // IfFalseMBB just falls through to TailMBB. 1398 IfFalseMBB->addSuccessor(TailMBB); 1399 1400 // Create PHIs for all of the select pseudo-instructions. 1401 auto SelectMBBI = MI.getIterator(); 1402 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 1403 auto InsertionPoint = TailMBB->begin(); 1404 while (SelectMBBI != SelectEnd) { 1405 auto Next = std::next(SelectMBBI); 1406 if (isSelectPseudo(*SelectMBBI)) { 1407 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 1408 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 1409 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 1410 .addReg(SelectMBBI->getOperand(4).getReg()) 1411 .addMBB(HeadMBB) 1412 .addReg(SelectMBBI->getOperand(5).getReg()) 1413 .addMBB(IfFalseMBB); 1414 SelectMBBI->eraseFromParent(); 1415 } 1416 SelectMBBI = Next; 1417 } 1418 1419 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 1420 return TailMBB; 1421 } 1422 1423 MachineBasicBlock * 1424 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 1425 MachineBasicBlock *BB) const { 1426 switch (MI.getOpcode()) { 1427 default: 1428 llvm_unreachable("Unexpected instr type to insert"); 1429 case RISCV::ReadCycleWide: 1430 assert(!Subtarget.is64Bit() && 1431 "ReadCycleWrite is only to be used on riscv32"); 1432 return emitReadCycleWidePseudo(MI, BB); 1433 case RISCV::Select_GPR_Using_CC_GPR: 1434 case RISCV::Select_FPR32_Using_CC_GPR: 1435 case RISCV::Select_FPR64_Using_CC_GPR: 1436 return emitSelectPseudo(MI, BB); 1437 case RISCV::BuildPairF64Pseudo: 1438 return emitBuildPairF64Pseudo(MI, BB); 1439 case RISCV::SplitF64Pseudo: 1440 return emitSplitF64Pseudo(MI, BB); 1441 } 1442 } 1443 1444 // Calling Convention Implementation. 1445 // The expectations for frontend ABI lowering vary from target to target. 1446 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 1447 // details, but this is a longer term goal. For now, we simply try to keep the 1448 // role of the frontend as simple and well-defined as possible. The rules can 1449 // be summarised as: 1450 // * Never split up large scalar arguments. We handle them here. 1451 // * If a hardfloat calling convention is being used, and the struct may be 1452 // passed in a pair of registers (fp+fp, int+fp), and both registers are 1453 // available, then pass as two separate arguments. If either the GPRs or FPRs 1454 // are exhausted, then pass according to the rule below. 1455 // * If a struct could never be passed in registers or directly in a stack 1456 // slot (as it is larger than 2*XLEN and the floating point rules don't 1457 // apply), then pass it using a pointer with the byval attribute. 1458 // * If a struct is less than 2*XLEN, then coerce to either a two-element 1459 // word-sized array or a 2*XLEN scalar (depending on alignment). 1460 // * The frontend can determine whether a struct is returned by reference or 1461 // not based on its size and fields. If it will be returned by reference, the 1462 // frontend must modify the prototype so a pointer with the sret annotation is 1463 // passed as the first argument. This is not necessary for large scalar 1464 // returns. 1465 // * Struct return values and varargs should be coerced to structs containing 1466 // register-size fields in the same situations they would be for fixed 1467 // arguments. 1468 1469 static const MCPhysReg ArgGPRs[] = { 1470 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 1471 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 1472 }; 1473 static const MCPhysReg ArgFPR32s[] = { 1474 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 1475 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 1476 }; 1477 static const MCPhysReg ArgFPR64s[] = { 1478 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 1479 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 1480 }; 1481 1482 // Pass a 2*XLEN argument that has been split into two XLEN values through 1483 // registers or the stack as necessary. 1484 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 1485 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 1486 MVT ValVT2, MVT LocVT2, 1487 ISD::ArgFlagsTy ArgFlags2) { 1488 unsigned XLenInBytes = XLen / 8; 1489 if (Register Reg = State.AllocateReg(ArgGPRs)) { 1490 // At least one half can be passed via register. 1491 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 1492 VA1.getLocVT(), CCValAssign::Full)); 1493 } else { 1494 // Both halves must be passed on the stack, with proper alignment. 1495 Align StackAlign = 1496 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 1497 State.addLoc( 1498 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 1499 State.AllocateStack(XLenInBytes, StackAlign), 1500 VA1.getLocVT(), CCValAssign::Full)); 1501 State.addLoc(CCValAssign::getMem( 1502 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 1503 LocVT2, CCValAssign::Full)); 1504 return false; 1505 } 1506 1507 if (Register Reg = State.AllocateReg(ArgGPRs)) { 1508 // The second half can also be passed via register. 1509 State.addLoc( 1510 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 1511 } else { 1512 // The second half is passed via the stack, without additional alignment. 1513 State.addLoc(CCValAssign::getMem( 1514 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 1515 LocVT2, CCValAssign::Full)); 1516 } 1517 1518 return false; 1519 } 1520 1521 // Implements the RISC-V calling convention. Returns true upon failure. 1522 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 1523 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 1524 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 1525 bool IsRet, Type *OrigTy) { 1526 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 1527 assert(XLen == 32 || XLen == 64); 1528 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 1529 1530 // Any return value split in to more than two values can't be returned 1531 // directly. 1532 if (IsRet && ValNo > 1) 1533 return true; 1534 1535 // UseGPRForF32 if targeting one of the soft-float ABIs, if passing a 1536 // variadic argument, or if no F32 argument registers are available. 1537 bool UseGPRForF32 = true; 1538 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 1539 // variadic argument, or if no F64 argument registers are available. 1540 bool UseGPRForF64 = true; 1541 1542 switch (ABI) { 1543 default: 1544 llvm_unreachable("Unexpected ABI"); 1545 case RISCVABI::ABI_ILP32: 1546 case RISCVABI::ABI_LP64: 1547 break; 1548 case RISCVABI::ABI_ILP32F: 1549 case RISCVABI::ABI_LP64F: 1550 UseGPRForF32 = !IsFixed; 1551 break; 1552 case RISCVABI::ABI_ILP32D: 1553 case RISCVABI::ABI_LP64D: 1554 UseGPRForF32 = !IsFixed; 1555 UseGPRForF64 = !IsFixed; 1556 break; 1557 } 1558 1559 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) 1560 UseGPRForF32 = true; 1561 if (State.getFirstUnallocated(ArgFPR64s) == array_lengthof(ArgFPR64s)) 1562 UseGPRForF64 = true; 1563 1564 // From this point on, rely on UseGPRForF32, UseGPRForF64 and similar local 1565 // variables rather than directly checking against the target ABI. 1566 1567 if (UseGPRForF32 && ValVT == MVT::f32) { 1568 LocVT = XLenVT; 1569 LocInfo = CCValAssign::BCvt; 1570 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 1571 LocVT = MVT::i64; 1572 LocInfo = CCValAssign::BCvt; 1573 } 1574 1575 // If this is a variadic argument, the RISC-V calling convention requires 1576 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 1577 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 1578 // be used regardless of whether the original argument was split during 1579 // legalisation or not. The argument will not be passed by registers if the 1580 // original type is larger than 2*XLEN, so the register alignment rule does 1581 // not apply. 1582 unsigned TwoXLenInBytes = (2 * XLen) / 8; 1583 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 1584 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 1585 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 1586 // Skip 'odd' register if necessary. 1587 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 1588 State.AllocateReg(ArgGPRs); 1589 } 1590 1591 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 1592 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 1593 State.getPendingArgFlags(); 1594 1595 assert(PendingLocs.size() == PendingArgFlags.size() && 1596 "PendingLocs and PendingArgFlags out of sync"); 1597 1598 // Handle passing f64 on RV32D with a soft float ABI or when floating point 1599 // registers are exhausted. 1600 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 1601 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 1602 "Can't lower f64 if it is split"); 1603 // Depending on available argument GPRS, f64 may be passed in a pair of 1604 // GPRs, split between a GPR and the stack, or passed completely on the 1605 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 1606 // cases. 1607 Register Reg = State.AllocateReg(ArgGPRs); 1608 LocVT = MVT::i32; 1609 if (!Reg) { 1610 unsigned StackOffset = State.AllocateStack(8, Align(8)); 1611 State.addLoc( 1612 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 1613 return false; 1614 } 1615 if (!State.AllocateReg(ArgGPRs)) 1616 State.AllocateStack(4, Align(4)); 1617 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 1618 return false; 1619 } 1620 1621 // Split arguments might be passed indirectly, so keep track of the pending 1622 // values. 1623 if (ArgFlags.isSplit() || !PendingLocs.empty()) { 1624 LocVT = XLenVT; 1625 LocInfo = CCValAssign::Indirect; 1626 PendingLocs.push_back( 1627 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 1628 PendingArgFlags.push_back(ArgFlags); 1629 if (!ArgFlags.isSplitEnd()) { 1630 return false; 1631 } 1632 } 1633 1634 // If the split argument only had two elements, it should be passed directly 1635 // in registers or on the stack. 1636 if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) { 1637 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 1638 // Apply the normal calling convention rules to the first half of the 1639 // split argument. 1640 CCValAssign VA = PendingLocs[0]; 1641 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 1642 PendingLocs.clear(); 1643 PendingArgFlags.clear(); 1644 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 1645 ArgFlags); 1646 } 1647 1648 // Allocate to a register if possible, or else a stack slot. 1649 Register Reg; 1650 if (ValVT == MVT::f32 && !UseGPRForF32) 1651 Reg = State.AllocateReg(ArgFPR32s, ArgFPR64s); 1652 else if (ValVT == MVT::f64 && !UseGPRForF64) 1653 Reg = State.AllocateReg(ArgFPR64s, ArgFPR32s); 1654 else 1655 Reg = State.AllocateReg(ArgGPRs); 1656 unsigned StackOffset = 1657 Reg ? 0 : State.AllocateStack(XLen / 8, Align(XLen / 8)); 1658 1659 // If we reach this point and PendingLocs is non-empty, we must be at the 1660 // end of a split argument that must be passed indirectly. 1661 if (!PendingLocs.empty()) { 1662 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 1663 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 1664 1665 for (auto &It : PendingLocs) { 1666 if (Reg) 1667 It.convertToReg(Reg); 1668 else 1669 It.convertToMem(StackOffset); 1670 State.addLoc(It); 1671 } 1672 PendingLocs.clear(); 1673 PendingArgFlags.clear(); 1674 return false; 1675 } 1676 1677 assert((!UseGPRForF32 || !UseGPRForF64 || LocVT == XLenVT) && 1678 "Expected an XLenVT at this stage"); 1679 1680 if (Reg) { 1681 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 1682 return false; 1683 } 1684 1685 // When an f32 or f64 is passed on the stack, no bit-conversion is needed. 1686 if (ValVT == MVT::f32 || ValVT == MVT::f64) { 1687 LocVT = ValVT; 1688 LocInfo = CCValAssign::Full; 1689 } 1690 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 1691 return false; 1692 } 1693 1694 void RISCVTargetLowering::analyzeInputArgs( 1695 MachineFunction &MF, CCState &CCInfo, 1696 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const { 1697 unsigned NumArgs = Ins.size(); 1698 FunctionType *FType = MF.getFunction().getFunctionType(); 1699 1700 for (unsigned i = 0; i != NumArgs; ++i) { 1701 MVT ArgVT = Ins[i].VT; 1702 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 1703 1704 Type *ArgTy = nullptr; 1705 if (IsRet) 1706 ArgTy = FType->getReturnType(); 1707 else if (Ins[i].isOrigArg()) 1708 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 1709 1710 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 1711 if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 1712 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy)) { 1713 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 1714 << EVT(ArgVT).getEVTString() << '\n'); 1715 llvm_unreachable(nullptr); 1716 } 1717 } 1718 } 1719 1720 void RISCVTargetLowering::analyzeOutputArgs( 1721 MachineFunction &MF, CCState &CCInfo, 1722 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 1723 CallLoweringInfo *CLI) const { 1724 unsigned NumArgs = Outs.size(); 1725 1726 for (unsigned i = 0; i != NumArgs; i++) { 1727 MVT ArgVT = Outs[i].VT; 1728 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 1729 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 1730 1731 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 1732 if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 1733 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) { 1734 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 1735 << EVT(ArgVT).getEVTString() << "\n"); 1736 llvm_unreachable(nullptr); 1737 } 1738 } 1739 } 1740 1741 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 1742 // values. 1743 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 1744 const CCValAssign &VA, const SDLoc &DL) { 1745 switch (VA.getLocInfo()) { 1746 default: 1747 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 1748 case CCValAssign::Full: 1749 break; 1750 case CCValAssign::BCvt: 1751 if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) { 1752 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 1753 break; 1754 } 1755 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 1756 break; 1757 } 1758 return Val; 1759 } 1760 1761 // The caller is responsible for loading the full value if the argument is 1762 // passed with CCValAssign::Indirect. 1763 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 1764 const CCValAssign &VA, const SDLoc &DL) { 1765 MachineFunction &MF = DAG.getMachineFunction(); 1766 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 1767 EVT LocVT = VA.getLocVT(); 1768 SDValue Val; 1769 const TargetRegisterClass *RC; 1770 1771 switch (LocVT.getSimpleVT().SimpleTy) { 1772 default: 1773 llvm_unreachable("Unexpected register type"); 1774 case MVT::i32: 1775 case MVT::i64: 1776 RC = &RISCV::GPRRegClass; 1777 break; 1778 case MVT::f32: 1779 RC = &RISCV::FPR32RegClass; 1780 break; 1781 case MVT::f64: 1782 RC = &RISCV::FPR64RegClass; 1783 break; 1784 } 1785 1786 Register VReg = RegInfo.createVirtualRegister(RC); 1787 RegInfo.addLiveIn(VA.getLocReg(), VReg); 1788 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 1789 1790 if (VA.getLocInfo() == CCValAssign::Indirect) 1791 return Val; 1792 1793 return convertLocVTToValVT(DAG, Val, VA, DL); 1794 } 1795 1796 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 1797 const CCValAssign &VA, const SDLoc &DL) { 1798 EVT LocVT = VA.getLocVT(); 1799 1800 switch (VA.getLocInfo()) { 1801 default: 1802 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 1803 case CCValAssign::Full: 1804 break; 1805 case CCValAssign::BCvt: 1806 if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) { 1807 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 1808 break; 1809 } 1810 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 1811 break; 1812 } 1813 return Val; 1814 } 1815 1816 // The caller is responsible for loading the full value if the argument is 1817 // passed with CCValAssign::Indirect. 1818 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 1819 const CCValAssign &VA, const SDLoc &DL) { 1820 MachineFunction &MF = DAG.getMachineFunction(); 1821 MachineFrameInfo &MFI = MF.getFrameInfo(); 1822 EVT LocVT = VA.getLocVT(); 1823 EVT ValVT = VA.getValVT(); 1824 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 1825 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8, 1826 VA.getLocMemOffset(), /*Immutable=*/true); 1827 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 1828 SDValue Val; 1829 1830 ISD::LoadExtType ExtType; 1831 switch (VA.getLocInfo()) { 1832 default: 1833 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 1834 case CCValAssign::Full: 1835 case CCValAssign::Indirect: 1836 case CCValAssign::BCvt: 1837 ExtType = ISD::NON_EXTLOAD; 1838 break; 1839 } 1840 Val = DAG.getExtLoad( 1841 ExtType, DL, LocVT, Chain, FIN, 1842 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 1843 return Val; 1844 } 1845 1846 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 1847 const CCValAssign &VA, const SDLoc &DL) { 1848 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 1849 "Unexpected VA"); 1850 MachineFunction &MF = DAG.getMachineFunction(); 1851 MachineFrameInfo &MFI = MF.getFrameInfo(); 1852 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 1853 1854 if (VA.isMemLoc()) { 1855 // f64 is passed on the stack. 1856 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 1857 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1858 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 1859 MachinePointerInfo::getFixedStack(MF, FI)); 1860 } 1861 1862 assert(VA.isRegLoc() && "Expected register VA assignment"); 1863 1864 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 1865 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 1866 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 1867 SDValue Hi; 1868 if (VA.getLocReg() == RISCV::X17) { 1869 // Second half of f64 is passed on the stack. 1870 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 1871 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1872 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 1873 MachinePointerInfo::getFixedStack(MF, FI)); 1874 } else { 1875 // Second half of f64 is passed in another GPR. 1876 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 1877 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 1878 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 1879 } 1880 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 1881 } 1882 1883 // FastCC has less than 1% performance improvement for some particular 1884 // benchmark. But theoretically, it may has benenfit for some cases. 1885 static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT, 1886 CCValAssign::LocInfo LocInfo, 1887 ISD::ArgFlagsTy ArgFlags, CCState &State) { 1888 1889 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 1890 // X5 and X6 might be used for save-restore libcall. 1891 static const MCPhysReg GPRList[] = { 1892 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 1893 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 1894 RISCV::X29, RISCV::X30, RISCV::X31}; 1895 if (unsigned Reg = State.AllocateReg(GPRList)) { 1896 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 1897 return false; 1898 } 1899 } 1900 1901 if (LocVT == MVT::f32) { 1902 static const MCPhysReg FPR32List[] = { 1903 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 1904 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 1905 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 1906 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 1907 if (unsigned Reg = State.AllocateReg(FPR32List)) { 1908 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 1909 return false; 1910 } 1911 } 1912 1913 if (LocVT == MVT::f64) { 1914 static const MCPhysReg FPR64List[] = { 1915 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 1916 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 1917 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 1918 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 1919 if (unsigned Reg = State.AllocateReg(FPR64List)) { 1920 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 1921 return false; 1922 } 1923 } 1924 1925 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 1926 unsigned Offset4 = State.AllocateStack(4, Align(4)); 1927 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 1928 return false; 1929 } 1930 1931 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 1932 unsigned Offset5 = State.AllocateStack(8, Align(8)); 1933 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 1934 return false; 1935 } 1936 1937 return true; // CC didn't match. 1938 } 1939 1940 // Transform physical registers into virtual registers. 1941 SDValue RISCVTargetLowering::LowerFormalArguments( 1942 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 1943 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1944 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1945 1946 switch (CallConv) { 1947 default: 1948 report_fatal_error("Unsupported calling convention"); 1949 case CallingConv::C: 1950 case CallingConv::Fast: 1951 break; 1952 } 1953 1954 MachineFunction &MF = DAG.getMachineFunction(); 1955 1956 const Function &Func = MF.getFunction(); 1957 if (Func.hasFnAttribute("interrupt")) { 1958 if (!Func.arg_empty()) 1959 report_fatal_error( 1960 "Functions with the interrupt attribute cannot have arguments!"); 1961 1962 StringRef Kind = 1963 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 1964 1965 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 1966 report_fatal_error( 1967 "Function interrupt attribute argument not supported!"); 1968 } 1969 1970 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 1971 MVT XLenVT = Subtarget.getXLenVT(); 1972 unsigned XLenInBytes = Subtarget.getXLen() / 8; 1973 // Used with vargs to acumulate store chains. 1974 std::vector<SDValue> OutChains; 1975 1976 // Assign locations to all of the incoming arguments. 1977 SmallVector<CCValAssign, 16> ArgLocs; 1978 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 1979 1980 if (CallConv == CallingConv::Fast) 1981 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_FastCC); 1982 else 1983 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false); 1984 1985 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 1986 CCValAssign &VA = ArgLocs[i]; 1987 SDValue ArgValue; 1988 // Passing f64 on RV32D with a soft float ABI must be handled as a special 1989 // case. 1990 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 1991 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 1992 else if (VA.isRegLoc()) 1993 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL); 1994 else 1995 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 1996 1997 if (VA.getLocInfo() == CCValAssign::Indirect) { 1998 // If the original argument was split and passed by reference (e.g. i128 1999 // on RV32), we need to load all parts of it here (using the same 2000 // address). 2001 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 2002 MachinePointerInfo())); 2003 unsigned ArgIndex = Ins[i].OrigArgIndex; 2004 assert(Ins[i].PartOffset == 0); 2005 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 2006 CCValAssign &PartVA = ArgLocs[i + 1]; 2007 unsigned PartOffset = Ins[i + 1].PartOffset; 2008 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, 2009 DAG.getIntPtrConstant(PartOffset, DL)); 2010 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 2011 MachinePointerInfo())); 2012 ++i; 2013 } 2014 continue; 2015 } 2016 InVals.push_back(ArgValue); 2017 } 2018 2019 if (IsVarArg) { 2020 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 2021 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 2022 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 2023 MachineFrameInfo &MFI = MF.getFrameInfo(); 2024 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 2025 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 2026 2027 // Offset of the first variable argument from stack pointer, and size of 2028 // the vararg save area. For now, the varargs save area is either zero or 2029 // large enough to hold a0-a7. 2030 int VaArgOffset, VarArgsSaveSize; 2031 2032 // If all registers are allocated, then all varargs must be passed on the 2033 // stack and we don't need to save any argregs. 2034 if (ArgRegs.size() == Idx) { 2035 VaArgOffset = CCInfo.getNextStackOffset(); 2036 VarArgsSaveSize = 0; 2037 } else { 2038 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 2039 VaArgOffset = -VarArgsSaveSize; 2040 } 2041 2042 // Record the frame index of the first variable argument 2043 // which is a value necessary to VASTART. 2044 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 2045 RVFI->setVarArgsFrameIndex(FI); 2046 2047 // If saving an odd number of registers then create an extra stack slot to 2048 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 2049 // offsets to even-numbered registered remain 2*XLEN-aligned. 2050 if (Idx % 2) { 2051 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 2052 VarArgsSaveSize += XLenInBytes; 2053 } 2054 2055 // Copy the integer registers that may have been used for passing varargs 2056 // to the vararg save area. 2057 for (unsigned I = Idx; I < ArgRegs.size(); 2058 ++I, VaArgOffset += XLenInBytes) { 2059 const Register Reg = RegInfo.createVirtualRegister(RC); 2060 RegInfo.addLiveIn(ArgRegs[I], Reg); 2061 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 2062 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 2063 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2064 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 2065 MachinePointerInfo::getFixedStack(MF, FI)); 2066 cast<StoreSDNode>(Store.getNode()) 2067 ->getMemOperand() 2068 ->setValue((Value *)nullptr); 2069 OutChains.push_back(Store); 2070 } 2071 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 2072 } 2073 2074 // All stores are grouped in one node to allow the matching between 2075 // the size of Ins and InVals. This only happens for vararg functions. 2076 if (!OutChains.empty()) { 2077 OutChains.push_back(Chain); 2078 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 2079 } 2080 2081 return Chain; 2082 } 2083 2084 /// isEligibleForTailCallOptimization - Check whether the call is eligible 2085 /// for tail call optimization. 2086 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 2087 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 2088 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 2089 const SmallVector<CCValAssign, 16> &ArgLocs) const { 2090 2091 auto &Callee = CLI.Callee; 2092 auto CalleeCC = CLI.CallConv; 2093 auto &Outs = CLI.Outs; 2094 auto &Caller = MF.getFunction(); 2095 auto CallerCC = Caller.getCallingConv(); 2096 2097 // Exception-handling functions need a special set of instructions to 2098 // indicate a return to the hardware. Tail-calling another function would 2099 // probably break this. 2100 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 2101 // should be expanded as new function attributes are introduced. 2102 if (Caller.hasFnAttribute("interrupt")) 2103 return false; 2104 2105 // Do not tail call opt if the stack is used to pass parameters. 2106 if (CCInfo.getNextStackOffset() != 0) 2107 return false; 2108 2109 // Do not tail call opt if any parameters need to be passed indirectly. 2110 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 2111 // passed indirectly. So the address of the value will be passed in a 2112 // register, or if not available, then the address is put on the stack. In 2113 // order to pass indirectly, space on the stack often needs to be allocated 2114 // in order to store the value. In this case the CCInfo.getNextStackOffset() 2115 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 2116 // are passed CCValAssign::Indirect. 2117 for (auto &VA : ArgLocs) 2118 if (VA.getLocInfo() == CCValAssign::Indirect) 2119 return false; 2120 2121 // Do not tail call opt if either caller or callee uses struct return 2122 // semantics. 2123 auto IsCallerStructRet = Caller.hasStructRetAttr(); 2124 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 2125 if (IsCallerStructRet || IsCalleeStructRet) 2126 return false; 2127 2128 // Externally-defined functions with weak linkage should not be 2129 // tail-called. The behaviour of branch instructions in this situation (as 2130 // used for tail calls) is implementation-defined, so we cannot rely on the 2131 // linker replacing the tail call with a return. 2132 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2133 const GlobalValue *GV = G->getGlobal(); 2134 if (GV->hasExternalWeakLinkage()) 2135 return false; 2136 } 2137 2138 // The callee has to preserve all registers the caller needs to preserve. 2139 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 2140 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2141 if (CalleeCC != CallerCC) { 2142 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2143 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2144 return false; 2145 } 2146 2147 // Byval parameters hand the function a pointer directly into the stack area 2148 // we want to reuse during a tail call. Working around this *is* possible 2149 // but less efficient and uglier in LowerCall. 2150 for (auto &Arg : Outs) 2151 if (Arg.Flags.isByVal()) 2152 return false; 2153 2154 return true; 2155 } 2156 2157 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 2158 // and output parameter nodes. 2159 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 2160 SmallVectorImpl<SDValue> &InVals) const { 2161 SelectionDAG &DAG = CLI.DAG; 2162 SDLoc &DL = CLI.DL; 2163 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2164 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2165 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2166 SDValue Chain = CLI.Chain; 2167 SDValue Callee = CLI.Callee; 2168 bool &IsTailCall = CLI.IsTailCall; 2169 CallingConv::ID CallConv = CLI.CallConv; 2170 bool IsVarArg = CLI.IsVarArg; 2171 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2172 MVT XLenVT = Subtarget.getXLenVT(); 2173 2174 MachineFunction &MF = DAG.getMachineFunction(); 2175 2176 // Analyze the operands of the call, assigning locations to each operand. 2177 SmallVector<CCValAssign, 16> ArgLocs; 2178 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2179 2180 if (CallConv == CallingConv::Fast) 2181 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_FastCC); 2182 else 2183 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI); 2184 2185 // Check if it's really possible to do a tail call. 2186 if (IsTailCall) 2187 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 2188 2189 if (IsTailCall) 2190 ++NumTailCalls; 2191 else if (CLI.CB && CLI.CB->isMustTailCall()) 2192 report_fatal_error("failed to perform tail call elimination on a call " 2193 "site marked musttail"); 2194 2195 // Get a count of how many bytes are to be pushed on the stack. 2196 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 2197 2198 // Create local copies for byval args 2199 SmallVector<SDValue, 8> ByValArgs; 2200 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 2201 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2202 if (!Flags.isByVal()) 2203 continue; 2204 2205 SDValue Arg = OutVals[i]; 2206 unsigned Size = Flags.getByValSize(); 2207 Align Alignment = Flags.getNonZeroByValAlign(); 2208 2209 int FI = 2210 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 2211 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2212 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 2213 2214 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 2215 /*IsVolatile=*/false, 2216 /*AlwaysInline=*/false, IsTailCall, 2217 MachinePointerInfo(), MachinePointerInfo()); 2218 ByValArgs.push_back(FIPtr); 2219 } 2220 2221 if (!IsTailCall) 2222 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 2223 2224 // Copy argument values to their designated locations. 2225 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 2226 SmallVector<SDValue, 8> MemOpChains; 2227 SDValue StackPtr; 2228 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 2229 CCValAssign &VA = ArgLocs[i]; 2230 SDValue ArgValue = OutVals[i]; 2231 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2232 2233 // Handle passing f64 on RV32D with a soft float ABI as a special case. 2234 bool IsF64OnRV32DSoftABI = 2235 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 2236 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 2237 SDValue SplitF64 = DAG.getNode( 2238 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 2239 SDValue Lo = SplitF64.getValue(0); 2240 SDValue Hi = SplitF64.getValue(1); 2241 2242 Register RegLo = VA.getLocReg(); 2243 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 2244 2245 if (RegLo == RISCV::X17) { 2246 // Second half of f64 is passed on the stack. 2247 // Work out the address of the stack slot. 2248 if (!StackPtr.getNode()) 2249 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 2250 // Emit the store. 2251 MemOpChains.push_back( 2252 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 2253 } else { 2254 // Second half of f64 is passed in another GPR. 2255 assert(RegLo < RISCV::X31 && "Invalid register pair"); 2256 Register RegHigh = RegLo + 1; 2257 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 2258 } 2259 continue; 2260 } 2261 2262 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 2263 // as any other MemLoc. 2264 2265 // Promote the value if needed. 2266 // For now, only handle fully promoted and indirect arguments. 2267 if (VA.getLocInfo() == CCValAssign::Indirect) { 2268 // Store the argument in a stack slot and pass its address. 2269 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT); 2270 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 2271 MemOpChains.push_back( 2272 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 2273 MachinePointerInfo::getFixedStack(MF, FI))); 2274 // If the original argument was split (e.g. i128), we need 2275 // to store all parts of it here (and pass just one address). 2276 unsigned ArgIndex = Outs[i].OrigArgIndex; 2277 assert(Outs[i].PartOffset == 0); 2278 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 2279 SDValue PartValue = OutVals[i + 1]; 2280 unsigned PartOffset = Outs[i + 1].PartOffset; 2281 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, 2282 DAG.getIntPtrConstant(PartOffset, DL)); 2283 MemOpChains.push_back( 2284 DAG.getStore(Chain, DL, PartValue, Address, 2285 MachinePointerInfo::getFixedStack(MF, FI))); 2286 ++i; 2287 } 2288 ArgValue = SpillSlot; 2289 } else { 2290 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL); 2291 } 2292 2293 // Use local copy if it is a byval arg. 2294 if (Flags.isByVal()) 2295 ArgValue = ByValArgs[j++]; 2296 2297 if (VA.isRegLoc()) { 2298 // Queue up the argument copies and emit them at the end. 2299 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 2300 } else { 2301 assert(VA.isMemLoc() && "Argument not register or memory"); 2302 assert(!IsTailCall && "Tail call not allowed if stack is used " 2303 "for passing parameters"); 2304 2305 // Work out the address of the stack slot. 2306 if (!StackPtr.getNode()) 2307 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 2308 SDValue Address = 2309 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 2310 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 2311 2312 // Emit the store. 2313 MemOpChains.push_back( 2314 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 2315 } 2316 } 2317 2318 // Join the stores, which are independent of one another. 2319 if (!MemOpChains.empty()) 2320 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2321 2322 SDValue Glue; 2323 2324 // Build a sequence of copy-to-reg nodes, chained and glued together. 2325 for (auto &Reg : RegsToPass) { 2326 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 2327 Glue = Chain.getValue(1); 2328 } 2329 2330 // Validate that none of the argument registers have been marked as 2331 // reserved, if so report an error. Do the same for the return address if this 2332 // is not a tailcall. 2333 validateCCReservedRegs(RegsToPass, MF); 2334 if (!IsTailCall && 2335 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 2336 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 2337 MF.getFunction(), 2338 "Return address register required, but has been reserved."}); 2339 2340 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 2341 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 2342 // split it and then direct call can be matched by PseudoCALL. 2343 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 2344 const GlobalValue *GV = S->getGlobal(); 2345 2346 unsigned OpFlags = RISCVII::MO_CALL; 2347 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 2348 OpFlags = RISCVII::MO_PLT; 2349 2350 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 2351 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2352 unsigned OpFlags = RISCVII::MO_CALL; 2353 2354 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 2355 nullptr)) 2356 OpFlags = RISCVII::MO_PLT; 2357 2358 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 2359 } 2360 2361 // The first call operand is the chain and the second is the target address. 2362 SmallVector<SDValue, 8> Ops; 2363 Ops.push_back(Chain); 2364 Ops.push_back(Callee); 2365 2366 // Add argument registers to the end of the list so that they are 2367 // known live into the call. 2368 for (auto &Reg : RegsToPass) 2369 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 2370 2371 if (!IsTailCall) { 2372 // Add a register mask operand representing the call-preserved registers. 2373 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 2374 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2375 assert(Mask && "Missing call preserved mask for calling convention"); 2376 Ops.push_back(DAG.getRegisterMask(Mask)); 2377 } 2378 2379 // Glue the call to the argument copies, if any. 2380 if (Glue.getNode()) 2381 Ops.push_back(Glue); 2382 2383 // Emit the call. 2384 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2385 2386 if (IsTailCall) { 2387 MF.getFrameInfo().setHasTailCall(); 2388 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 2389 } 2390 2391 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 2392 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 2393 Glue = Chain.getValue(1); 2394 2395 // Mark the end of the call, which is glued to the call itself. 2396 Chain = DAG.getCALLSEQ_END(Chain, 2397 DAG.getConstant(NumBytes, DL, PtrVT, true), 2398 DAG.getConstant(0, DL, PtrVT, true), 2399 Glue, DL); 2400 Glue = Chain.getValue(1); 2401 2402 // Assign locations to each value returned by this call. 2403 SmallVector<CCValAssign, 16> RVLocs; 2404 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 2405 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true); 2406 2407 // Copy all of the result registers out of their specified physreg. 2408 for (auto &VA : RVLocs) { 2409 // Copy the value out 2410 SDValue RetValue = 2411 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 2412 // Glue the RetValue to the end of the call sequence 2413 Chain = RetValue.getValue(1); 2414 Glue = RetValue.getValue(2); 2415 2416 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 2417 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 2418 SDValue RetValue2 = 2419 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 2420 Chain = RetValue2.getValue(1); 2421 Glue = RetValue2.getValue(2); 2422 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 2423 RetValue2); 2424 } 2425 2426 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL); 2427 2428 InVals.push_back(RetValue); 2429 } 2430 2431 return Chain; 2432 } 2433 2434 bool RISCVTargetLowering::CanLowerReturn( 2435 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 2436 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 2437 SmallVector<CCValAssign, 16> RVLocs; 2438 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2439 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 2440 MVT VT = Outs[i].VT; 2441 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 2442 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 2443 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 2444 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr)) 2445 return false; 2446 } 2447 return true; 2448 } 2449 2450 SDValue 2451 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2452 bool IsVarArg, 2453 const SmallVectorImpl<ISD::OutputArg> &Outs, 2454 const SmallVectorImpl<SDValue> &OutVals, 2455 const SDLoc &DL, SelectionDAG &DAG) const { 2456 const MachineFunction &MF = DAG.getMachineFunction(); 2457 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 2458 2459 // Stores the assignment of the return value to a location. 2460 SmallVector<CCValAssign, 16> RVLocs; 2461 2462 // Info about the registers and stack slot. 2463 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2464 *DAG.getContext()); 2465 2466 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 2467 nullptr); 2468 2469 SDValue Glue; 2470 SmallVector<SDValue, 4> RetOps(1, Chain); 2471 2472 // Copy the result values into the output registers. 2473 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 2474 SDValue Val = OutVals[i]; 2475 CCValAssign &VA = RVLocs[i]; 2476 assert(VA.isRegLoc() && "Can only return in registers!"); 2477 2478 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 2479 // Handle returning f64 on RV32D with a soft float ABI. 2480 assert(VA.isRegLoc() && "Expected return via registers"); 2481 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 2482 DAG.getVTList(MVT::i32, MVT::i32), Val); 2483 SDValue Lo = SplitF64.getValue(0); 2484 SDValue Hi = SplitF64.getValue(1); 2485 Register RegLo = VA.getLocReg(); 2486 assert(RegLo < RISCV::X31 && "Invalid register pair"); 2487 Register RegHi = RegLo + 1; 2488 2489 if (STI.isRegisterReservedByUser(RegLo) || 2490 STI.isRegisterReservedByUser(RegHi)) 2491 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 2492 MF.getFunction(), 2493 "Return value register required, but has been reserved."}); 2494 2495 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 2496 Glue = Chain.getValue(1); 2497 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 2498 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 2499 Glue = Chain.getValue(1); 2500 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 2501 } else { 2502 // Handle a 'normal' return. 2503 Val = convertValVTToLocVT(DAG, Val, VA, DL); 2504 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 2505 2506 if (STI.isRegisterReservedByUser(VA.getLocReg())) 2507 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 2508 MF.getFunction(), 2509 "Return value register required, but has been reserved."}); 2510 2511 // Guarantee that all emitted copies are stuck together. 2512 Glue = Chain.getValue(1); 2513 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2514 } 2515 } 2516 2517 RetOps[0] = Chain; // Update chain. 2518 2519 // Add the glue node if we have it. 2520 if (Glue.getNode()) { 2521 RetOps.push_back(Glue); 2522 } 2523 2524 // Interrupt service routines use different return instructions. 2525 const Function &Func = DAG.getMachineFunction().getFunction(); 2526 if (Func.hasFnAttribute("interrupt")) { 2527 if (!Func.getReturnType()->isVoidTy()) 2528 report_fatal_error( 2529 "Functions with the interrupt attribute must have void return type!"); 2530 2531 MachineFunction &MF = DAG.getMachineFunction(); 2532 StringRef Kind = 2533 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 2534 2535 unsigned RetOpc; 2536 if (Kind == "user") 2537 RetOpc = RISCVISD::URET_FLAG; 2538 else if (Kind == "supervisor") 2539 RetOpc = RISCVISD::SRET_FLAG; 2540 else 2541 RetOpc = RISCVISD::MRET_FLAG; 2542 2543 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 2544 } 2545 2546 return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps); 2547 } 2548 2549 void RISCVTargetLowering::validateCCReservedRegs( 2550 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 2551 MachineFunction &MF) const { 2552 const Function &F = MF.getFunction(); 2553 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 2554 2555 if (std::any_of(std::begin(Regs), std::end(Regs), [&STI](auto Reg) { 2556 return STI.isRegisterReservedByUser(Reg.first); 2557 })) 2558 F.getContext().diagnose(DiagnosticInfoUnsupported{ 2559 F, "Argument register required, but has been reserved."}); 2560 } 2561 2562 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2563 return CI->isTailCall(); 2564 } 2565 2566 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 2567 switch ((RISCVISD::NodeType)Opcode) { 2568 case RISCVISD::FIRST_NUMBER: 2569 break; 2570 case RISCVISD::RET_FLAG: 2571 return "RISCVISD::RET_FLAG"; 2572 case RISCVISD::URET_FLAG: 2573 return "RISCVISD::URET_FLAG"; 2574 case RISCVISD::SRET_FLAG: 2575 return "RISCVISD::SRET_FLAG"; 2576 case RISCVISD::MRET_FLAG: 2577 return "RISCVISD::MRET_FLAG"; 2578 case RISCVISD::CALL: 2579 return "RISCVISD::CALL"; 2580 case RISCVISD::SELECT_CC: 2581 return "RISCVISD::SELECT_CC"; 2582 case RISCVISD::BuildPairF64: 2583 return "RISCVISD::BuildPairF64"; 2584 case RISCVISD::SplitF64: 2585 return "RISCVISD::SplitF64"; 2586 case RISCVISD::TAIL: 2587 return "RISCVISD::TAIL"; 2588 case RISCVISD::SLLW: 2589 return "RISCVISD::SLLW"; 2590 case RISCVISD::SRAW: 2591 return "RISCVISD::SRAW"; 2592 case RISCVISD::SRLW: 2593 return "RISCVISD::SRLW"; 2594 case RISCVISD::DIVW: 2595 return "RISCVISD::DIVW"; 2596 case RISCVISD::DIVUW: 2597 return "RISCVISD::DIVUW"; 2598 case RISCVISD::REMUW: 2599 return "RISCVISD::REMUW"; 2600 case RISCVISD::FMV_W_X_RV64: 2601 return "RISCVISD::FMV_W_X_RV64"; 2602 case RISCVISD::FMV_X_ANYEXTW_RV64: 2603 return "RISCVISD::FMV_X_ANYEXTW_RV64"; 2604 case RISCVISD::READ_CYCLE_WIDE: 2605 return "RISCVISD::READ_CYCLE_WIDE"; 2606 } 2607 return nullptr; 2608 } 2609 2610 /// getConstraintType - Given a constraint letter, return the type of 2611 /// constraint it is for this target. 2612 RISCVTargetLowering::ConstraintType 2613 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 2614 if (Constraint.size() == 1) { 2615 switch (Constraint[0]) { 2616 default: 2617 break; 2618 case 'f': 2619 return C_RegisterClass; 2620 case 'I': 2621 case 'J': 2622 case 'K': 2623 return C_Immediate; 2624 case 'A': 2625 return C_Memory; 2626 } 2627 } 2628 return TargetLowering::getConstraintType(Constraint); 2629 } 2630 2631 std::pair<unsigned, const TargetRegisterClass *> 2632 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 2633 StringRef Constraint, 2634 MVT VT) const { 2635 // First, see if this is a constraint that directly corresponds to a 2636 // RISCV register class. 2637 if (Constraint.size() == 1) { 2638 switch (Constraint[0]) { 2639 case 'r': 2640 return std::make_pair(0U, &RISCV::GPRRegClass); 2641 case 'f': 2642 if (Subtarget.hasStdExtF() && VT == MVT::f32) 2643 return std::make_pair(0U, &RISCV::FPR32RegClass); 2644 if (Subtarget.hasStdExtD() && VT == MVT::f64) 2645 return std::make_pair(0U, &RISCV::FPR64RegClass); 2646 break; 2647 default: 2648 break; 2649 } 2650 } 2651 2652 // Clang will correctly decode the usage of register name aliases into their 2653 // official names. However, other frontends like `rustc` do not. This allows 2654 // users of these frontends to use the ABI names for registers in LLVM-style 2655 // register constraints. 2656 Register XRegFromAlias = StringSwitch<Register>(Constraint.lower()) 2657 .Case("{zero}", RISCV::X0) 2658 .Case("{ra}", RISCV::X1) 2659 .Case("{sp}", RISCV::X2) 2660 .Case("{gp}", RISCV::X3) 2661 .Case("{tp}", RISCV::X4) 2662 .Case("{t0}", RISCV::X5) 2663 .Case("{t1}", RISCV::X6) 2664 .Case("{t2}", RISCV::X7) 2665 .Cases("{s0}", "{fp}", RISCV::X8) 2666 .Case("{s1}", RISCV::X9) 2667 .Case("{a0}", RISCV::X10) 2668 .Case("{a1}", RISCV::X11) 2669 .Case("{a2}", RISCV::X12) 2670 .Case("{a3}", RISCV::X13) 2671 .Case("{a4}", RISCV::X14) 2672 .Case("{a5}", RISCV::X15) 2673 .Case("{a6}", RISCV::X16) 2674 .Case("{a7}", RISCV::X17) 2675 .Case("{s2}", RISCV::X18) 2676 .Case("{s3}", RISCV::X19) 2677 .Case("{s4}", RISCV::X20) 2678 .Case("{s5}", RISCV::X21) 2679 .Case("{s6}", RISCV::X22) 2680 .Case("{s7}", RISCV::X23) 2681 .Case("{s8}", RISCV::X24) 2682 .Case("{s9}", RISCV::X25) 2683 .Case("{s10}", RISCV::X26) 2684 .Case("{s11}", RISCV::X27) 2685 .Case("{t3}", RISCV::X28) 2686 .Case("{t4}", RISCV::X29) 2687 .Case("{t5}", RISCV::X30) 2688 .Case("{t6}", RISCV::X31) 2689 .Default(RISCV::NoRegister); 2690 if (XRegFromAlias != RISCV::NoRegister) 2691 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 2692 2693 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 2694 // TableGen record rather than the AsmName to choose registers for InlineAsm 2695 // constraints, plus we want to match those names to the widest floating point 2696 // register type available, manually select floating point registers here. 2697 // 2698 // The second case is the ABI name of the register, so that frontends can also 2699 // use the ABI names in register constraint lists. 2700 if (Subtarget.hasStdExtF() || Subtarget.hasStdExtD()) { 2701 std::pair<Register, Register> FReg = 2702 StringSwitch<std::pair<Register, Register>>(Constraint.lower()) 2703 .Cases("{f0}", "{ft0}", {RISCV::F0_F, RISCV::F0_D}) 2704 .Cases("{f1}", "{ft1}", {RISCV::F1_F, RISCV::F1_D}) 2705 .Cases("{f2}", "{ft2}", {RISCV::F2_F, RISCV::F2_D}) 2706 .Cases("{f3}", "{ft3}", {RISCV::F3_F, RISCV::F3_D}) 2707 .Cases("{f4}", "{ft4}", {RISCV::F4_F, RISCV::F4_D}) 2708 .Cases("{f5}", "{ft5}", {RISCV::F5_F, RISCV::F5_D}) 2709 .Cases("{f6}", "{ft6}", {RISCV::F6_F, RISCV::F6_D}) 2710 .Cases("{f7}", "{ft7}", {RISCV::F7_F, RISCV::F7_D}) 2711 .Cases("{f8}", "{fs0}", {RISCV::F8_F, RISCV::F8_D}) 2712 .Cases("{f9}", "{fs1}", {RISCV::F9_F, RISCV::F9_D}) 2713 .Cases("{f10}", "{fa0}", {RISCV::F10_F, RISCV::F10_D}) 2714 .Cases("{f11}", "{fa1}", {RISCV::F11_F, RISCV::F11_D}) 2715 .Cases("{f12}", "{fa2}", {RISCV::F12_F, RISCV::F12_D}) 2716 .Cases("{f13}", "{fa3}", {RISCV::F13_F, RISCV::F13_D}) 2717 .Cases("{f14}", "{fa4}", {RISCV::F14_F, RISCV::F14_D}) 2718 .Cases("{f15}", "{fa5}", {RISCV::F15_F, RISCV::F15_D}) 2719 .Cases("{f16}", "{fa6}", {RISCV::F16_F, RISCV::F16_D}) 2720 .Cases("{f17}", "{fa7}", {RISCV::F17_F, RISCV::F17_D}) 2721 .Cases("{f18}", "{fs2}", {RISCV::F18_F, RISCV::F18_D}) 2722 .Cases("{f19}", "{fs3}", {RISCV::F19_F, RISCV::F19_D}) 2723 .Cases("{f20}", "{fs4}", {RISCV::F20_F, RISCV::F20_D}) 2724 .Cases("{f21}", "{fs5}", {RISCV::F21_F, RISCV::F21_D}) 2725 .Cases("{f22}", "{fs6}", {RISCV::F22_F, RISCV::F22_D}) 2726 .Cases("{f23}", "{fs7}", {RISCV::F23_F, RISCV::F23_D}) 2727 .Cases("{f24}", "{fs8}", {RISCV::F24_F, RISCV::F24_D}) 2728 .Cases("{f25}", "{fs9}", {RISCV::F25_F, RISCV::F25_D}) 2729 .Cases("{f26}", "{fs10}", {RISCV::F26_F, RISCV::F26_D}) 2730 .Cases("{f27}", "{fs11}", {RISCV::F27_F, RISCV::F27_D}) 2731 .Cases("{f28}", "{ft8}", {RISCV::F28_F, RISCV::F28_D}) 2732 .Cases("{f29}", "{ft9}", {RISCV::F29_F, RISCV::F29_D}) 2733 .Cases("{f30}", "{ft10}", {RISCV::F30_F, RISCV::F30_D}) 2734 .Cases("{f31}", "{ft11}", {RISCV::F31_F, RISCV::F31_D}) 2735 .Default({RISCV::NoRegister, RISCV::NoRegister}); 2736 if (FReg.first != RISCV::NoRegister) 2737 return Subtarget.hasStdExtD() 2738 ? std::make_pair(FReg.second, &RISCV::FPR64RegClass) 2739 : std::make_pair(FReg.first, &RISCV::FPR32RegClass); 2740 } 2741 2742 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 2743 } 2744 2745 unsigned 2746 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 2747 // Currently only support length 1 constraints. 2748 if (ConstraintCode.size() == 1) { 2749 switch (ConstraintCode[0]) { 2750 case 'A': 2751 return InlineAsm::Constraint_A; 2752 default: 2753 break; 2754 } 2755 } 2756 2757 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 2758 } 2759 2760 void RISCVTargetLowering::LowerAsmOperandForConstraint( 2761 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 2762 SelectionDAG &DAG) const { 2763 // Currently only support length 1 constraints. 2764 if (Constraint.length() == 1) { 2765 switch (Constraint[0]) { 2766 case 'I': 2767 // Validate & create a 12-bit signed immediate operand. 2768 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2769 uint64_t CVal = C->getSExtValue(); 2770 if (isInt<12>(CVal)) 2771 Ops.push_back( 2772 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 2773 } 2774 return; 2775 case 'J': 2776 // Validate & create an integer zero operand. 2777 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 2778 if (C->getZExtValue() == 0) 2779 Ops.push_back( 2780 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 2781 return; 2782 case 'K': 2783 // Validate & create a 5-bit unsigned immediate operand. 2784 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2785 uint64_t CVal = C->getZExtValue(); 2786 if (isUInt<5>(CVal)) 2787 Ops.push_back( 2788 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 2789 } 2790 return; 2791 default: 2792 break; 2793 } 2794 } 2795 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 2796 } 2797 2798 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 2799 Instruction *Inst, 2800 AtomicOrdering Ord) const { 2801 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 2802 return Builder.CreateFence(Ord); 2803 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 2804 return Builder.CreateFence(AtomicOrdering::Release); 2805 return nullptr; 2806 } 2807 2808 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 2809 Instruction *Inst, 2810 AtomicOrdering Ord) const { 2811 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 2812 return Builder.CreateFence(AtomicOrdering::Acquire); 2813 return nullptr; 2814 } 2815 2816 TargetLowering::AtomicExpansionKind 2817 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 2818 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 2819 // point operations can't be used in an lr/sc sequence without breaking the 2820 // forward-progress guarantee. 2821 if (AI->isFloatingPointOperation()) 2822 return AtomicExpansionKind::CmpXChg; 2823 2824 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 2825 if (Size == 8 || Size == 16) 2826 return AtomicExpansionKind::MaskedIntrinsic; 2827 return AtomicExpansionKind::None; 2828 } 2829 2830 static Intrinsic::ID 2831 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 2832 if (XLen == 32) { 2833 switch (BinOp) { 2834 default: 2835 llvm_unreachable("Unexpected AtomicRMW BinOp"); 2836 case AtomicRMWInst::Xchg: 2837 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 2838 case AtomicRMWInst::Add: 2839 return Intrinsic::riscv_masked_atomicrmw_add_i32; 2840 case AtomicRMWInst::Sub: 2841 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 2842 case AtomicRMWInst::Nand: 2843 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 2844 case AtomicRMWInst::Max: 2845 return Intrinsic::riscv_masked_atomicrmw_max_i32; 2846 case AtomicRMWInst::Min: 2847 return Intrinsic::riscv_masked_atomicrmw_min_i32; 2848 case AtomicRMWInst::UMax: 2849 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 2850 case AtomicRMWInst::UMin: 2851 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 2852 } 2853 } 2854 2855 if (XLen == 64) { 2856 switch (BinOp) { 2857 default: 2858 llvm_unreachable("Unexpected AtomicRMW BinOp"); 2859 case AtomicRMWInst::Xchg: 2860 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 2861 case AtomicRMWInst::Add: 2862 return Intrinsic::riscv_masked_atomicrmw_add_i64; 2863 case AtomicRMWInst::Sub: 2864 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 2865 case AtomicRMWInst::Nand: 2866 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 2867 case AtomicRMWInst::Max: 2868 return Intrinsic::riscv_masked_atomicrmw_max_i64; 2869 case AtomicRMWInst::Min: 2870 return Intrinsic::riscv_masked_atomicrmw_min_i64; 2871 case AtomicRMWInst::UMax: 2872 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 2873 case AtomicRMWInst::UMin: 2874 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 2875 } 2876 } 2877 2878 llvm_unreachable("Unexpected XLen\n"); 2879 } 2880 2881 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 2882 IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 2883 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 2884 unsigned XLen = Subtarget.getXLen(); 2885 Value *Ordering = 2886 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 2887 Type *Tys[] = {AlignedAddr->getType()}; 2888 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 2889 AI->getModule(), 2890 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 2891 2892 if (XLen == 64) { 2893 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 2894 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 2895 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 2896 } 2897 2898 Value *Result; 2899 2900 // Must pass the shift amount needed to sign extend the loaded value prior 2901 // to performing a signed comparison for min/max. ShiftAmt is the number of 2902 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 2903 // is the number of bits to left+right shift the value in order to 2904 // sign-extend. 2905 if (AI->getOperation() == AtomicRMWInst::Min || 2906 AI->getOperation() == AtomicRMWInst::Max) { 2907 const DataLayout &DL = AI->getModule()->getDataLayout(); 2908 unsigned ValWidth = 2909 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 2910 Value *SextShamt = 2911 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 2912 Result = Builder.CreateCall(LrwOpScwLoop, 2913 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 2914 } else { 2915 Result = 2916 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 2917 } 2918 2919 if (XLen == 64) 2920 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 2921 return Result; 2922 } 2923 2924 TargetLowering::AtomicExpansionKind 2925 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 2926 AtomicCmpXchgInst *CI) const { 2927 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 2928 if (Size == 8 || Size == 16) 2929 return AtomicExpansionKind::MaskedIntrinsic; 2930 return AtomicExpansionKind::None; 2931 } 2932 2933 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 2934 IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 2935 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 2936 unsigned XLen = Subtarget.getXLen(); 2937 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 2938 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 2939 if (XLen == 64) { 2940 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 2941 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 2942 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 2943 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 2944 } 2945 Type *Tys[] = {AlignedAddr->getType()}; 2946 Function *MaskedCmpXchg = 2947 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 2948 Value *Result = Builder.CreateCall( 2949 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 2950 if (XLen == 64) 2951 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 2952 return Result; 2953 } 2954 2955 Register RISCVTargetLowering::getExceptionPointerRegister( 2956 const Constant *PersonalityFn) const { 2957 return RISCV::X10; 2958 } 2959 2960 Register RISCVTargetLowering::getExceptionSelectorRegister( 2961 const Constant *PersonalityFn) const { 2962 return RISCV::X11; 2963 } 2964 2965 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 2966 // Return false to suppress the unnecessary extensions if the LibCall 2967 // arguments or return value is f32 type for LP64 ABI. 2968 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 2969 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 2970 return false; 2971 2972 return true; 2973 } 2974 2975 #define GET_REGISTER_MATCHER 2976 #include "RISCVGenAsmMatcher.inc" 2977 2978 Register 2979 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 2980 const MachineFunction &MF) const { 2981 Register Reg = MatchRegisterAltName(RegName); 2982 if (Reg == RISCV::NoRegister) 2983 Reg = MatchRegisterName(RegName); 2984 if (Reg == RISCV::NoRegister) 2985 report_fatal_error( 2986 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 2987 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 2988 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 2989 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 2990 StringRef(RegName) + "\".")); 2991 return Reg; 2992 } 2993