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