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