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