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