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